javaelasticsearchbuilderapiclient

Create TermsQuery with List<String> using elasticsearch java api client


I have an elastic search query as below.

{
   "query":{
      "bool":{
         "filter":{
            "bool":{
               "must_not":{
                  "terms":{
                     "names":[
                        "john",
                        "jose"
                     ]
                  }
               }
            }
         }
      }
   }
}

I am trying to build something like this in the code corresponding to the query.

BoolQuery.Builder builder = new BoolQueryBuilder();
List<String> names = ["john","jose"];
TermsQueryField field = new TermsQueryBuilder().value(names).build();
builder.mustNot(TermsQuery.of(t -> t.field("names").terms(field))._toQuery());

But I am getting error in this line as it is expecting List of FieldValue inside value function and not List of String.

TermsQueryField field = new TermsQueryBuilder().value(names).build();

Can someone help on this?


Solution

  • you need to use below code to create fieldValues for your names

    List<FieldValue> fieldValues = names.stream().map(FieldValue::of).toList();