solr復雜查詢條件查詢(排序、過濾、高亮)
簡單案例:
package cn.kingdee;
import java.util.List;
import java.util.Map;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServer;
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.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.junit.Test;
public class TestMyMannager {
@Test
public void queryIndex() throws Exception {
//創建連接
SolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr");
//創建一個query對象
SolrQuery solrQuery = new SolrQuery();
//設置默認的查詢范圍
solrQuery.set("df", "product_name");
//設置查詢條件
solrQuery.setQuery("台燈");
//設置過濾條件
solrQuery.setFilterQueries("product_catalog_name:幽默雜貨");
//設置排序條件
solrQuery.setSort("product_price",ORDER.desc);
//分頁處理
//開始索引為0
solrQuery.setStart(0);
//每頁顯示多少行
solrQuery.setRows(8);
//設置高亮(開啟)
solrQuery.setHighlight(true);
//設置高亮域
solrQuery.addHighlightField("product_name");
//設置高亮前綴
solrQuery.setHighlightSimplePre("<em>");
//設置高亮后綴
solrQuery.setHighlightSimplePost("</em>");
//執行語句
QueryResponse query = solrServer.query(solrQuery);
//取到查詢結果集
SolrDocumentList results = query.getResults();
//共查詢到商品數量
long numFound = results.getNumFound();
//遍歷結果
String productname="";
for (SolrDocument doc : results) {
Map<String, Map<String, List<String>>> highlighting = query.getHighlighting();
List<String> list = highlighting.get(doc.get("id")).get("product_name");
if (list!=null&&list.size()>0) {
productname = list.get(0);
}else{
productname=(String) doc.get("product_name");
}
System.out.println(doc.get("id"));
System.out.println(doc.get("product_name"));
}
}
}
