利用SolrJ操作solr API
来源:互联网 发布:杭州博远软件 编辑:程序博客网 时间:2024/05/24 02:25
使用SolrJ操作Solr会比利用httpClient来操作Solr要简单。SolrJ通过封装httpClient方法,来操作solr的API的。即SolrJ底层还是通过使用httpClient中的方法来完成Solr的操作
添加jar包:首先,你需要在你的web项目中添加SolrJ需要的jar包,这些jar包在你所下载的Solr包中都可以找到(我下载的是solr-4.10.0.zip),包括:
- apache-solr-solrj-4.10.0.jar : solr-4.10.0\dist文件夹下
- apache-solr-solrj-4.10.0.jar所依赖的其他jar包 : solr-4.10.0\dist\solrj-lib文件夹下
- solr-core-4.10.0.jar
- commons-logging-1.0.4.jar 日志相关jar
Junit测试:
- package com.april.lucene.solr;
-
- import java.io.IOException;
- import java.net.MalformedURLException;
- import java.util.List;
- import org.apache.solr.client.solrj.SolrQuery;
- import org.apache.solr.client.solrj.SolrQuery.ORDER;
- import org.apache.solr.client.solrj.SolrServerException;
- import org.apache.solr.client.solrj.impl.HttpSolrServer;
- 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.After;
- import org.junit.Before;
- import org.junit.Test;
- import com.april.lucene.model.JavaBean;
-
-
-
-
-
-
- public class ServerTest {
- private HttpSolrServer server = null;
-
-
-
-
-
-
- private static final String URL = "http://localhost:8080/solr/april"; //april索引库URL
- @Before
- public void init() {
- server = new HttpSolrServer(URL);
- }
-
-
-
- @Test
- public void addDoc() {
-
- SolrInputDocument doc = new SolrInputDocument();
- doc.addField("id", 1);
- doc.addField("name", "Add Solr Index");
- doc.addField("manu", "Solr test file");
- try {
- UpdateResponse response = server.add(doc);
-
- server.commit();
- System.out.println(response);
- System.out.println("query time:" + response.getQTime());
- System.out.println("Elapsed Time:" + response.getElapsedTime());
- System.out.println("status:" + response.getStatus());
- } catch (SolrServerException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
-
-
- @Test
- public void addBean() throws IOException, SolrServerException {
-
- JavaBean bean = new JavaBean();
- bean.setId("2");
- bean.setName("Add bean index");
- bean.setMenu("index bean menu");
- server.addBean(bean);
-
- server.commit();
- }
-
-
-
- @Test
- public void remove() throws SolrServerException, IOException {
- server.deleteById("1");
- server.commit();
-
- server.commit(true, true); <li class="alt" style="box-sizing: border-box; margin-left: 40px; list-style: decimal; border-top: none; border-right: none; border-bottom: none; border-left: 3px solid rgb(108, 226, 108); border-image: initial; color: inherit; line-height: 18px; margin-top: 0px !important; margin-right: 0px !important; margin-bottom: 0px !important; padding: 0px 3px 0px 10px !import