java 以json格式返回solr响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28374428/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:28:13  来源:igfitidea点击:

Return solr response in json format

javajsonsolrsolrj

提问by user1247412

I am trying to return solr response in JSON format. However I am not able to get the JSON response. Below is my solr config:'

我正在尝试以 JSON 格式返回 solr 响应。但是我无法获得 JSON 响应。以下是我的 solr 配置:'

<queryResponseWriter name="json" default="true" class="org.apache.solr.request.JSONResponseWriter">
    <str name="content-type">application/json</str>
</queryResponseWriter>

Below is my java code:

下面是我的java代码:

HttpSolrServer server = new HttpSolrServer(serverUrl);
SolrQuery query = new SolrQuery();
query.setQuery(query);
query.set("indent","true");
query.set("wt","json");
QueryResponse response = server.query(query);

System.out.println(response.getResults().get(index));

However output is displyed in following format.

但是,输出以以下格式显示。

{numFound=1,start=0,docs=[SolrDocument{_uniqueKey=[“[email protected]”,”abc”], calculation_policy=text_value, username=abc, [email protected], display_order=10, last_login=Mon Jan 26 11:27:35 PST 2015, created=Mon Jan 26 11:27:35 PST 2015}]}

However I get JSON response after execute following line:

但是,我在执行以下行后得到 JSON 响应:

System.out.println(new Gson().toJson(queryResponse.getResults().get(index)));

Can someone please tell me what step am I missing?

有人可以告诉我我错过了哪一步吗?

采纳答案by David Kaplan

Perhaps this link may clarify: quoted format json from Solrj

也许这个链接可以澄清: 来自 Solrj 的引用格式 json

Else maybe you can achieve what you need just through an Http Request as I know that indeed has json support.

否则,也许您可​​以通过 Http 请求来实现您需要的东西,因为我知道确实有 json 支持。

回答by laberning

With newer versions of Solr (starting with 4.7.0) it is possible to return the query response directly in json-format. This can be done with the NoOpResponseParser.

使用较新版本的 Solr(从 4.7.0 开始),可以直接以 json 格式返回查询响应。这可以通过NoOpResponseParser.

SolrQuery query = new SolrQuery();
QueryRequest req = new QueryRequest(query);

NoOpResponseParser rawJsonResponseParser = new NoOpResponseParser();
rawJsonResponseParser.setWriterType("json");
req.setResponseParser(rawJsonResponseParser);

NamedList<Object> resp = mySolrClient.request(req);
String jsonResponse = (String) resp.get("response");

System.out.println(jsonResponse );

回答by Swaraj

By default Solrj uses wt=javabin&version=2as default for fetching results as described in http://wiki.apache.org/solr/javabin

默认情况下,Solrj 使用wt=javabin&version=2作为默认获取结果,如http://wiki.apache.org/solr/javabin 中所述

However to show the response in json either use GSON or Hymanson(Object Mapper).

但是,要在 json 中显示响应,请使用 GSON 或 Hymanson(Object Mapper)。