一、导入依赖
导入Solr源码包dist
文件夹下的solr-solrj-6.6.2.jar
以及solrj-lib
文件夹下的所有包到项目中。除此之外,还要加上log4j
包和junit
测试包。
二、添加/更新数据
Solrj的使用十分简单,下面是一个添加数据的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Test public void testAdd() throws Exception { String baseURL = "http://localhost:8080/solr/core1";
HttpSolrClient solrClient = new HttpSolrClient(baseURL);
SolrInputDocument doc = new SolrInputDocument(); doc.addField("id", "10086"); doc.addField("author", "jitwxs"); solrClient.add(doc, 1000); }
|
(1)BaseURL就是Solr的首页地址和核:
(2)创建一个SolrClient
,其中HttpSolrClient
是单机版,CloudSolrClient
是集群版。
(3)可以设置提交时间自动提交,也可以手动提交solrClient.commit();
(4)这种初始化SolrClient
的方式在Solr 7.0
中被废弃,改为:
1 2 3 4
| HttpSolrClient solrClient = new HttpSolrClient.Builder(BASE_URL) .withConnectionTimeout(10000) .withSocketTimeout(60000) .build();
|
查看Solr后台,发现数据已经被添加了:
三、删除数据
删除十分简单,不再具体演示,给出相关API:
1 2 3 4 5 6 7 8 9 10 11 12 13
| solrClient.deleteById("10086");
List<String> ids = new ArrayList<>(); ids.add("1"); solrClient.deleteById(ids, 1000);
solrClient.deleteByQuery("*:*");
solrClient.deleteByQuery("core1", "id:10086", 1000);
|
四、查询数据
业务需求:
-
默认域为item_title
-
关键词:手机
-
价格:5k以上
-
价格降序
-
分页:第1页,每页10条
-
高亮:红色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| @Test public void testQuery() throws Exception { String baseURL = "http://localhost:8080/solr/core1";
SolrClient HttpSolrClient = new HttpSolrClient(baseURL);
SolrQuery solrQuery = new SolrQuery(); solrQuery.set("df", "item_title"); solrQuery.set("q", "手机"); solrQuery.set("fq", "item_price:[5000 TO *]"); solrQuery.addSort("item_price", ORDER.desc); solrQuery.setStart(1); solrQuery.setRows(5); solrQuery.setHighlight(true); solrQuery.addHighlightField("item_title"); solrQuery.setHighlightSimplePre("<span style='color:red'>"); solrQuery.setHighlightSimplePost("</span>"); QueryResponse response = solrClient.query(solrQuery); SolrDocumentList docs = response.getResults(); Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); long numFound = docs.getNumFound(); System.out.println("共查到:" + numFound + "条数据"); for(SolrDocument doc : docs) { System.out.println("id:" + doc.get("id")); System.out.println("sell_point:" +doc.get("item_sell_point")); System.out.println("price:" +doc.get("item_price")); Map<String, List<String>> map = highlighting.get(doc.get("id")); List<String> list = map.get("item_title"); for(String s : list) { System.out.println("title:" + s); } System.out.println("=================="); } }
|