ElasticSearch orderby length of field

Hello there , i have any elasticSearch Index with an requirement where field needs to be sorted based on it's length.
Have used below aggregate:

{
  "size": 0,
  "aggs": {
    "groupByMake": {
      "terms": {
        "field": "make.keyword",
        "size": 100,
        "order": {
          "_term": "asc"
        }
      }, "aggs": {
    "makeCount": {
      "terms": {
        "script": """doc['make.keyword'].size()==0? "empty":doc['make.keyword'].value.length()""",
        "order": {
          "_key": "asc"
        }
      }
     
    }
  }
      
    }
  }
}

but it just sorts irrespective of length of it's columns .

In comparision to SQL : I want resultset for
SELECT * FROM table ORDER BY length(column);

Doing this during query time will be pretty slow. If you keep running this query, doing this on index time sounds way better to me. You could use an ingest processor to do this, see this example

PUT _ingest/pipeline/count_length
{
  "processors": [
    {
      "script": {
        "source": "ctx.keyword_length = ctx.make.length();"
      }
    }
  ]
}

PUT foo/_doc/1?pipeline=count_length
{
  "make" : "this are a few chars"
}

GET foo/_doc/1

output of the last get call is

{
  "_index" : "foo",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 2,
  "_seq_no" : 1,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "keyword_length" : 20,
    "make" : "this are a few chars"
  }
}

hope this helps as a starter

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.