Forbid negative `weight` in Function Score Query (#33390)
This change forbids negative `weight` in Function Score query. Negative scores are forbidden in Lucene 8.
This commit is contained in:
parent
4561c5ee83
commit
c92ec1c5d7
|
@ -24,7 +24,6 @@ import org.elasticsearch.common.io.stream.StreamInput;
|
|||
import org.elasticsearch.common.io.stream.StreamOutput;
|
||||
import org.elasticsearch.common.lucene.search.function.ScoreFunction;
|
||||
import org.elasticsearch.common.lucene.search.function.WeightFactorFunction;
|
||||
import org.elasticsearch.common.xcontent.ToXContent.Params;
|
||||
import org.elasticsearch.common.xcontent.ToXContentFragment;
|
||||
import org.elasticsearch.common.xcontent.XContentBuilder;
|
||||
import org.elasticsearch.index.query.QueryShardContext;
|
||||
|
@ -46,7 +45,7 @@ public abstract class ScoreFunctionBuilder<FB extends ScoreFunctionBuilder<FB>>
|
|||
* Read from a stream.
|
||||
*/
|
||||
public ScoreFunctionBuilder(StreamInput in) throws IOException {
|
||||
weight = in.readOptionalFloat();
|
||||
weight = checkWeight(in.readOptionalFloat());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -70,10 +69,17 @@ public abstract class ScoreFunctionBuilder<FB extends ScoreFunctionBuilder<FB>>
|
|||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public final FB setWeight(float weight) {
|
||||
this.weight = weight;
|
||||
this.weight = checkWeight(weight);
|
||||
return (FB) this;
|
||||
}
|
||||
|
||||
private Float checkWeight(Float weight) {
|
||||
if (weight != null && Float.compare(weight, 0) < 0) {
|
||||
throw new IllegalArgumentException("[weight] cannot be negative for a filtering function");
|
||||
}
|
||||
return weight;
|
||||
}
|
||||
|
||||
/**
|
||||
* The weight applied to the function before combining.
|
||||
*/
|
||||
|
|
|
@ -20,6 +20,7 @@
|
|||
package org.elasticsearch.index.query.functionscore;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
|
||||
import org.apache.lucene.index.Term;
|
||||
import org.apache.lucene.search.MatchAllDocsQuery;
|
||||
import org.apache.lucene.search.Query;
|
||||
|
@ -272,6 +273,8 @@ public class FunctionScoreQueryBuilderTests extends AbstractQueryTestCase<Functi
|
|||
FunctionScoreQueryBuilder builder = new FunctionScoreQueryBuilder(matchAllQuery());
|
||||
expectThrows(IllegalArgumentException.class, () -> builder.scoreMode(null));
|
||||
expectThrows(IllegalArgumentException.class, () -> builder.boostMode(null));
|
||||
expectThrows(IllegalArgumentException.class,
|
||||
() -> new FunctionScoreQueryBuilder.FilterFunctionBuilder(new WeightBuilder().setWeight(-1 * randomFloat())));
|
||||
}
|
||||
|
||||
public void testParseFunctionsArray() throws IOException {
|
||||
|
|
Loading…
Reference in New Issue