2

I have elasticsearch response stored as a String value in java,How to process only hits data

Sowmya CR
  • 312
  • 1
  • 3
  • 13
  • 1
    ...what format is the response in? Can you parse that somehow...? – f1sh Jan 17 '19 at 11:56
  • Possible duplicate of [How to parse JSON in Java](https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java) – f1sh Jan 17 '19 at 11:56

3 Answers3

3

For example, you want to retrieve all data as Car type. Your query response is store in searchResponse variable, get all hits and serialize them to the objects. Look at the example below:

Gson gson = new Gson();

var flowers = new ArrayList<Flower>();

Arrays.stream(searchResponse.getHits().getHits()).forEach(hit ->
                    cars.add(gson.fromJson(hit.getSourceAsString(), Car.class)));

Of course, I am using gson to serialize the JSON to the object.

Ice
  • 1,783
  • 4
  • 26
  • 52
1

The best way to access it from Java is to use the official Java REST API from Elastic. The API will let you work with Java objects instead of processing the data yourself.

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
0

You first need to convert the json string to a json/map object, either using gson, Jackson, or other method.

Then, once you have a Map, the hits are under: hits.hits key, as an array of maps, each map in the array represent a hit, with its metadata. The original doc is under the key _source in each hit.

I also highly recommend reading elasticsearch docs, which are good source.