Solr java客户端solrJ的CRUD操作

xiaoxiao2021-02-28  114

需要的jar包

代码

public class SolrTest { @After public void tearDown() throws Exception { } //添加索引 @Test public void testAdd() throws SolrServerException, IOException { //创建和solr服务器的连接 String url="http://localhost:8080/solr"; SolrServer solrServer=new HttpSolrServer(url); //创建一个文档对象 SolrInputDocument document = new SolrInputDocument(); document.addField("id","solr001"); document.addField("product_name", "魅族手机"); document.addField("product_price", 3000); solrServer.add(document); solrServer.commit(); } //根据id删除 @Test public void deleteDocumentById() throws Exception{ //创建和solr服务器的连接 String url="http://localhost:8080/solr"; SolrServer solrServer=new HttpSolrServer(url); solrServer.deleteById("solr001"); solrServer.commit(); } //删除全部 @Test public void deleteAll()throws Exception{ //创建和solr服务器的连接 String url="http://localhost:8080/solr"; SolrServer solrServer=new HttpSolrServer(url); solrServer.deleteByQuery("*:*"); solrServer.commit(); } //更新和添加一样 略 @Test public void testSearch() throws Exception{ //创建和solr服务器的连接 String url="http://localhost:8080/solr"; SolrServer solrServer=new HttpSolrServer(url); //创建查询对象 SolrQuery是SolrParams 的子类 SolrQuery solrQuery = new SolrQuery(); //solrQuery.set("q", "*:*"); //solrQuery.setQuery("*:*"); //设置默认搜索域 solrQuery.set("df", "product_name"); //设置查询条件 solrQuery.setQuery("手机"); //设置过滤条件 solrQuery.addFilterQuery("product_price:[100 TO 6600]"); //设置排序条件 solrQuery.setSort("product_price", ORDER.asc); //设置分页条件 solrQuery.setStart(0); solrQuery.setRows(10); //设置显示的域 solrQuery.setFields("id","product_name","product_price"); solrQuery.setHighlight(true); solrQuery.addHighlightField("product_name"); solrQuery.setHighlightSimplePre("<span style='color:red'>"); solrQuery.setHighlightSimplePost("</span>"); //执行查询 QueryResponse queryResponse = solrServer.query(solrQuery); //取文档列表 SolrDocumentList results = queryResponse.getResults(); System.out.println("查询结果总量:"+results.getNumFound()); //遍历查询结果 for (SolrDocument solrDocument : results) { System.out.println(solrDocument.get("id")); System.out.println(solrDocument.get("product_name")); System.out.println(solrDocument.get("product_price")); System.out.println(solrDocument.get("product_catalog_name")); System.out.println(solrDocument.get("product_picture")); Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting(); //key 域名 Map<String, List<String>> map = highlighting.get(solrDocument.get("id")); List<String> list = map.get("product_name"); System.out.println(list.get(0)); System.out.println("--------------"); } } }
转载请注明原文地址: https://www.6miu.com/read-44476.html

最新回复(0)