Skip to content

Commit

Permalink
Scripting: Make _score in groovy scripts comparable
Browse files Browse the repository at this point in the history
  • Loading branch information
rjernst committed Dec 31, 2014
1 parent f83909f commit 6304f68
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
7 changes: 6 additions & 1 deletion src/main/java/org/elasticsearch/script/ScoreAccessor.java
Expand Up @@ -30,7 +30,7 @@
* The provided {@link DocLookup} is used to retrieve the score
* for the current document.
*/
public final class ScoreAccessor extends Number {
public final class ScoreAccessor extends Number implements Comparable<Number> {

Scorer scorer;

Expand Down Expand Up @@ -65,4 +65,9 @@ public float floatValue() {
public double doubleValue() {
return score();
}

@Override
public int compareTo(Number o) {
return Float.compare(this.score(), o.floatValue());
}
}
33 changes: 23 additions & 10 deletions src/test/java/org/elasticsearch/script/GroovyScriptTests.java
Expand Up @@ -117,20 +117,33 @@ public void testGroovyScriptAccess() {
client().prepareIndex("test", "doc", "3").setSource("foo", "dog spiders that can eat a dog", "bar", 3).get();
refresh();

// _score access
SearchResponse resp = client().prepareSearch("test").setQuery(functionScoreQuery(matchQuery("foo", "dog"))
.add(scriptFunction("_score", "groovy"))
.boostMode(CombineFunction.REPLACE)).get();
// doc[] access
SearchResponse resp = client().prepareSearch("test").setQuery(functionScoreQuery(matchAllQuery())
.add(scriptFunction("doc['bar'].value", "groovy"))
.boostMode(CombineFunction.REPLACE)).get();

assertNoFailures(resp);
assertSearchHits(resp, "3", "1");
assertOrderedSearchHits(resp, "3", "2", "1");
}

public void testScoreAccess() {
client().prepareIndex("test", "doc", "1").setSource("foo", "quick brow fox jumped over the lazy dog", "bar", 1).get();
client().prepareIndex("test", "doc", "2").setSource("foo", "fast jumping spiders", "bar", 2).get();
client().prepareIndex("test", "doc", "3").setSource("foo", "dog spiders that can eat a dog", "bar", 3).get();
refresh();

// doc[] access
resp = client().prepareSearch("test").setQuery(functionScoreQuery(matchAllQuery())
.add(scriptFunction("doc['bar'].value", "groovy"))
.boostMode(CombineFunction.REPLACE)).get();
// _score can be accessed
SearchResponse resp = client().prepareSearch("test").setQuery(functionScoreQuery(matchQuery("foo", "dog"))
.add(scriptFunction("_score", "groovy"))
.boostMode(CombineFunction.REPLACE)).get();
assertNoFailures(resp);
assertSearchHits(resp, "3", "1");

// _score is comparable
resp = client().prepareSearch("test").setQuery(functionScoreQuery(matchQuery("foo", "dog"))
.add(scriptFunction("_score > 0 ? _score : 0", "groovy"))
.boostMode(CombineFunction.REPLACE)).get();
assertNoFailures(resp);
assertOrderedSearchHits(resp, "3", "2", "1");
assertSearchHits(resp, "3", "1");
}
}

0 comments on commit 6304f68

Please sign in to comment.