Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort nested object in Elasticsearch

I'm using the following mapping:

PUT /my_index
{
  "mappings": {
    "blogpost": {
      "properties": {
        "title": {"type": "string"}
        "comments": {
          "type": "nested", 
          "properties": {
            "comment": { "type": "string"  },
            "date":    { "type": "date"    }
          }
        }
      }
    }
  }
}

Example of document:

PUT /my_index/blogpost/1
{
  "title": "Nest eggs",
  "comments": [ 
    {
      "comment": "Great article",
      "date":    "2014-09-01"
    },
    {
      "comment": "More like this please",
      "date":    "2014-10-22"
    },
    {
      "comment": "Visit my website",
      "date":    "2014-07-02"
    },
    {
      "comment": "Awesome",
      "date":    "2014-08-23"
    }
  ]
}

My question is how to retrieve this document and sort the nested object "comments" by "date"? the result:

PUT /my_index/blogpost/1
{
  "title": "Nest eggs",
  "comments": [ 
    {
      "comment": "Awesome",
      "date":    "2014-07-23"
    },
    {
      "comment": "Visit my website",
      "date":    "2014-08-02"
    },
    {
      "comment": "Great article",
      "date":    "2014-09-01"
    },
    {
      "comment": "More like this please",
      "date":    "2014-10-22"
    }
  ]
}
like image 800
Akram Fares Avatar asked Dec 28 '15 10:12

Akram Fares


1 Answers

You need to sort on the inner_hits to sort the nested objects. This will give you the desired output

GET my_index/_search
{
  "query": {
    "nested": {
      "path": "comments",
      "query": {
        "match_all": {}
      },
      "inner_hits": {
        "sort": {
          "comments.date": {
            "order": "asc"
          }
        },
        "size": 5
      }
    }
  },
  "_source": [
    "title"
  ]
}

I am using source filtering to get only "title" as comments will be retrieved inside inner_hit but you can avoid that if you want

size is 5 because default value is 3 and we have 4 objects in the given example.

Hope this helps!

like image 162
ChintanShah25 Avatar answered Nov 09 '22 00:11

ChintanShah25