解析Solr响应时出错

时间:2015-04-03 10:02:58

标签: java solr lucene solrj solr4

我正在使用Solr-5.0.0。

我想用Java查询Solr。我在这里使用group by子句。

我的代码

SolrQuery qry = new SolrQuery();

qry.setQuery("product_name:(laptops)");
qry.addFilterQuery("brand:dell OR brand: sony OR brand:samsung");
qry.setParam("group", true);
qry.setParam("group.field", "brand");
qry.setParam("stats", true);
qry.setParam("stats.field", "product_price");
qry.setFields("brand");
System.out.println(qry.toString());  

QueryRequest qryReq = new QueryRequest(qry);
QueryResponse resp = qryReq.process(solr);
System.out.println(resp.getResponse().toString());

// Here I am getting required response;
SolrDocumentList docs = resp.getResults();

//Below code giving me exception null pointer
for(int i = 0; i < docs.size(); i++) {
  System.out.println(docs.get(i)); 
}

但是我无法解析查询的结果。我只需要从列表或数组中的查询中获取品牌及其相应的计数

2 个答案:

答案 0 :(得分:0)

我不熟悉您使用的SolrQuery类。

我在程序中使用solr创建了一个URL(Solr请求)并将响应作为JSon获取,如下所示。

将请求定义为url

String url = "http://"+solr_server+":"+solr_port+"/solr/collection_name/select?q="+brand+"&wt=json&indent=true";

将solr结果作为JSon从请求URL

中读取
JSONObject json = readJsonFromUrl(url);

获取响应,然后获取文档 - 然后遍历文档

JSONObject j1 = (JSONObject) json.get("response");
JSONArray j2 = j1.getJSONArray("docs");
for(int i=0;i<j2.length();i++){
    //do whatever you want to do
}

请记住在类路径中使用http://www.java2s.com/Code/JarDownload/java-json/java-json.jar.zip的jar。

答案 1 :(得分:0)

使用a link调试查询,查看查询是否构建正确。然后你可以采用java