Bulding nested query with new Java API

I try to achieve a query like this:

 {
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "metaData.cluster": "mobile"
            }
          }
        },
        {
          "bool": {
            "should": [
              {
                "match": {
                  "city.keyword": "London"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

into the new (8.1.1) Java API. I tried so far something like

BoolQuery bool_query = BoolQuery
				.of(b -> b.must(t -> t.match(r -> r.field("metaData.cluster").query("mobile")))
						.should(s -> s.match(t -> t.field("city.keyword").query("London"))));

But this results in a query whre the "should" is at the same level as the "must". The "should"-query must be underneath the "must" uery.

Any ideas?

Hi @schmermeister

Try this code:

BoolQuery bool_query = BoolQuery
        .of(b -> b
            .must(t -> t.match(r -> r.field("metaData.cluster").query("mobile")))
            .must(t -> t.bool(BoolQuery.of(bq -> bq.should(s -> s.match(m -> m.field("city.keyword").query("London")))))));

Wow, phnatastic, works like a charm. Thank you very much.

1 Like