0

I am using the following java code to query the elasticsearch 7.3 and get 1 document. I have set it to only 1 doc with the highest score. It is working fine and returning me the doc perfectly.

  @Autowired
    RestHighLevelClient client;

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public @ResponseBody
    String getItem(@RequestParam("string") String string) throws IOException {


        QueryBuilder matchQueryBuilder = QueryBuilders.simpleQueryStringQuery(string);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(matchQueryBuilder);
        sourceBuilder.from(0);
        sourceBuilder.size(1);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        SearchRequest searchRequest = new SearchRequest("nutrients");
        searchRequest.source(sourceBuilder);

        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        return searchResponse.toString();
    }

The response is as follow, I want to access the values using java code of Calories , Fat , Protein , Carbohydrate and ignore the values of other Nutrient. I need the values in 4 variables like String caloriesVar=153 kcal and similarly for the other 3.

[Search Response[1]

Lily
  • 605
  • 3
  • 15
  • 31
  • 1
    If you use Spring Data Elasticsearch, why don't you define an entity and use Spring Data Repositories or at least the template implementation instead of doing the whole work of writing the queries and parsing the results? – P.J.Meisch May 10 '20 at 05:41
  • Convert the response string to JSON Object and access your data. – damjad May 10 '20 at 09:15
  • @chuckskull kindly provide me an answer, I am unable to achieve this – Lily May 10 '20 at 11:31
  • Answer to this question is here, https://stackoverflow.com/questions/17037340/converting-jsonarray-to-arraylist/17037364#17037364 – Lily May 10 '20 at 15:05
  • to be honest, I still don't get the point why you use Spring Data Elasticsearch, or better, why you don't use all the stuff the Spring Data Elasticsearch offers. Believe me, you don't really want to parse all the JSON by yourself. – P.J.Meisch May 10 '20 at 15:55
  • @P.J.Meisch Sir I haven't used the Spring Data Elasticserach before. COuld you please guide me how could I use in my case? – Lily May 10 '20 at 16:10
  • you might have a look a Greg's talk https://www.infoq.com/presentations/intro-spring-data/, or just search for Spring Data tutorials. To get the concept it must not be Spring Data Elasticsearch, it can be JPA or MongoDB as well. The concept is the same for all Spring Data Modules. Just the underlying store differs – P.J.Meisch May 11 '20 at 05:39

0 Answers0