在上一篇blog中(http://guwq2014.iteye.com/blog/2289866),已经将solr服务端搭建完成了,这一篇将介绍solr客户端中使用solrj实现基本的增、删、查功能。
创建java工程TestSolr,导入基本的jar包:
新建一个测试类:SolrTest.java:
package com.solr;
import java.util.ArrayList;
import java.util.Collection;
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.BinaryRequestWriter;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
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.SolrInputDocument;
/**
* solrJ 使用 :增、删、查
*/
public class SolrJTest {
public static final String SOLR_URL = "http://127.0.0.1:8080/solrweb";
/**
* 添加
*/
public static void addDoc() {
String[] words = { "中央全面深化改革领导小组", "第四次会议", "审议了国企薪酬制度改革", "考试招生制度改革",
"传统媒体与新媒体融合等", "相关内容文件", "总理强调要", "逐步规范国有企业收入分配秩序",
"实现薪酬水平适当", "结构合理、管理规范、监督有效", "对不合理的偏高", "过高收入进行调整",
"深化考试招生制度改革", "总的目标是形成分类考试", "综合评价", "多元录取的考试招生模式", "健全促进公平",
"科学选才", "监督有力的体制机制", "着力打造一批形态多样", "手段先进", "具有竞争力的新型主流媒体",
"建成几家拥有强大实力和传播力", "公信力", "影响力的新型媒体集团" };
long start = System.currentTimeMillis();
Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
for (int i = 1; i < 10; i++) {
SolrInputDocument doc1 = new SolrInputDocument();
doc1.addField("id", "id" + i, 1.0f);
doc1.addField("name", words[i % 21], 1.0f);
doc1.addField("price", 10 * i);
docs.add(doc1);
}
try {
HttpSolrServer server = new HttpSolrServer(SOLR_URL);
UpdateResponse response = server.add(docs);
server.optimize(); // 一定要执行一下
System.out.println(response.getStatus());
} catch (Exception e) {
System.out.println(e);
}
System.out.println("time elapsed(ms):"
+ (System.currentTimeMillis() - start));
}
/**
* 删除
*/
public static void delDoc() {
long start = System.currentTimeMillis();
try {
HttpSolrServer server = new HttpSolrServer(SOLR_URL);
List<String> ids = new ArrayList<String>();
for (int i = 1; i < 10; i++) {
ids.add("id" + i);
}
UpdateResponse response = server.deleteById(ids);
server.commit();
server.optimize(); // 一定要执行一下
System.out.println(response.getStatus());
} catch (Exception e) {
System.out.println(e);
}
System.out.println("time elapsed(ms):"
+ (System.currentTimeMillis() - start));
}
/**
* 查询
*/
public static void queryDoc() {
HttpSolrServer server = new HttpSolrServer(SOLR_URL);
server.setMaxRetries(1);
server.setConnectionTimeout(5000);
server.setParser(new XMLResponseParser());
server.setSoTimeout(1000);
server.setDefaultMaxConnectionsPerHost(100);
server.setMaxTotalConnections(100);
server.setFollowRedirects(false);
server.setAllowCompression(true);
// 使用SolrQuery传递参数,SolrQuery的封装性更好
server.setRequestWriter(new BinaryRequestWriter());
SolrQuery query = new SolrQuery();
query.setQuery("video");
query.setFields("id", "name", "price", "score");
query.setSort("price", ORDER.asc);
query.setStart(0);
query.setRows(10);
QueryResponse response = null;
try {
response = server.query(query);
} catch (SolrServerException e) {
e.printStackTrace();
}
// 搜索得到的结果数
System.out.println("Find:" + response.getResults().getNumFound());
// 输出结果
int iRow = 1;
for (SolrDocument doc : response.getResults()) {
System.out.println("----------" + iRow + "------------");
System.out.println("id: " + doc.getFieldValue("id").toString());
System.out.println("name: " + doc.getFieldValue("name").toString());
System.out.println("price: " + doc.getFieldValue("price").toString());
System.out.println("score: " + doc.getFieldValue("score"));
iRow++;
}
}
/**
* main
*
* @param args
*/
public static void main(String[] args) {
// addDoc();
// delDoc();
queryDoc();
}
}
即可实现增、删、查功能。
几个常见错误和解决方法:
报错信息:RemoteSolrException: Expected mime type application/octet-stream but got text/html
错误原因:solr服务端的地址错误
解决方法:在使用Tomcat部署Solr后,Collection1的地址为:http://127.0.0.1:8080/solr/#/collection1,但使用SolrJ进行索引的时候,应该使用http://127.0.0.1:8080/solr/collection1,即无中间的#号。