导入jar包
package com.tzy.solrJ; import java.io.IOException; import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test; public class SolrJManager { @Test
public void testAdd() throws SolrServerException, IOException{
String baseURL = "http://localhost:8080/solr/";
SolrServer solrServer = new HttpSolrServer(baseURL);
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id", "lala");
doc.setField("name", "张三");
//添加
solrServer.add(doc);
solrServer.commit(); }
}
@Test
public void deleteDocumentByid() throws Exception {
//创建连接
SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr");
//根据id删除文档
solrServer.deleteById("lala");
//删除全部
//solrServer.deleteByQuery("*:*", 1000);
//提交修改
solrServer.commit();
}
删除方法
//查询索引
@Test
public void queryIndex() throws Exception {
//创建连接
SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr");
//创建一个query对象
SolrQuery query = new SolrQuery();
//设置查询条件
//query.set("q","*:*");
query.setQuery("product_name:台灯"); //过滤
//query.set("fq", "product_picture:[* TO 11}"); //排序
query.addSort("product_price", ORDER.desc); //分页
query.setStart(0);
query.setRows(5); //设置默认域
query.set("df", "product_name");//设置好以后query.setQuery("台灯");就可以查询 //只查询指定域
query.set("fl", "id,product_name"); //高亮
query.setHighlight(true);
query.addHighlightField("product_name");
query.setHighlightSimplePre("<span style='color:red'>");
query.setHighlightSimplePost("</span>"); //执行查询
QueryResponse queryResponse = solrServer.query(query);
//取查询结果
SolrDocumentList solrDocumentList = queryResponse.getResults();
//高亮查询结果
Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
//共查询到商品数量
System.out.println("共查询到商品数量:" + solrDocumentList.getNumFound());
//遍历查询的结果
for (SolrDocument solrDocument : solrDocumentList) {
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"));
System.out.println("************"); Map<String, List<String>> map = highlighting.get(solrDocument.get("id"));
List<String> list = map.get("product_name");
System.out.println(list.get(0)); }
}
查询方法