Sowmya CR
Sowmya CR

Reputation: 312

How to get hits data from elasticsearch in Java

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

Upvotes: 2

Views: 5030

Answers (3)

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.

Upvotes: 0

Ice
Ice

Reputation: 1971

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.

Upvotes: 3

Mike Thomsen
Mike Thomsen

Reputation: 37506

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.

Upvotes: 1

Related Questions