javaspring-bootelasticsearchelasticsearch-java-api

Elasticsearch inner hits reponse


This is my query function :

public  List<feed> search(String id) throws IOException {    
    Query nestedQuery = NestedQuery.of(nq ->nq.path("comment").innerHits(InnerHits.of(ih -> ih)).query(MatchQuery
                        .of(mq -> mq.field("comment.c_text").query(id))._toQuery()))._toQuery();
    Query termQueryTitle = TermQuery.of(tq -> tq.field("title").value(id))._toQuery();
    Query termQueryBody = TermQuery.of(tq -> tq.field("body").value(id))._toQuery();
    Query boolQuery = BoolQuery.of(bq -> bq.should(nestedQuery, termQueryBody, termQueryTitle))._toQuery();
    SearchRequest searchRequest = SearchRequest.of(s -> s.index(indexName).query(boolQuery));
    var response = elasticsearchClient.search(searchRequest, feed.class);
    for (var hit : response.hits().hits()){
        System.out.println("this is inner hit response: " + (hit.innerHits().get("comment").hits().hits()));  }
           List<Hit<feed>> hits = response.hits().hits();
           List<feed> feeds = new ArrayList<>();
           feed f=null;
           for(Hit object : hits){
               f = (feed) object.source();
             feeds.add(f); }   
           return feeds;
           }

i have add this code

 for (var hit : response.hits().hits()){
        System.out.println("this is inner hit response: " + (hit.innerHits().get("comment").hits().hits()));  }

if it founds 2 records it gives me the refrence of 2 records but dont show me the actual records like its outpout is as follow if it founds 2 records in inner hit :

this is inner hit response [co.elastic.clients.elasticsearch.core.search.Hit@75679b1a]
this is inner hit response [co.elastic.clients.elasticsearch.core.search.Hit@1916d9c6]

can anyone help me to poput the actual records


Solution

  • This properly works for me in console :

     for (var hit : response.hits().hits()) {
            var innerHits = hit.innerHits().get("comment").hits().hits();
            for (var innerHit : innerHits) {
                JsonData source = innerHit.source();
                String jsonDataString = source.toString();
                System.out.println("Matched comments"+jsonDataString);
            }
        }