10

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"
    }
  ]
}
2
  • what version of ES you are using? this is weird, I followed this link and it is not working. I am not sure if this is bug, might be related to this issue Commented Dec 28, 2015 at 14:56
  • That's not my question, i don't want to filter "by" nested field, i want to sort "the" nested field. ES version 1.7 Commented Dec 28, 2015 at 16:18

1 Answer 1

15

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!

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

1 Comment

So size here only limits how many comments we want to display (sorted by date) ? So if I specify "size": 1 then I'll get the first (the oldest) message, aren't I ? Thx in advance !

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.