Elasticsearch v8 Java API client boost Query

I am using new Java API client . I have a method in my code which returns Query of multiple types e.g bool, range


public Query createQuery(String field, String value) {

if(something)
return Query.of(query->query.range(rangeQuery->rangeQuery.field(fieldName).gt(JsonData.of(value))))
else 
retun  new Query.Builder().bool(boolQuery->boolQuery.should(query->query.match(matchQuery->matchQuery.field(fieldName)
                            .query(value))));
}

//Calling that method somewhere
Query resultQuery =  createQuery("field", "value")

but I want to boost the resultQuery, as in Old java client there is QueryBuilder which can be boosted , such as

QueryBuilder resultQuery =  createQuery("field", "value").boost(0.1f)

but there is nothing like that possible with Query like

Query resultQuery =  createQuery("field", "value").boost(0.1f)

I want to provided this Boosted query into disMaxQuery,
please help how i can boost the Query.

Hi @ijaxahmed

A solution would be pass the boost as a parameter.

public Query createQuery(String fieldName, String value, Float boost) {

    if (something) {
      return Query.of(query -> query
          .range(rangeQuery ->
              rangeQuery.field(fieldName).gt(JsonData.of(value))
                  .boost(boost)));
    } else {
      return new Query.Builder()
          .bool(boolQuery -> boolQuery
              .should(query -> query.match(matchQuery -> matchQuery.field(fieldName).query(value)))
              .boost(boost))
          .build();
    }
  }

hmm ok Thanks @RabBit_BR , what happens if Null passed as "boost" parameter, then .boost(null) will be ok or cause exception ??

OR

Instead of null i should pass 0 ? boost(0) wont have any effect ?isnt it?

you can do that:

public static Query createQuery(String fieldName, String value) {
    return createQuery(fieldName, value, 1.0f);
  }

  public static Query createQuery(String fieldName, String value, Float boost) {
....
}

@RabBit_BR ah ok so the default boost is 1.0f ??? :roll_eyes:

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