一、需求
es搜索keyWord字段,需要给es指定字段weight加上权重进行排序
es版本:elasticsearch 6.5.0
二、建立测试索引

 curl -XDELETE 'http://flxapp01:9200/local_service'
curl -X PUT '192.168.1.96:9200/local_service?pretty' \
-H 'Accept: application/json,text/plain, */*' \
-H 'Content-Type: application/json;charset=UTF-8' \
-d '{
 "settings": {
  "number_of_shards": 3,
  "number_of_replicas": 2
 },
 "mappings": {
  "local_basic":{
   "properties": {
    "keyWord": {"type": "text"},
    "weight": {"type": "long"},
    "gmtCreate": {"type": "long"},
    "gmtModified": {"type": "text"},
    "type": {"type": "text"}
   }
 }
 }
}'

二、加入测试数据

curl -X POST '192.168.1.59:9200/local_service/local_basic/1' \
-H 'Accept: application/json,text/plain, */*' \
-H 'Content-Type: application/json;charset=UTF-8' \
-d '
{
    "keyWord":"c",
    "weight":1,
    "gmtCreate":10011,
    "gmtModified":"liyingjiea",
     "type":"es"
    }'

三、排序代码
利用painless脚本,利用doc找到对应的索引字段值加上权重,doc[‘weigth’]

curl -XGET 'http://192.168.1.59:9200/es_local_service/_search/?pretty' \
-H 'Accept: application/json,text/plain, */*' \
-H 'Content-Type: application/json;charset=UTF-8' \
-d '{
"query": {
        "match_phrase": {
            "keyWord": "c"
        }
    },
    "sort":[ {
           "_script":{
           "type": "number",
            "script": {
                "source": "def s=0.0;s =  doc['\''weight'\''].value+params.score_percent;return s;",
                "params": {
                    "score_percent": 0.7, 
                    "course_percent": 0.3
                }
        },
        "order": "asc"
     }
  }
  ]
}'

四、问题
在利用linux 的curl 测试过程中出现如下错误

{
  "error" : {
    "root_cause" : [
      {
        "type" : "script_exception",
        "reason" : "compile error",
        "script_stack" : [
          "def s=0.0;s =  doc[weight].value+params.scor ...",
          "                   ^---- HERE"
        ],
        "script" : "def s=0.0;s =  doc[weight].value+params.score_percent;return s;",
        "lang" : "painless"
      }
    ],
    "type" : "search_phase_execution_exception",
    "reason" : "all shards failed",
    "phase" : "query",
    "grouped" : true,
    "failed_shards" : [
      {
        "shard" : 0,
        "index" : "local_service",
        "node" : "sFvc-I-CRSqUw1qlGFiLrA",
        "reason" : {
          "type" : "script_exception",
          "reason" : "compile error",
          "script_stack" : [
            "def s=0.0;s =  doc[weight].value+params.scor ...",
            "                   ^---- HERE"
          ],
          "script" : "def s=0.0;s =  doc[weight].value+params.score_percent;return s;",
          "lang" : "painless",
          "caused_by" : {
            "type" : "illegal_argument_exception",
            "reason" : "Variable [weight] is not defined."
          }
        }
      }
    ]
  },
  "status" : 500
}

在请求参数中,用的是doc[‘weight’] ,没用对单引号进行转义

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐