ElasticSearch 自定义排序处理

使用function_score进行分组处理,利用分组函数script_score进行自定义分值处理,

注意:使用script功能需要在配置中打开脚本功能:

 script.inline: on  
 script.indexed: on
 script.engine.groovy.inline.aggs: on  
 script.file: on

下图中的查询表示,查询termid为1238218的记录,或者displayname包含“宝宝”的记录;

termid为1238218的记录排序分人为设定为100,displayname等于“宝宝”的记录分值设定为99,其他按照displaynamelen排序;

{
  "query": {
    "function_score": {
      "filter": {
        "bool": {
          "should": [
            {
              "term": {
                "termid": "1238218"
              }
            },
            {
              "match_phrase": {
                "displayname": "宝宝"
              }
            }
          ]
        }
      },
      "functions": [
        {
          "filter": {
            "term": {
              "termid": "1238218"
            }
          },
          "weight": 100
        },
        {
          "filter": {
            "term": {
              "displayname": "宝宝"
            }
          },
          "weight": 99
        },
        {
          "script_score": {
            "script": "_score + doc['level'].value"
          }
        }
      ],
      "score_mode": "first"
    }
  }
}
原文地址:https://www.cnblogs.com/thaughtZhao/p/5552735.html