Neeraj Jain
Neeraj Jain

Reputation: 7730

Map ElasticSearch LowLevelRestClient's Response to Bean

I am using Elastic LowLevelRestClient to interact with my elastic instance, when I query the elastic using my search query it returns the response which is wrapped as an HttpEntity.

As per documentation of Elastic Reading Responses EntityUtils class of Apache provides a way to convert this HttpEntity into String which gives me below response. I just want to map this response to an appropriate Object.

My Code Snippet:

Request request = new Request("GET", "/neeraj_party/_search");
request.setJsonEntity(searchQuery);
Response response = lowLevelClient.performRequest(request);
String responseBody = EntityUtils.toString(response.getEntity());

ResponseBody looks like this

{
  "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"
        }
      }
    ]
  }
}

My Question is simple

Do ElasticSearch provide any such bean which can represent this response, or Should I create my own CustomBean.

Upvotes: 1

Views: 432

Answers (1)

Paplusc
Paplusc

Reputation: 1130

You could use SearchResponse Object to achieve this.

If you use the search(SearchRequest) method, It gives you back a SearchResponse object (including aggs).

Or you also could make the SearchResponse from that String using this method.

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();
}

I got this information from here: ElasticSearch Forum

Upvotes: 3

Related Questions