所需的包如图:
代码如下:
package solr;
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.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Before;
import org.junit.Test;
public class test {
private static final String URL = "http://localhost:8983/solr/test/";
private HttpSolrClient server = null;
/*
* 初始化
*/
@Before
public void init() {
// 创建 server
server = new HttpSolrClient(URL);
}
/*
* 添加、修改索引
*/
@Test
public void addDoc() {
SolrInputDocument doc = new SolrInputDocument();
doc.addField("id", "4");
doc.addField("title", "号外!号外!特别喜讯");
doc.addField("content", "王部长今天把solr关键应用点全部贯通,希望在以后的学习生涯再接再厉。");
try {
//如果不存在,就添加;如果存在,就更改
UpdateResponse response = server.add(doc);
//一定要提交
server.commit();
System.out.println("Query Time :" + response.getQTime());
System.out.println("Elapsed Time :" + response.getElapsedTime());
System.out.println("Status :" + response.getStatus());
} catch (Exception e) {
System.err.print(e);
}
}
/**
* 普通查询
*/
@Test
public void testQuery() {
String queryStr = "content:*";
SolrQuery params = new SolrQuery(queryStr);
params.setSort("id",ORDER.asc);
params.set("rows", 10);
try {
QueryResponse response = null;
response = server.query(params);
SolrDocumentList list = response.getResults();
System.out.println("总共 : " + list.getNumFound() + "条记录");
for (SolrDocument doc : list) {
System.out.println("id : " + doc.get("id") + " title : " + doc.get("title")+
" content : "+ doc.get("content"));
}
} catch (Exception e) {
System.err.print(e);
}
}
/*
* 高亮查询
*/
@Test
public void hightLightQuery() throws Exception{
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery("title:新闻");
//solrQuery.setFilterQueries("content:[0 TO 100]");
//solrQuery.setSort("content",ORDER.asc);
// 开启高亮
solrQuery.setHighlight(true).setHighlightSnippets(1); ;
// 设置高亮域
solrQuery.addHighlightField("title");
// 设置高亮前缀
solrQuery.setHighlightSimplePre("<font color='red'>");
// 设置高亮后缀
solrQuery.setHighlightSimplePost("</font>");
QueryResponse queryResponse = server.query(solrQuery);
// 从查询响应中获取结果集
SolrDocumentList solrDocumentList = queryResponse.getResults();
// 打印结果集中的数据
for (SolrDocument solrDocument : solrDocumentList) {
// 获取查询结果
System.out.println( solrDocument.get("content"));
// 获取高亮结果
Map<String, Map<String, List<String>>> map = queryResponse.getHighlighting();
//获取多层嵌套的结果
List<String> lists = map.get(solrDocument.get("id")).get("title");
if(lists != null)
System.out.println(lists.get(0));
}
}
/*
* 删除
*/
@Test
public void deletDoc() throws Exception{
server.deleteByQuery("id:4");
//一定要提交
server.commit();
}
}