4.Solr使用Java进行索引库增删改查

环境:Tomcat8部署Solr7.5

使用Java对Solr进行索引库操作,需添入solrJ的jar包,如果是Maven进行项目管理,那是极好的,添加依赖


<!-- https://mvnrepository.com/artifact/org.apache.solr/solr-solrj -->
<dependency>
    <groupId>org.apache.solr</groupId>
    <artifactId>solr-solrj</artifactId>
    <version>7.5.0</version>
</dependency>

但如果没有使用Maven管理,那就很坑了,需要手动添加一些依赖的Jar包,这个没用使用Maven的项目,我只能挨个下载并替换成最新版,老版本不行的,同时把老版本删除

地址

1.查,进行一个简单的查询测试,查询一下Solr索引库的数据条数

// 指定Solr服务指定地址,后期从参数中配置获取
		String SOLR_URL = "http://xxxx:8080/solr/core1/";
		HttpSolrClient solrClient = new HttpSolrClient.Builder(SOLR_URL).withConnectionTimeout(10000).withSocketTimeout(60000).build();
		// 创建Solr查询语句
		SolrQuery solrQuery = new SolrQuery();
		// 设置查询条件
		solrQuery.setQuery("bi_menu_TITLE:"+bi_menu_TITLE);//设置查询关键字q
//		solrQuery.setFields("id,item_name");//显示的字段f
//		solrQuery.setSort("id",SolrQuery.ORDER.desc);//按照id排序
//		solrQuery.setStart(0);//offset
//		solrQuery.setRows(5);//limit
		// 执行查询(传入core核)
		QueryResponse response = solrClient.query(solrQuery);
		// 获取文档列表
		SolrDocumentList documentList = response.getResults();
		// 获取总记录数
		long numFound = documentList.getNumFound();
		System.out.println("总记录数:"+numFound);

查询条件与solr页面功能相同

2.增/改,在Solr索引库中,如果ID不存在则新增,存在则更新(改),id是每条数据必填项,也必须是唯一的,

批量新增则构建List<SolrInputDocument>,单条使用SolrInputDocument即可

// solr服务器地址
		String SOLR_URL = "http://xxxx:8080/solr/core1/";
		HttpSolrClient solrClient = new HttpSolrClient.Builder(SOLR_URL).withConnectionTimeout(10000).withSocketTimeout(60000).build();
		DBConnection dbc = DataSource.getDBConnection(DataSource.CORE_DATASOURCE);
		DDProxy ddp = new DDProxy(dbc, "CORE_MENU");
		List<Map<String,String>> menuList = ddp.getDBQuery().query("CORE_MENU.solr.query", null);
		List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
		for(Map<String,String> menu : menuList) {
			// solr添加数据即添加文档doc,构造一篇文档
			SolrInputDocument document = new SolrInputDocument();
			// 向doc中添加字段,需与managed-schema中field(域)对应,其中id必需传入,且不能相同
			document.addField("id",menu.get("MENU_CODE"));
			document.addField("APPL_CODE",menu.get("APPL_CODE"));
			document.addField("MENU_CODE",menu.get("MENU_CODE"));
			document.addField("TITLE",menu.get("TITLE"));
			document.addField("URL",menu.get("URL"));
			docs.add(document);
		}
		solrClient.add(docs);
		solrClient.commit();

3.删,deleteByQuery为索引库中需要删除的数据条件

// solr服务器地址
		String SOLR_URL = "http://xxxx:8080/solr/core1/";
		HttpSolrClient solrClient = new HttpSolrClient.Builder(SOLR_URL).withConnectionTimeout(10000).withSocketTimeout(60000).build();
		// 先清空索引表
		solrClient.deleteByQuery("*:*");//删除条件
		solrClient.commit();
		

solrClient.deleteById(param.get("id").toString());

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值