How to add another condition to SearchRequest.Builder in Java API

For new Java API, If I want to make a search like below:

my code below, but I will set range and terms in different place, how should I combination the second setting to exist condition.
In my code, the second .query() will replace the first one.

SearchRequest.Builder builder = new SearchRequest.Builder();
builder.index("index1").query(qu->qu.bool(f->f.filter(r->r.range(rq->rq.field("PostDate").from("2022-02-01T13:30:01.000").to("2022-02-07T13:30:01.999")))));
......
List<FieldValue> data = new ArrayList<FieldValue>();
data.add(FieldValue.of( "news"));
builder.query(qu->qu.bool(f->f.filter(ft->ft.terms(ts->ts.field("Type").terms(TermsQueryField.of(t->t.value(data)))))));

Hi @cchuang4

I don't know if it's the best option, but what I would do is have a single point where I build the SearchRequest (it can be a method) and receive a BoolQuery object as a parameter.

Who will build this BoolQuery would be responsible for receiving the other clauses, in your case the rangeQuery and TermsQuery.

    var rangeQuery = RangeQuery.of(rq -> rq.field("PostDate").from("2022-02-01T13:30:01.000").to("2022-02-07T13:30:01.999"))._toQuery();

    List<FieldValue> data = new ArrayList<FieldValue>();
    data.add(FieldValue.of("news"));
    var termsQuery = TermsQuery.of(ts -> ts.field("Type").terms(TermsQueryField.of(t -> t.value(data))))._toQuery();

    var boolQuery = BoolQuery.of(bq -> bq.filter(rangeQuery, termsQuery));

    SearchRequest builder = SearchRequest.of(sr ->
        sr.index("index1").query(q -> q.bool(boolQuery))
    );

Thank you, I got the point of how to combine different condition.

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.