部署solr服务
上一篇中讲述了如何部署一个solr项目, 部署成功进行访问访问就进入到了solr的浏览器界面。
利用浏览器界面也可以进行索引的添加和关键词的查询, solrj也可以添加索引进行搜索。 solrj和浏览器界面的区别就类似于jdbc和mysql客户端的区别。
涉及到的类
- 通过HttpSolrServer对象:和solr服务器建立连接;将添加的域添加到索引;库; 执行搜索请求;根据条件删除索引;
- 通过SolrInputDocument对象:添加域
- 通过SolrQuery对象 :设置搜索条件
- SolrDocument对象:搜索结果
所需jar包:
- dist/solr-solrj-版本
- dist/solr-lib文件夹下的jar包
- example/lib/ext文件夹下jar包
上代码
创建索引
@Test
public void testCreateIndex() throws IOException, SolrServerException {
// 创建httpsolrserver对象, 和solr服务器进行链接
HttpSolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/");
// 创建solrinputdocument对象, 添加域
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "007");
document.addField("content", "helloworld");
// 通过solrserver将solrinputdocument添加到索引域
solrServer.add(document);
// 提交
solrServer.commit();
}
删除索引
@Test
public void testDeleteIndex() throws Exception{
// 创建solrserver对象, 用于链接solr服务器
HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr/");
// 根据条件删除
server.deleteById("007"); // 根据id删除
server.deleteByQuery("*:*"); // 删除所有
// 提交
server.commit();
}
简单搜索
@Test
public void testQuery() throws Exception{
// 创建solrserver对象,用于和solr服务器进行连接
HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr/");
// 创建查询对象
SolrQuery query = new SolrQuery();
query.setQuery("*:*");
// 执行查询
QueryResponse response = server.query(query);
// 得到结果
SolrDocumentList results = response.getResults();
// 处理结果
long totalNum = results.getNumFound();
System.out.println("共发现"+ totalNum +"条结果");
for (SolrDocument document: results){
System.out.println(document.getFieldValue("id"));
System.out.println(document.getFieldValue("content"));
}
}
网友评论