Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested elasticsearch query for java QueryBuilders

I am trying to achieve this elasticsearch query in java querybuilder for elasticsearch. But i am not able to get the equivalent results. Can anyone help with this.

 GET /XX/XX/_search
    {
       "query": {
          "bool": {
             "must": [
                {
                   "nested": {
                      "path": "XX",
                      "filter": {
                         "term": {
                            "A": "7:140453136:T"
                         }
                      }
                   }
                },
                {
                   "nested": {
                      "path": "XX",
                      "filter": {
                         "term": {
                            "B": "RF"
                         }
                      }
                   }
                },
                {
                   "nested": {
                      "path": "XX",
                      "filter": {
                         "term": {
                            "C": "RFFF"
                         }
                      }
                   }
                }
             ]
          }
       }
    }

The code which i tried:

   QueryBuilders qbWithArguments = QueryBuilders.boolQuery()
                    .must(QueryBuilders.termQuery("A", "RF"))
                    .must(QueryBuilders.termQuery("B", "EF"))
                    .must(QueryBuilders.termQuery("C", "RF"));
like image 339
Abhi.G Avatar asked Dec 24 '22 09:12

Abhi.G


1 Answers

You need to add nested query too. Use below code:

QueryBuilders.boolQuery().must(nestedQuery("XX", FilterBuilders.termFilter("A","RF")))
                             .must(nestedQuery("XX", FilterBuilders.termFilter("B","EF")))
                             .must(nestedQuery("XX", FilterBuilders.termFilter("C","RF")))

For higher versions you can use :

QueryBuilders.boolQuery().must(nestedQuery("XX", QueryBuilders.boolQuery()
           .should(QueryBuilders.termQuery("A","RF"))
           .should(QueryBuilders.termQuery("B","EF"))
           .should(QueryBuilders.termQuery("C","RF"))
           .minimumShouldMatch("1")))

Notes: In 6.7, even if the doc stayed that ScoreMode is optional, you may need to provide this param when using the java QueryBuilders.

like image 86
Richa Avatar answered Feb 09 '23 02:02

Richa