我正在使用Elastic LowLevelRestClient 与我的 flex 实例进行交互,当我使用搜索查询查询 flex 时,它返回包装为HttpEntity的响应。

根据Elastic Reading Responses的文档,Apache的EntityUtils类提供了一种将此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"
        }
      }
    ]
  }
}

我的问题很简单

最佳答案

您可以使用SearchResponse对象来实现此目的。

如果您使用search(SearchRequest)方法,它将返回一个SearchResponse对象(包括aggs)。

或者,您也可以使用此方法从该String生成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

09-15 20:59