solrj是访问Solr服务的java客户端,提供索引和搜索的请求方法,如下图:(Solrj和图形界面操作的区别就类似于数据库中使用jdbc和mysql客户端的区别一样。)
环境准备
- 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
代码实现
1.增/改
//更改就是添加相同的ID,这里便不做相同代码的演示了 /* * 创建HttpSolrServer对象,通过它和Solr服务器建立连接。 * 创建SolrInputDocument对象,然后通过它来添加域。 * 通过HttpSolrServer对象将SolrInputDocument添加到索引库。 */ // 提取HttpSolrServer创建 private HttpSolrServer httpSolrServer; @Before public void init() { // 1. 创建HttpSolrServer对象 // 设置solr服务接口,浏览器客户端地址http://127.0.0.1:8787/solr/#/ String baseURL = "http://127.0.0.1:8787/solr/"; this.httpSolrServer = new HttpSolrServer(baseURL); } @Test public void testCreateAndUpdateIndex() throws Exception { // 2. 创建SolrInputDocument对象 SolrInputDocument document = new SolrInputDocument(); document.addField("id", "c1001"); // 3. 把SolrInputDocument对象添加到索引库中 httpSolrServer.add(document); // 4. 提交 httpSolrServer.commit(); }
2.删/* * 删除索引逻辑,两种: * 根据id删除 * 根据条件删除,根据条件删除 * 可以使用*:*作为条件,就是删除所有数据(慎用) */ // 提取HttpSolrServer创建 private HttpSolrServer httpSolrServer; @Before public void init() { // 1. 创建HttpSolrServer对象 // 设置solr服务接口,浏览器客户端地址http://127.0.0.1:8787/solr/#/ String baseURL = "http://127.0.0.1:8787/solr/"; this.httpSolrServer = new HttpSolrServer(baseURL); } @Test public void testDeleteIndex() throws Exception { // 根据id删除索引数据 // this.httpSolrServer.deleteById("c1001"); // 根据条件删除(如果是*:*就表示全部删除,慎用) this.httpSolrServer.deleteByQuery("*:*"); // 提交 this.httpSolrServer.commit(); }
3.查/** * 简单搜索 * * @throws Exception */ // 提取HttpSolrServer创建 private HttpSolrServer httpSolrServer; @Before public void init() { // 1. 创建HttpSolrServer对象 // 设置solr服务接口,浏览器客户端地址http://127.0.0.1:8787/solr/#/ String baseURL = "http://127.0.0.1:8787/solr/"; this.httpSolrServer = new HttpSolrServer(baseURL); } @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")); } }