Home > Software engineering >  Convert elasticsearch bool query to Java
Convert elasticsearch bool query to Java

Time:01-06

GET feeds/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "comment",
            "query": { 
              "match": {
                "comment.c_text": "This is mateen"
              }
            },"inner_hits": {}
          }
        },
        {
          "term": {
            "title.keyword": {
              "value": "This is mateen"
            }
          }
        },
        {
          "term": {
            "body.keyword": {
              "value": "This is mateen"
            }
          }
        }
      ]
    }
  }
}

Mapping is as follows:

PUT feeds
{
  "mappings": {
    "properties": {
      "comment":{
        "type": "nested"
      }
    }
  }
}

I am using Elasticsearch 7.17.3. For searching all documents of Elasticsearch in my springboot I have written the following code that gives me the exact output:

public  List<feed> searchAllDocuments() throws IOException {
        SearchRequest searchRequest = SearchRequest.of(s -> s.index(indexName));
        SearchResponse searchResponse = elasticsearchClient.search(searchRequest, feed.class);
        List<Hit> hits = searchResponse.hits().hits();
        List<feed> feeds = new ArrayList<>();
        feed f=null;
        for (Hit object : hits) {
            f = (feed) object.source();
           
            feeds.add(f);
            }

        return feeds;
        }

Can anyone help me convert the query into springboot application? I am new to it and need your guidance

CodePudding user response:

If you use the new Java Api Client try the code bellow:

Query nestedQuery = NestedQuery.of(nq ->
    nq.path("comment")
        .innerHits(InnerHits.of(ih -> ih))
        .query(MatchQuery.of(mq -> mq.field("comment.c_text").query("This is mateen"))._toQuery())
)._toQuery();

Query termQueryTitle = TermQuery.of(
    tq -> tq.field("title.keyword").value("This is mateen")
)._toQuery();

Query termQueryBody = TermQuery.of(
    tq -> tq.field("body.keyword").value("This is mateen")
)._toQuery();

Query boolQuery = BoolQuery.of(bq -> bq.should(nestedQuery, termQueryBody, termQueryTitle))._toQuery();

SearchRequest searchRequest = SearchRequest.of(
    s -> s.index("idx_name").query(boolQuery)
);

var response = client.search(searchRequest, Feed.class);
  • Related