Native (Java) Scripts
Elastic 提供丰富的排序,大部分基于TF/IDF计算score。然后有时业务需要自定义排序,就是根据一个规则来计算score,然后根据这个score进行排序。目前实现自定义排序有两种方案:
- Function Score
- Script
1.1 Groovy scripts
1.2 Native Scripts
本文重点介绍以Native Scripts插件的形式实现Elatic 自定义排序。
注意:Elastic版本更新比较快,在不同版本实现方式不一样。在参考本文时候注意Elastic的版本。Native Scripts在5.0~5.4可以正常使用,在5.5版本中被弃用,6.0版本完全被移除。使用Elastic 5.5版本以上需要使用ScriptEngine。
- Sometimes groovy and expression aren’t enough. For those times you can implement a native script.
- Native Scripts were deprecated in v5.5.0 and removed in v6.0.0。Consider migrating your native scripts to the ScriptEngine.
自定义排序实现
使用ScriptPlugin插件实现一个简单排序:
定义一个”feature”字段,而该字段的打分规则由我们自己制定。其规则如下:
- 如果查询字段feature与被查询字段feature长度相等,此时被查询的文档得分90
- 如果查询字段feature长度比被查询字段feature长度小,此时被查询的文档得分60
- 如果查询字段feature长度比被查询字段feature长度大,此时被查询的文档得分30
Java代码实现
参考 Native(Java)Scripts帮助文档, 其代码实现如下:
package com.zz.localservice.es.plugin;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.ScriptPlugin;
import org.elasticsearch.script.AbstractDoubleSearchScript;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.NativeScriptFactory;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: smartfly2017
* Date: 2017/10/16
* Time: 15:53
* Description:
* To change this template use File | Settings | File Templates | Includes | File Header
*/
public class MyNativeScriptPlugin extends Plugin implements ScriptPlugin{
private final static Logger logger = LogManager.getLogger(MyNativeScriptPlugin.class);
@Override
public List<NativeScriptFactory> getNativeScripts() {
return Collections.singletonList(new MyNativeScriptFactory());
}
public static class MyNativeScriptFactory implements NativeScriptFactory {
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) {
String feature = params == null ? null : XContentMapValues.nodeStringValue(params.get("feature"), null);
if (feature == null){
logger.info("feature is null!");
}
return new MyNativeScript(feature);
}
@Override
public boolean needsScores() {
return false;
}
@Override
public String getName() {
return "my_script";
}
}
public static class MyNativeScript extends AbstractDoubleSearchScript {
private final String feature;
public MyNativeScript(String feature) {
this.feature = feature;
}
@Override
public double runAsDouble() {
String sourceFeature = (String) source().get("feature");
int len1 = feature.length();
int len2 = sourceFeature.length();
if (len1 == len2){
return 90;
} else if (len1 < len2){
return 60;
}