Elasticsearch Sort By Length Of Text

Viewed 256

I'm using elasticsearch 7.13 and code on kibana

This is my mapping

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

This is my data

"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***"
  }
]

This is my code to sort by length of full_text.title

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

So why sort result return only 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
 ]
1 Answers

Because doc['full_text.title'] will split "title" into array, you need to join that array to string. Try this:

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