Q:

How should I write the query to get only nested properties in elasticsearch

I have the index as below.
{
    "id": {
        "type": "keyword"
    },
    "title": {
        "type": "text"
    },
    "comments": {
        "type": "nested"
    }
}

And I put some docs as below.
{
    "id": 1,
    "title": "Types",
    "comments": [
        {
            "id": 113,
            "contents": "Number"
        },
        {
            "id": 2005,
            "contents": "String"
        },
        {
            "id": 317,
            "contents": "Boolean"
        }
    ]
}
{
    "id": 2,
    "title": "Animals",
    "comments": [
        {
            "id": 45,
            "contents": "Dog"
        },
        {
            "id": 175,
            "contents": "Cat"
        },
        {
            "id": 26,
            "contents": "Pig"
        }
    ]
}
{
    "id": 3,
    "title": "Colors",
    "comments": [
        {
            "id": 97,
            "contents": "Red"
        },
        {
            "id": 28,
            "contents": "Green"
        },
        {
            "id": 56,
            "contents": "Blue"
        }
    ]
}

When I use a nested query as below that the total count is just 3 but I want to get the 9 (All about nested properties).
{
    "query": {
        "nested": {
            "path": "comment",
            "query": {
                "match_all": {}
            }
        }
    }
}

I got the result as below.
{
    "hits": {
        "total": 3,
        "hits": [
            {
                "_source": {
                    "id": 1,
                    "title": "Types",
                    "comments": [...]
                }
            },
            {
                "_source": {
                    "id": 2,
                    "title": "Animals",
                    "comments": [...]
                }
            },
            {
                "_source": {
                    "id": 3,
                    "title": "Colors",
                    "comments": [...]
                }
            }
        ]
    }
}

But I wanted the result is like below format.
{
    "hits": {
        "total": 9,
        "hits": [
            {
                "_source": {
                    "id": 113,
                    "contents": "Number"
                }
            },
            ...,
            {
                "_source": {
                    "id": 56,
                    "contents": "Blue"
                }
            }
        ]
    }
}

How should I write the query to get the only 9 nested properties as I wanted result like above?

A:

You need to use nested inner_hits like this:
{
    "_source": false,              <-- add this to prevent the parent doc from showing up
    "query": {
        "nested": {
            "path": "comment",
            "query": {
                "match_all": {}
            },
            "inner_hits": {}       <-- and this to only show the matching nested documents
        }
    }
}

