4

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?

7
  • Pfff, you'd be much better if you had a single field that would combine the value itself and the name and you'd do a sorting on that. Commented Feb 23, 2018 at 11:02
  • Do you have a known set of names in there? For example, would be feasible to create a field called like_count_value that should contain a value like 9_like_count? Commented Feb 23, 2018 at 11:05
  • I have multiple kinds of engagement values (e.g. share_count, followers, followings, reach etc) so If I create columns then I will have to create new columns every time if a new engagement key comes. Current structure supports any kind of engagement value without creating a new column by just appending key/value in the array. Commented Feb 23, 2018 at 11:13
  • I understand what you say and I understand is way more comfortable like this :-). But, performance wise, you won't be better off with way. Commented Feb 23, 2018 at 11:21
  • I got something like this but it is not working as per expected. { "_source": ["engagement"], "sort": { "engagement.value": { "order": "desc", "nested_filter": { "term": { "engagement.name": "like_count" } } } } } Commented Feb 23, 2018 at 11:49

1 Answer 1

3
+50

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.