Created
June 23, 2011 22:12
-
-
Save tsxn26/1043766 to your computer and use it in GitHub Desktop.
Using Native Scripts in Elastic Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1) Extend AbstractFloatSearchScript: | |
package com.example.elastic; | |
import org.elasticsearch.script.AbstractFloatSearchScript; | |
import static java.lang.Math.*; | |
public class MySearchScript extends AbstractFloatSearchScript { | |
@Override | |
public float runAsFloat() { | |
int daysSinceRelease = doc().numeric("daysSinceRelease").getIntValue(); | |
return score() + 0.033f * ((float) | |
( | |
0.4 * ( | |
-150.0 * pow(max(daysSinceRelease - -30000.0, 0), 0.000001) * pow(max(-1826.0 - daysSinceRelease, 0), 0.000001) | |
) | |
) | |
); | |
} | |
} | |
2) Extend NativeScriptFactory: | |
package com.example.elastic; | |
import org.elasticsearch.common.Nullable; | |
import org.elasticsearch.script.ExecutableScript; | |
import org.elasticsearch.script.NativeScriptFactory; | |
import java.util.Map; | |
public class MyScriptFactory implements NativeScriptFactory { | |
@Override public ExecutableScript newScript(@Nullable Map<String, Object> params) { | |
return new MySearchScript(); | |
} | |
} | |
3) Create a jar with the two classes | |
4) Place jar in $ES_HOME/lib or $ES_HOME/plugins/SOME_NAME | |
5) Add to $ES_HOME/config/elasticsearch.yml | |
script.native.foo.type: | |
com.example.elastic.MySearchScript | |
Where foo is the alias for your script. Name it whatever you want. | |
6) Issue your custom query e.g.: | |
curl -XGET 'http://localhost:9200/media/object/_search' -d '{"explain" : true, "query":{"custom_score":{ "query":{ "query_string":{ "fields" : ["title^1.5", "alt_title^0.3", "objectType^0.05"], "use_dis_max": "true", "query":"honda civic" } }, "lang":"native", "script":"foo" } } }' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment