
需求背景
當(dāng)不知道怎么去構(gòu)造一個(gè)復(fù)雜到查文檔都查不出所以然的query時(shí),第一個(gè)想到的肯定是插件解決,插件終歸是最靈活又最不靈活的解決方案。插件靈活在可以不受query語(yǔ)法的影響,通過(guò)java/python等來(lái)表達(dá)需求,最終可以形成非常復(fù)雜的query擴(kuò)展,這個(gè)也是es一個(gè)開(kāi)放性的好處。那么不靈活在哪呢?插件做為第三方擴(kuò)展,需要通過(guò)額外安裝的形式來(lái)加載到集群當(dāng)中。當(dāng)用單節(jié)點(diǎn)測(cè)試集群測(cè)試時(shí)可能并不會(huì)覺(jué)得困難,但是當(dāng)?shù)骄€上環(huán)境以后,面對(duì)的是多個(gè)節(jié)點(diǎn)集群的插件安裝部署,需要做集群重啟操作,會(huì)嚴(yán)重影響線上服務(wù)的提供,所以并不能頻繁的迭代插件以達(dá)到更新召回調(diào)整。
這次我把需求概括到最簡(jiǎn)化的方式:
使用doc中的nested嵌套字段來(lái)計(jì)算_score以提供權(quán)重調(diào)整召回排序
即使最終這個(gè)需求經(jīng)過(guò)討論發(fā)現(xiàn)并不需要插件來(lái)實(shí)現(xiàn),但這次插件開(kāi)發(fā)也是很有意義的,為以后靈活定制es的query提供了新思路。我曾經(jīng)介紹過(guò)關(guān)于es2.x版本similartity插件的開(kāi)發(fā),時(shí)過(guò)境遷我們的集群已經(jīng)更新到了6.3.2版本,許多API已經(jīng)完全不一樣了。
一個(gè)小小的吐槽,es插件的API在幾個(gè)小版本之間都發(fā)生了變化,更不要說(shuō)一個(gè)大版本內(nèi)能共用了,6.3.2版本的api和6.8.x的API就已經(jīng)不一樣了。
文檔結(jié)構(gòu)
簡(jiǎn)單點(diǎn),把文檔簡(jiǎn)化成以下的樣子,直接關(guān)注最核心的部分。
{
"_index": "tag_test_v1",
"_type": "_doc",
"_id": "2",
"_version": 1,
"_score": 1,
"_source": {
"tag": {
"31": 1.1111,
"32": 1.1111,
"33": 1.1111,
"34": 1.1111
},
"id": "2"
}
}
上面的文檔有2個(gè)字段,一個(gè)是唯一標(biāo)識(shí)符id,另外一個(gè)就是nested字段tag,tag字段下有n組鍵值對(duì),key為標(biāo)簽id,value為標(biāo)簽分?jǐn)?shù),而要做的事就是,在召回的時(shí)候根據(jù)query對(duì)于tag的命中,來(lái)調(diào)整對(duì)應(yīng)的_score。
先不去想說(shuō)能不能通過(guò)其他方式解決,其實(shí)是有的,但是這次我只是借這個(gè)例子來(lái)鞏固一下關(guān)于去開(kāi)發(fā)es插件來(lái)更靈活定制自己的需求。
字段規(guī)約
在說(shuō)腳本之前首先要聊一下關(guān)于字段規(guī)約,也就是mapping,這里的mapping設(shè)計(jì)有兩個(gè)點(diǎn)是需要注意的,一個(gè)是嵌套字段的mapping設(shè)計(jì),另外一個(gè)有點(diǎn)特殊。仔細(xì)看tag下的鍵值對(duì),并不是固定字段而是動(dòng)態(tài)的,所以要使用動(dòng)態(tài)模板。
mapping = {
"mappings": {
"_doc": {
"properties": {
"id":{
"type": "keyword"
}
},
"dynamic_templates": [
{
"tag":
{
"match": "tag.*",
"match_mapping_type": "double",
"mapping":
{
"type": "double"
}
}
}
]
}
}
}
插件開(kāi)發(fā)
進(jìn)入正題。
- 建立一個(gè)maven類型的項(xiàng)目
- pom文件引入依賴,我這里針對(duì)6.3.2版本做開(kāi)發(fā)
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.3.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.39</version>
</dependency>
</dependencies>
- assembly配置文件,因?yàn)橐獕嚎s成符合es格式的zip包
<?xml version="1.0"?>
<assembly>
<id>tag-plugin</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>${project.basedir}/config</directory>
<outputDirectory>config</outputDirectory>
</fileSet>
</fileSets>
<files>
<file>
<source>${project.basedir}/src/main/resources/plugin-descriptor.properties</source>
<outputDirectory/>
<filtered>true</filtered>
</file>
</files>
<dependencySets>
<dependencySet>
<outputDirectory/>
<useProjectArtifact>true</useProjectArtifact>
<useTransitiveFiltering>true</useTransitiveFiltering>
<excludes>
<exclude>org.elasticsearch:elasticsearch</exclude>
</excludes>
</dependencySet>
</dependencySets>
</assembly>
- 同時(shí)在pom文件下配置用assembly打包
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.6</version>
<configuration>
<appendAssemblyId>false</appendAssemblyId>
<!-- 將resources中的plugin-descriptor.properties放在根目錄下 -->
<outputDirectory>${project.build.directory}/resource/</outputDirectory>
<descriptors><!--assembly使用的配置文件地址 -->
<descriptor>${basedir}/src/main/assemblies/plugin.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
- 外部配置基本完畢,接下來(lái)關(guān)注點(diǎn)都在代碼本身上。首先明確目的,通過(guò)script方式自定義召回打分排序,所以我們需要繼承ScriptPlugin這個(gè)類。建立一個(gè)類做為插件入口
package org.elasticsearch.plugin.analysis.tag;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.plugins.ScriptPlugin;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptEngine;
import java.util.Collection;
public class TagScriptPlugin extends Plugin implements ScriptPlugin{
@Override
public ScriptEngine getScriptEngine(Settings settings, Collection<ScriptContext<?>> contexts) {
return new TagScriptEngine();
}
}
- 接著實(shí)現(xiàn)插件打分的邏輯
package org.elasticsearch.plugin.analysis.tag;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Term;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.SearchScript;
import org.elasticsearch.search.lookup.SourceLookup;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.HashMap;
import java.util.Map;
public class TagScriptEngine implements ScriptEngine{
private static final String SCRIPT_NAME = "tag_weight";
private static final String SCRIPT_SOURCE = "test";
protected final Logger logger = Loggers.getLogger(getClass());
@Override
public String getType() {
return SCRIPT_NAME;
}
@Override
public <FactoryType> FactoryType compile(String name, String code, ScriptContext<FactoryType> context, Map<String, String> params) {
if (!context.equals(SearchScript.CONTEXT)) {
throw new IllegalArgumentException(getType()
+ " scripts cannot be used for context ["
+ context.name + "]");
}
if (!code.equals(SCRIPT_SOURCE)){
throw new IllegalArgumentException("Unknown script name " + code);
}
SearchScript.Factory factory = (p, lookup) -> new SearchScript.LeafFactory() {
final String tag_id;
final String[] tag_ids;
{
if (p.containsKey("tag_id") == false) {
throw new IllegalArgumentException("Missing parameter [tag_id]");
}
tag_id = p.get("tag_id").toString();
tag_ids = tag_id.split(" ");
}
@Override
public SearchScript newInstance(LeafReaderContext context) throws IOException {
return new SearchScript(p, lookup, context) {
@Override
public double runAsDouble() {
SourceLookup source = lookup.source();
Double score = 0d;
logger.info("========" + source.get("tag").getClass().toString() + "=========");
HashMap tag = (HashMap) source.get("tag");
for (String tag_id : tag_ids) {
// 如果沒(méi)獲取標(biāo)簽直接跳過(guò)
if (!tag.containsKey(tag_id)) continue;
score += (Double)(tag.get(tag_id));
}
return score;
}
};
}
@Override
public boolean needs_score() {
return false;
}
};
return context.factoryClazz.cast(factory);
}
@Override
public void close() throws IOException {
}
}
我主要重寫的方法就是runAsDouble,其余的方法還沒(méi)有研究明白可以定制那些東西。修改runAsDouble就可以隨意定制每個(gè)doc的_score。
- 打包上傳運(yùn)行
通過(guò)maven打包,執(zhí)行以下命令
mvn clean package
打成zip包后,上傳到es集群所在的服務(wù)器。來(lái)到es的bin目錄下
安裝插件命令
elasticsearch-plugin install file:///home/tag-plugin-1.0-SNAPSHOT.zip
卸載插件命令
elasticsearch-plugin remove DemoPlugin
查看集群插接件列表
curl http://10.14.12.32:9400/_cat/plugins
注意一個(gè)點(diǎn),安裝插件后需要重啟集群才能加載,插件安裝可以離線進(jìn)行,也就是說(shuō)在關(guān)閉集群的狀態(tài)下也能安裝插件。
8.最后來(lái)到使用查詢環(huán)節(jié)
{
"explain": true,
"from": 0,
"size": 20,
"query": {
"bool": {
"should": [{
"match": {
"id": "21507"
}
}],
"adjust_pure_negative": true,
"minimum_should_match": "1",
"boost": 1
}
},
"rescore": [{
"window_size": 1500,
"query": {
"rescore_query": {
"function_score": {
"query": {
"match_all": {
"boost": 1
}
},
"functions": [{
"script_score": {
"script": {
"source": "test",
"lang": "tag_weight",
"params": {
"tag_id": "32 33"
}
}
}
}],
"score_mode": "multiply",
"boost_mode": "multiply",
"max_boost": 3.4028235e+38,
"boost": 1
}
},
"query_weight": 1,
"rescore_query_weight": 1,
"score_mode": "multiply"
}
}]
}
這里關(guān)鍵的參數(shù)是source和lang,都是我們?cè)诓寮锒x的參數(shù)。這樣一來(lái)doc的打分邏輯便會(huì)跟隨插件中定義的邏輯。我這個(gè)插件的邏輯很簡(jiǎn)單,輸入?yún)?shù)為32 33,doc的分?jǐn)?shù)就是32的值加上33的值,也就是2.2222。
源代碼我上傳到了這里
es插件開(kāi)發(fā)