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;
}
}