java 使用 solrj 检索 json 格式的 SolrDocument
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13011637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using solrj to retrieve a SolrDocument in json format
提问by rrr
How do I specify the SolrQuery to return the data in json format? Heres the code I am using to query data: Once I get the SolrDocument how can I convert it to a json Object/string?
如何指定 SolrQuery 以 json 格式返回数据?下面是我用来查询数据的代码:一旦我获得 SolrDocument,如何将其转换为 json 对象/字符串?
SolrQuery sQuery = new SolrQuery();
sQuery.setQuery("name:test");
QueryResponse resp = server.query(sQuery);
SolrDocumentList docs = resp.getResults();
回答by ravi
Import the JSONUtil class from solrj, it has json converter for solr documents or you can write one easily if you see the code of that class:
从 solrj 导入 JSONUtil 类,它具有用于 solr 文档的 json 转换器,或者如果您看到该类的代码,您可以轻松编写一个:
import org.apache.noggit.JSONUtil;
SolrQuery sQuery = new SolrQuery();
sQuery.setQuery("name:test");
QueryResponse resp = server.query(sQuery);
SolrDocumentList docs = resp.getResults();
String returnValue = JSONUtil.toJSON(docs); //this has the json documents
回答by Paige Cook
SolrJ is designed to retrieve/convert the document as your defined POJO. If you want to convert the document to JSON, you would need to use a library like Hymansonto do the conversion from SolrDocument to JSON.
SolrJ 旨在检索/转换文档作为您定义的 POJO。如果要将文档转换为 JSON,则需要使用Hymanson这样的库来完成从 SolrDocument 到 JSON 的转换。
Not sure if this would be an option for you, but wanted to mention that you might consider getting the response from Solr already formatted as JSON. See SolJSONfor more details. You would not need to use SolrJ in this case. The easiest thing would be to use a straight http call (via a java http client library) and get a JSON response back from Solr using the SolJSON techniques.
不确定这是否适合您,但想提一下您可能会考虑从已经格式化为 JSON 的 Solr 获取响应。有关更多详细信息,请参阅SolJSON。在这种情况下,您不需要使用 SolrJ。最简单的方法是使用直接的 http 调用(通过 java http 客户端库)并使用 SolJSON 技术从 Solr 获取 JSON 响应。
回答by shivadarshan
You can also do it using GSON.
您也可以使用GSON来完成。
SolrDocumentList SolrResponse = searchWithSolr();
Gson gson = new Gson();
if (SolrResponse.size()!=0) {
System.out.println(gson.toJson(SolrResponse));
interpolMap.put("interpol", gson.toJson(InterpolSolrResponse));
}