ps:需要注意的点都用注释标明了
一,连接
/**
* 创建连接
* @return
* @throws IOException
* @throws SolrServerException
*/
public SolrClient connectSolr() throws IOException, SolrServerException {
//连接zookeeper
CloudSolrClient cloudSolrClient = new CloudSolrClient("ip:zookeeper端口号");
cloudSolrClient.setDefaultCollection("paper6.1");
cloudSolrClient.connect();
return cloudSolrClient;
}
二,构造查询条件
/**
* 构造查询条件
* @return
*/
public SolrQuery buildSearchParam(){
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery("stringIS_sysSubType:R03");//q
solrQuery.setFilterQueries("auto_stringITMS_keyword:zh-cn|钢铁");//fq
solrQuery.setFields("id,type,stringIS_sysSubType,auto_stringITMS_keyword");//fl
solrQuery.addField("dateIS_date");//新增fl项
return solrQuery;
}
三,普通查询
/**
* 普通查询
*/
public void simpleSearch(){
//1.构造查询条件
SolrQuery solrQuery = this.buildSearchParam();
solrQuery.setSort("dateIS_date ", SolrQuery.ORDER.asc);//sort
solrQuery.setStart(0);
solrQuery.setRows(1);
//2.查询
QueryResponse queryResponse = null;
try {
queryResponse = this.connectSolr().query(solrQuery);
} catch (Exception e) {
e.printStackTrace();
}
//3.遍历结果
//3.1 map遍历
SolrDocumentList results = queryResponse.getResults();//SolrDocumentList本质是List<Map>结构
Iterator<SolrDocument> iterator = results.iterator();
while (iterator.hasNext()) {
SolrDocument document = iterator.next();
Set<Map.Entry<String, Object>> entries = document.entrySet();
for (Map.Entry<String, Object> entry : entries) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
//3.2 List转json
SolrDocumentList docs = queryResponse.getResults();
String json = new Gson().toJson(docs);//list转json
System.out.println(json);
//3.3 map转json
StringBuffer sb = new StringBuffer("[");
while(iterator.hasNext()) {
SolrDocument document = iterator.next();
JSONObject jsonObject = new JSONObject(document);
String string = jsonObject.toString();
sb.append(string);
sb.append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
sb.append("]");
System.out.println(sb.toString());
}
四,游标查询
/**
* 游标查询
*/
public void cursorSearch() throws IOException, SolrServerException {
SolrQuery solrQuery = this.buildSearchParam();
solrQuery.setSort("id", SolrQuery.ORDER.asc);//如果使用游标查询,那么必须根据主键排序
solrQuery.setRows(2);//注意:使用游标方式,不能设置start
String beginCursor = CursorMarkParams.CURSOR_MARK_START;//* 游标开始的标志
boolean flag = true;
while(flag){
solrQuery.setParam(CursorMarkParams.CURSOR_MARK_PARAM,beginCursor);
QueryResponse queryResponse = this.connectSolr().query(solrQuery);
SolrDocumentList docs = queryResponse.getResults();//获取查询结果
String json = new Gson().toJson(docs);
System.out.println(json);
String nextCursorMark = queryResponse.getNextCursorMark();//获取下一个游标值
if (beginCursor.equalsIgnoreCase(nextCursorMark)){ //如果值获取完毕,那么返回的游标值就和上次的一样
flag = false;
}
beginCursor = nextCursorMark;
}
}