首页 > 解决方案 > Elasticsearch 按文本长度排序

问题描述

我在 kibana 上使用 elasticsearch 7.13 和代码

这是我的映射

{
   "full_text" : {
      "properties" : {
          "title" : {
              "type" : "text",
              "fielddata" : true
          },
      }
   }
}

这是我的数据

"full_text" : [
  {
    "title" : "Pkd chuyên cho thuê kingdom 101 1pn đến 3pn giá rẻ nhất thị trường chỉ 11 triệu/căn. lh 0919504***"
  }
]

这是我按 full_text.title 长度排序的代码

"sort": {
   "_script": {
      "type": "number",
      "order": "desc",
      "script": {
         "lang": "painless",
         "source": "doc['full_text.title'].value.length()"
       }
   }
}

那么为什么排序结果只返回 7 呢?

"_source" : {
     "full_text" : [
        {
           "title" : "Pkd chuyên cho thuê kingdom 101 1pn đến 3pn giá rẻ nhất thị trường chỉ 11 triệu/căn. lh 0919504***"
        }
     ]
 },
 "sort": [
     7.0
 ]

标签: sortingelasticsearchkibana

解决方案


因为 doc['full_text.title'] 会将“title”拆分为数组,因此您需要将该数组加入字符串。试试这个:

"source": "int length = String.join(' ',doc['full_text.title']).length(); return length;"

推荐阅读