Transform SearchHit to Java Object in ElasticSearch

I am trying to retrieve data form ES query and I am confused about how can I transform each hit of retrieved data to Java Object. Until now, I can get each hit in JSON format using Gson but I think is useless to transform from Hit to JSON and then to Java Object.

My current code is:

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY) .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300)); Settings settings = Settings.builder() .put("cluster.name", "elasticsearch") .put("path.home", "/Users/user/Apps/elasticsearch-5.4.1") .build(); QueryBuilder qb = termQuery("price", 12); SearchResponse response = client.prepareSearch("kal").setTypes("products") .setSearchType(SearchType.DEFAULT) .setQuery(qb) .get(); SearchHit[] results = response.getHits().getHits(); for (SearchHit hit : results) { String sourceAsString = hit.getSourceAsString(); Map<String, SearchHitField> responseFields = hit.getFields(); if (sourceAsString != null) { Gson gson = new GsonBuilder().setDateFormat(sourceAsString) .create(); } }
5

3 Answers

One line

YourObject yourObject = new com.fasterxml.jackson.databind.ObjectMapper().convertValue(searchHit.getSourceAsMap(), YourObjectClass.class);

I implemented this solution but I am not sure if this is the proper way or not.

SearchHit[] results = response.getHits().getHits(); for (SearchHit hit : results) { String sourceAsString = hit.getSourceAsString(); Map<String, SearchHitField> responseFields = hit.getFields(); SearchHitField field = responseFields.get("product_id"); Map map = hit.getSource(); System.out.println(map.toString()); }
 I am working with Elasticsearch version 7.4.2 SearchHit[] searchHit = response.getHits().getHits(); for (SearchHit hit : searchHit) { String jsonString=hit.getSourceAsString(); TempClass tmpCl=(TempClass )JSONToObject.parser(jsonString, TempClass .class); System.out.println(tmpCl.toString()); } // JSONToObject class private static Object dc; public static Object parser(String file, Class<?> cls) { try { Gson gson = new Gson(); dc = gson.fromJson(file, cls); } catch (Exception e) { e.printStackTrace(); } return dc; }
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like