更改elasticsearch的score评分
在某些情况下,我们需要自定义score的分值,从而达到个性化搜索的目的。例如我们通过机器学习可以得到每个用户的特征向量、同时知道每个商品的特征向量,如何计算这两个特征向量的相似度?这个两个特征向量越高,评分越高,从而把那些与用户相似度高的商品优先推荐给用户。
插件源码解读
通过查看官网文档,运行一个脚步必须通过“ScriptEngine”来实现的。为了开发一个自定义的插件,我们需要实现“ScriptEngine”接口,并通过getScriptEngine()这个方法来加载我们的插件。ScriptEngine接口具体介绍见文献[1].下面通过官网给出的一个具体例子:
private static class MyExpertScriptEngine implements ScriptEngine {
//可以命名自己在脚本api中使用的名称来引用这个脚本后端。
@Override
public String getType() {
return "expert_scripts";
}
//核心方法,下面是通过java的lamada表达式来实现的
@Override
public T compile(String scriptName, String scriptSource, ScriptContext context, Map params) {
if (context.equals(SearchScript.CONTEXT) == false) {
throw new IllegalArgumentException(getType() + " scripts cannot be used for context [" + context.name + "]");
}
// we use the script "source" as the script identifier
if ("pure_df".equals(scriptSource)) {
//通过p来获取参数params中的值,lookup得到文档中的的值
SearchScript.Factory factory = (p, lookup) -> new SearchScript.LeafFactory() {
final String field;
final String term;
{
if (p.containsKey("field") == false) {
throw new IllegalArgumentException("Missing parameter [field]");
}
if (p.containsKey("term") == false) {
throw new IllegalArgumentException("Missing parameter [term]");
}
field = p.get("field").toString();
term = p.get("term").toString();
}
@Override
public SearchScript newInstance(LeafReaderContext context) throws IOException {
PostingsEnum postings = context.reader().postings(new Term(field, term));
if (postings == null) {
// the field and/or term don't exist in this segment, so always return 0
return new SearchScript(p, lookup, context) {
@Override
public double runAsDouble() {
return 0.0d;
}
};
}
return new SearchScript(p, lookup, context) {
int currentDocid = -1;
@Override
public void setDocument(int docid) {
// advance has undefined behavior calling with a docid <= its current docid
if (postings.docID() < docid) {
try {
postings.advance(docid);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
currentDocid = docid;
}
@Override
public double runAsDouble() {
if (postings.docID() != currentDocid) {
// advance moved past the current doc, so this doc has no occurrences of the term
return 0.0d;
}
try {
return postings.freq();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
};
}
@Override
public boolean needs_score() {
return false;
}
};
return context.factoryClazz.cast(factory);
}
throw new IllegalArgumentException("Unknown script name " + scriptSource);
}
@Override
public void close() {
// optionally close resources
}
}
通过分析上面的代码,我们给出自己的脚步:
开发自己的脚步v1
package com;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.index.LeafReaderContext;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.