什么是solrj
solrj是访问Solr服务的java客户端,提供索引和搜索的请求方法,SolrJ通常在嵌入在业务系统中,通过SolrJ的API接口操作Solr服务,如下图:
需要导入的jar包:
代码:
package com.me.solrj; import static org.junit.jupiter.api.Assertions.*; import java.util.List; import java.util.Map; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery.ORDER; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrInputDocument; import org.junit.jupiter.api.Test; public class SolrJManager { //solrj管理 //增加 //修改 //删除 //查询 @Test void testAdd() throws Exception { // 添加与更新相同 //连接solr服务器 String baseURL="http://localhost:8080/solr"; SolrServer solrserver=new HttpSolrServer(baseURL); SolrInputDocument solrinputdocument=new SolrInputDocument(); solrinputdocument.setField("id", "haha"); solrinputdocument.setField("name", "hsjsjs"); solrserver.add(solrinputdocument); solrserver.commit(); } @Test void testDelete() throws Exception { String baseURL="http://localhost:8080/solr"; SolrServer solrserver=new HttpSolrServer(baseURL); solrserver.deleteByQuery("*:*", 1000);//删除所有 // solrserver.deleteById("*"); } @Test void testSearch() throws Exception { String baseURL="http://localhost:8080/solr"; SolrServer solrserver=new HttpSolrServer(baseURL); SolrQuery solrquery=new SolrQuery(); //关键字查询 solrquery.set("q", "*:*"); // solrquery.setQuery("*:*");与上面一句效果相同 solrquery.set("fq", "product_catalog_name:幽默杂货"); //设置价格区间 solrquery.set("fq", "product_price:[* TO 50]"); //设置排序 solrquery.addSort("product_price", ORDER.asc); //设置分页 solrquery.setStart(0); solrquery.setRows(5); //设置默认域 solrquery.set("df", "product_name"); //设置查询域 solrquery.set("fl", "*"); //设置高亮 solrquery.setHighlight(true); //设置高亮域 solrquery.addHighlightField("id"); //高亮显示的前缀 solrquery.setHighlightSimplePre("<span style=‘color:red‘>"); //高亮显示的后缀 solrquery.setHighlightSimplePost("</span>"); //执行查询 QueryResponse response = solrserver.query(solrquery); Map<String, Map<String, List<String>>> highlighting = response.getHighlighting(); //文档结果集 SolrDocumentList results = response.getResults(); //搜索到的文档数量 long numFound = results.getNumFound(); System.out.println(numFound); //遍历文档 for (SolrDocument sd : results) { Map<String, List<String>> map = highlighting.get("id"); List<String> list = map.get("product_name"); System.out.println(list.get(0)); System.out.println("----------------------------"); System.out.println(sd.get("id")); System.out.println(sd.get("product_name")); System.out.println(sd.get("product_price")); System.out.println(sd.get("product_catalog_name")); System.out.println(sd.get("product_picture")); } } }
原文:https://www.cnblogs.com/tkg1314/p/12261506.html