java中solr的使用

solr在java程序中的应用

  1.导入jar包   

<!-- solr客户端 -->
	<dependency>
	<groupId>org.apache.solr</groupId>
	<artifactId>solr-solrj</artifactId>
	</dependency>
 程序代码
//增加索引库
	@Test
  public void addDocument() throws Exception{
	  //创建连接
	  SolrServer solrServer = new HttpSolrServer("http://192.168.21.198:8080/solr/");
	  //创建文档对象
	  SolrInputDocument doucument= new SolrInputDocument();
	  doucument.addField("id", "917770");
	  doucument.addField("item_title", "华为 P6-C00 电信3G手机(粉色) CDMA2000/GSM 双模双待双通");
	  doucument.addField("item_price", 134900);
	  //把文档对象写入文档里
	  solrServer.add(doucument);
	  //提交
	  solrServer.commit();
  }
	//删除索引库
	@Test
	public void delDocument() throws Exception{
		//创建连接
		  SolrServer solrServer = new HttpSolrServer("http://192.168.21.198:8080/solr/");
		 // solrServer.deleteById("");
		  solrServer.deleteByQuery("*:*");
		  solrServer.commit();
	}
	//查询
	@Test
	public void queryDocument() throws Exception{
		//创建连接
		  SolrServer solrServer = new HttpSolrServer("http://192.168.21.198:8080/solr/");
		  //创建一个查询对象
		  SolrQuery query= new SolrQuery();
		  query.setQuery("*:*");
		  query.setStart(20);
		  query.setRows(50);
		  //执行查询
		  QueryResponse response = solrServer.query(query);
		  
		  //取查询结果
		  SolrDocumentList documentList = response.getResults();
		  System.out.println("查询的条数为:"+documentList.getNumFound());
		  for(SolrDocument solrDocument: documentList){
			  System.out.println(solrDocument.get("id"));
			  System.out.println(solrDocument.get("item_title"));
			  System.out.println(solrDocument.get("item_price"));
			  System.out.println(solrDocument.get("item_image"));
			
			  
		  }
	}


相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页