public class PriceSorterEngine implements ScriptEngine {
protected final Logger logger = Loggers.getLogger(PriceSorterEngine.class, "PriceSorterEngineLog");
@Override
public String getType() {
return PriceSorterConfig.SCRIPT_NAME;
}
@Override
public <FactoryType> FactoryType compile(String s, String s1, ScriptContext<FactoryType> scriptContext, Map<String, String> map) {
if (!scriptContext.equals(ScoreScript.CONTEXT)) {
throw new IllegalArgumentException(getType()
+ " scripts cannot be used for context ["
+ scriptContext.name + "]");
}
if (!s1.equals(PriceSorterConfig.SCRIPT_SCORE)){
throw new IllegalArgumentException("Unknown script name " + s1);
}
ScoreScript.Factory factory = ((p, searchLookup) -> new ScoreScript.LeafFactory() {
@Override
public boolean needs_score() {
return false;
}
@Override
public ScoreScript newInstance(LeafReaderContext leafReaderContext) throws IOException {
return new ScoreScript(p, searchLookup, leafReaderContext) {
@Override
public double execute(ExplanationHolder explanationHolder) {
// 获取原始分数
double rawScore = this.get_score();
searchLookup.doc();
// 获取文档信息
SourceLookup lookup = searchLookup.source();
// 获取原文
Map<String, Object> sourceMap = lookup.loadSourceIfNeeded();
int docId = lookup.docId();
[b] sourceMap.put("test", "我是被强加进来滴");
lookup.setSource(sourceMap);
searchLookup.source().setSource(sourceMap);
searchLookup.source().loadSourceIfNeeded().put("test", "我是被强加进来滴");[/b]
return Math.random();
}
};
}
});
return scriptContext.factoryClazz.cast(factory);
}
@Override
public Set<ScriptContext<?>> getSupportedContexts() {
Set<ScriptContext<?>> set = new HashSet<>();
set.add(FilterScript.CONTEXT);
return set;
}
}
以上是我自定义插件的源码,我希望在算分的过程中,同步处理一些统计的count值,并向原文doc追加一个字段进去,但是按以上三种方式(代码中加粗,或以下)写都没用。求教,是脚本插件不能做这个事儿,还是我操作的姿势不对呢?
sourceMap.put("test", "我是被强加进来滴"); lookup.setSource(sourceMap); searchLookup.source().setSource(sourceMap); searchLookup.source().loadSourceIfNeeded().put("test", "我是被强加进来滴");
2 个回复
Charele - Cisco4321
赞同来自:
searchLookup.doc();
// 获取文档信息
SourceLookup lookup = searchLookup.source();
// 获取原文
Map<String, Object> sourceMap = lookup.loadSourceIfNeeded();
1 SearchLookup类没有doc()这个方法
2 SourceLookup类也没有loadSourceIfNeeded()这个方法
(我的是ES7.12.0)
laoyang360 - 《一本书讲透Elasticsearch》作者,Elastic认证工程师 [死磕Elasitcsearch]知识星球地址:http://t.cn/RmwM3N9;微信公众号:铭毅天下; 博客:https://elastic.blog.csdn.net
赞同来自:
1、 脚本方式检索的时候指定新的字段;
2、预处理的方式,写入钱拼凑出新的字段。