Elasticsearch自定排序插件实现

时间:2022-09-13 00:14:58

Elasticsearch自定排序插件实现

本文将介绍以插件的形式实现Elasticsearch自定义排序。

整个插件项目的结构为

12345678910111213 project--src----main--------assemblies------------plugin.xml--------java------------com.dcharm.plugin----------------NativeScriptPlugin.java----------------JyhBaseScriptFactory.java--------resources------------es-plugin.properties----test--pom.xml

下面会介绍各个文件的内容
1.pom.xml
pom.xml添加对Elasticsearch并且设置打包的方式,打包的方式引用了plugin.xml

12345678910111213141516171819202122232425262728293031    <dependencies>       <dependency>           <groupId>org.elasticsearch</groupId>           <artifactId>elasticsearch</artifactId>           <version>${es.version}</version>           <scope>compile</scope>       </dependency>  </dependencies><build>       <plugins>           <plugin>               <artifactId>maven-assembly-plugin</artifactId>               <version>2.3</version>               <configuration>                   <appendAssemblyId>false</appendAssemblyId>                   <outputDirectory>${project.build.directory}/releases/</outputDirectory>                   <descriptors>                       <descriptor>${basedir}/src/main/assemblies/plugin.xml</descriptor>                   </descriptors>               </configuration>               <executions>                   <execution>                       <phase>package</phase>                       <goals>                           <goal>single</goal>                       </goals>                   </execution>               </executions>           </plugin>       </plugins>   </build>

2.plugin.xml
plugin.xml指定了插件打包的方式

123456789101112131415161718 <?xmlversion="1.0"?><assembly>    <id>plugin</id>    <formats>        <format>zip</format>    </formats>    <includeBaseDirectory>false</includeBaseDirectory>    <dependencySets>        <dependencySet>            <outputDirectory>/</outputDirectory>            <useProjectArtifact>true</useProjectArtifact>            <useTransitiveFiltering>true</useTransitiveFiltering>            <excludes>                <exclude>org.elasticsearch:elasticsearch</exclude>            </excludes>        </dependencySet>    </dependencySets></assembly>

3.NativeScriptPlugin类

1234567891011121314151617 publicclass
NativeScriptPlugin
extendsAbstractPlugin {
    @Override    publicString name() {        return"native-script";//native-script为插件的名称    }     @Override    publicString description() {        return"native scripts";    }     publicvoid
onModule(ScriptModule module) {
        //m2c_jyh_default就是排序算法的名称        module.registerScript("m2c_jyh_default", JyhBaseScriptFactory.class);    } }

4.JyhBaseScriptFactory类

1234567891011121314151617181920212223242526272829303132 publicclass
JyhBaseScriptFactory
implementsNativeScriptFactory {
    @Override    publicExecutableScript newScript(@NullableMap<String, Object> params) {        returnnew
JyhScript(params);
    }     protectedclass
JyhScript
extendsAbstractDoubleSearchScript {
        privatedouble
price;
        privateString category;         //params就是搜索请求中传入的参数        publicJyhScript(@NullableMap<String,Object> params){            this.price = (Double)params.get("price");            this.category = (String)params.get("category");        }         @Override        publicdouble
runAsDouble() {
            //iismerchant对应着doc values中iismerchant字段的值            longiismerchant = ((ScriptDocValues.Longs)doc().get("iismerchant")).getValue();            doublescore = 30;            if(iismerchant == 1) {                score += 20;            }            else{                score += this.price;            }            score = score < 0?0: score;            returnscore;        }    }}

5.es-plugin.properties
在src/main/resources下新增es-plugin.properties文件

1 plugin=com.dcharm.NativeScriptPlugin

6.打包
插件打包的方式和一般的maven项目相同,使用下面的命令

1 mvn
clean
install

打包后,插件为target/release目录下的project.zip文件

7.安装

1 bin/elasticsearch-plugin--urlfile:///path-to-target/project.zip --installnative-script

其中native-script为插件的名称


bin/elasticsearch-plugin--urlfile:///path-to-target/project.zip --installnative-script

安装的时候一定要注意这个路径的写法:file:///
我在这掉坑里了。


8.调用排序插件
调用自定义排序时,需要指定实现方式为native,排序名称为m2c_jyh_default

12345678910111213141516171819202122232425 curl
-XPOST localhost:9200
/m2c/item/_search-d '{
  "fields": ["id","sproduct"],  "from": 0,  "size": 1,  "query": {    "function_score": {      "query": {        "match": {"sproduct":"nike"}      },      "functions": [        {          "script_score": {            "lang":"native",            "script":"m2c_jyh_default",              "params": {              "price": 10.0,              "category":"12 34"            }          }        }      ],      "boost_mode":"replace"    }  }}'

上面的请求访问的是我自己测试用的索引m2c,大家在尝试的时候可以自己建立其他的索引。