Mohd Shahid
Mohd Shahid

Reputation: 1606

Elasticsearch sorting by array of objects

I have a column engagement like this along with other columns

record 1

"date":"2017-11-23T06:46:04.358Z",
"remarks": "test1",
"engagement": [
    {
      "name": "comment_count",
      "value": 6
    },
    {
      "name": "like_count",
      "value": 2
    }
  ],
  ....
  ....

record 2

  "date":"2017-11-23T07:16:14.358Z",
  "remarks": "test2",
  "engagement": [
    {
    "name": "comment_count",
    "value": 3
    },
    {
    "name": "like_count",
    "value": 9
    }
  ],
  ....
  ....

I am storing objects in an array format, Now I want to sort the data by desc order of any given object name, e.g. value of like_count or value of share_count.

So if I sort by like_count then 2nd record should come before the 1st record as the value of like_count of the 2nd record is 9 compared to the value of like_count of the first record which is 2.

How to do this in elasticsearch?

Upvotes: 4

Views: 2110

Answers (1)

khaled_gomaa
khaled_gomaa

Reputation: 3412

You should have something like the following:

{
  "query": {
    "nested": { 
      "path": "engagement",
      "filter": {
        ...somefilter...
      }
    }
  },
  "sort": {
    "engagement.name": { 
      "order": "desc",   
      "mode":  "min",   
      "nested_filter": { 
        ...same.filter.as.before
      }
    }
  }
}

Source: Elastic Docs

Upvotes: 3

Related Questions