Skip to content

Commit

Permalink
Forbid negative weight in Function Score Query (#33390)
Browse files Browse the repository at this point in the history
This change forbids negative `weight` in Function Score query. Negative scores are forbidden in Lucene 8.
  • Loading branch information
lipsill authored and jimczi committed Sep 12, 2018
1 parent 4561c5e commit c92ec1c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
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;
Expand All @@ -46,7 +45,7 @@ public ScoreFunctionBuilder() {
* Read from a stream.
*/
public ScoreFunctionBuilder(StreamInput in) throws IOException {
weight = in.readOptionalFloat();
weight = checkWeight(in.readOptionalFloat());
}

@Override
Expand All @@ -70,10 +69,17 @@ public final void writeTo(StreamOutput out) throws IOException {
*/
@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.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -272,6 +273,8 @@ public void testIllegalArguments() {
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 {
Expand Down

0 comments on commit c92ec1c

Please sign in to comment.