# ElasticSearch orderby length of field

**URL:** <https://discuss.elastic.co/t/elasticsearch-orderby-length-of-field/202644>\
**Category:** Elasticsearch\
**Created:** [October 8, 2019, 9:58am UTC](https://discuss.elastic.co/t/elasticsearch-orderby-length-of-field/202644 "2019-10-08T09:58:14Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sanjay\_Agnani](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/sanjay_agnani/32/45398_2.png) [@Sanjay\_Agnani](https://discuss.elastic.co/u/Sanjay_Agnani)\
**Post date:** [October 8, 2019, 9:58am UTC](https://discuss.elastic.co/t/elasticsearch-orderby-length-of-field/202644/1 "2019-10-08T09:58:14Z")

</div>

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);`

---

<div class="post-metadata">

**Author:** ![spinscale](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/spinscale/32/25011_2.png) [@spinscale](https://discuss.elastic.co/u/spinscale)\
**Post date:** [October 8, 2019, 12:06pm UTC](https://discuss.elastic.co/t/elasticsearch-orderby-length-of-field/202644/2 "2019-10-08T12:06:27Z")

</div>

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

```auto
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

```auto
{
  "_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

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [November 5, 2019, 12:06pm UTC](https://discuss.elastic.co/t/elasticsearch-orderby-length-of-field/202644/3 "2019-11-05T12:06:28Z")

</div>

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