Returning nested inner hits that don't match the main query in ES 5.x

Hi all,

In the docs for ES 1.x and 2.x, the top level inner hits use case was described as follows: "The main reason for using the top level inner hits definition is to let the inner hits return documents that don’t match with the main query".

Since inner hits was removed in ES 5.x, is there anyway to return an inner hit for results that don't match the main query? The change log docs seem to indicate there is: "Use cases previously only possible with top level inner hits can now be done with inner hits defined inside the query dsl", but the docs don't appear to mention anyway to do it.

My use case is a person doc with a comments nested doc. In my query, I'd like to return:

a. comments that match the query for a user
b. the latest 5 comments the user has made

The query in ES 1/2.x looks something like this:

    "query" : {
        "nested" : {
            "path" : "comments",
            "query" : {
                "match" : {"comments.message" : "Hello world"}
            "inner_hits" : {"name": "search_match_comments"} 
    "inner_hits": {
        "latest_comments": {
            "path": {
                "comments": {
                    "sort": {
                        "comments.created": {
                            "order": "desc",
                            "missing": "_last"
                    "query": {
                        "match_all": {}
                    "size": 4

Any advice on how I can achieve this in ES 5.x?

Thanks heaps!

I guess in this contrived example I could always store the latest 4 comments against the user object to save an extra inner hits query but would still be nice to know if there's anyway to do this in ES 5.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.