我正在使用Elastic LowLevelRestClient 与我的Elastic实例进行交互,当我使用搜索查询查询Elastic时,它返回包装为HttpEntity的响应。
根据Apache Elastic Reading Responses类的文档,提供了一种将此HttpEntity转换为String的方法,这使我获得以下响应。我只想将此响应映射到适当的对象。
我的代码段:
Request request = new Request("GET", "/neeraj_party/_search");
request.setJsonEntity(searchQuery);
Response response = lowLevelClient.performRequest(request);
String responseBody = EntityUtils.toString(response.getEntity());
ResponseBody看起来像这样
{
"took": 4,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 32.986195,
"hits": [
{
"_index": "neeraj_party",
"_type": "party",
"_id": "28588489",
"_score": 32.986195,
"_source": {
"name": "MUST HK LTD",
"city_nm": "郑州",
"@timestamp": "2019-03-23T18:28:07.305Z",
"type": "json",
"legal_nm": "MUST HK Ltd",
"gr_id": "28588489",
"path": "/ssd/sdds",
"address": "郑州",
"state_province_cd": "180",
"country_iso2_cd": "CN",
"host": "neeraj.com",
"postal_cd": "450000",
"@version": "1"
}
}
]
}
}
我的问题很简单
ElasticSearch是否提供任何可以表示此响应的bean,还是我应该创建自己的CustomBean?
答案 0 :(得分:1)
您可以使用SearchResponse
对象来实现这一目标。
如果使用search(SearchRequest)
方法,它将为您返回一个SearchResponse
对象(包括aggs)。
或者您也可以使用此方法从该字符串中生成SearchResponse
。
public static SearchResponse getSearchResponseFromJson(String jsonResponse){
try {
NamedXContentRegistry registry = new
NamedXContentRegistry(DashboardCuke.getDefaultNamedXContents());
XContentParser parser =
JsonXContent.jsonXContent.createParser(registry, jsonResponse);
return SearchResponse.fromXContent(parser);
}catch (IOException e) {
System.out.println("exception " + e);
}catch (Exception e){
System.out.println("exception " + e);
}
return new SearchResponse();
}
我从这里获得了以下信息:ElasticSearch Forum