什么是solrj
solrj是访问Solr服务的java客户端,提供索引和搜索的请求方法,如下图:
Solrj和图形界面操作的区别就类似于数据库中使用jdbc和mysql客户端的区别一样。
需求
使用solrj调用solr服务实现对索引库的增删改查操作。
环境准备
- Solr:4.10.3
- Jdk环境:1.7
- IDE环境:Eclipse Mars2
工程搭建
创建java工程
添加jar
Solrj的包,\solr-4.10.3\dist\目录下
solrj依赖包,\solr-4.10.3\dist\solrj-lib
Solr服务的依赖包,\solr\example\lib\ext
-
代码实现
添加&修改索引
- 步骤
- 创建HttpSolrServer对象,通过它和Solr服务器建立连接。
- 创建SolrInputDocument对象,然后通过它来添加域。
- 通过HttpSolrServer对象将SolrInputDocument添加到索引库。
- 提交。
代码
说明:根据id(唯一约束)域来更新Document的内容,如果根据id值搜索不到id域则会执行添加操作,如果找到则更新。
@Test
public void testCreateAndUpdateIndex() throws Exception {
// 1. 创建HttpSolrServer对象
// 设置solr服务接口,浏览器客户端地址http://127.0.0.1:8081/solr/#/
String baseURL = "http://127.0.0.1:8081/solr";
HttpSolrServer httpSolrServer = new HttpSolrServer(baseURL);
// 2. 创建SolrInputDocument对象
SolrInputDocument document = new SolrInputDocument();
document.addField("id", "c1001");
document.addField("content ", "Hello world!");
// 3. 把SolrInputDocument对象添加到索引库中
httpSolrServer.add(document);
// 4. 提交
httpSolrServer.commit();
}
删除索引
代码
抽取HttpSolrServer 的创建代码
private HttpSolrServer httpSolrServer;
// 提取HttpSolrServer创建
@Before
public void init() {
// 1. 创建HttpSolrServer对象
// 设置solr服务接口,浏览器客户端地址http://127.0.0.1:8081/solr/#/
String baseURL = "http://127.0.0.1:8081/solr/";
this.httpSolrServer = new HttpSolrServer(baseURL);
}
查询索引
简单查询
/**
* 简单搜索
*
* @throws Exception
*/
@Test
public void testSearchIndex1() throws Exception {
// 创建搜索对象
SolrQuery query = new SolrQuery();
// 设置搜索条件
query.setQuery("*:*");
// 发起搜索请求
QueryResponse response = this.httpSolrServer.query(query);
// 处理搜索结果
SolrDocumentList results = response.getResults();
System.out.println("搜索到的结果总数:" + results.getNumFound());
// 遍历搜索结果
for (SolrDocument solrDocument : results) {
System.out.println("----------------------------------------------------");
System.out.println("id:" + solrDocument.get("id"));
System.out.println("content" + solrDocument.get("content"));
}
}