Home > Blockchain >  Elasticsearch inner hits reponse
Elasticsearch inner hits reponse

Time:01-10

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

CodePudding user response:

I created a class Comment with property "c_text" and did a cast before adding inside a lists comments.

 var comments = new ArrayList<Comment>();
    for (var hit : response.hits().hits()) {
      comments.addAll(hit.innerHits().get("comment").hits().hits().stream().map(
          h -> h.source().to(Comment.class)
      ).collect(Collectors.toList()));
    }
    System.out.println(comments);

CodePudding user response:

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);
        }
    }
  • Related