Search code examples
searchelasticsearchtire

Elastic search order by count of nested object


Beginner with Elasticsearch. I feel like this should be pretty simple, but I'm stuck here. I've got a mapping for Posts that looks like this:

[ post1: {
   title: 'asdfasd',
   comments: [commment1, comment2, comment3]
},
post2: {
   title: 'asdf',
   comments: [comment1, comment2]
}
.
.
.]

And I'm trying to search for them by title and then order them by number of comments. I can search by title just fine, but I'm a little confused as to how to go about ordering the results by comments count. What would be the best way to go about doing this?


Solution

  • You have two options -

    1. Use a script to get the length of an array. So you would do something like:

      {  
        "query" : {  
          ....  
        },  
        "sort" : {  
          "_script" : {  
            "script" : "doc['comments'].values.length",  
            "type" : "number",  
            "order" : "desc"  
          }  
        }  
      }
      
    2. Keep an additional field for the number of comments, each time you add a comment also increment the value of the comments counter, and sort by it.

    Option #2 is preferable if you have a lot of data. Using a script has its overhead and it can increase search time if you have to calculate the script on a large collection of documents. Sorting by a field, on the other hand, is much better in terms of performance. I would go with #2.