Get grouped results along with siblings not matching the filter criteria

Hi, is it possible to query elastic for documents matching a filter criteria, grouped by a field and also get any sibling documents not matching the filter criteria?
By siblings I mean documents having the same value on the attribute by which results are being grouped by.

Here 's the scenario.

Mapping

PUT my-index-000001
{
  "mappings": {
    "properties": {
      "groupId": { "type": "keyword" },
      "attr": { "type": "keyword" }
    }
  }
}

Documents

POST my-index-000001/_doc
{
  "groupId": "a",
  "attr": "1"
}
POST my-index-000001/_doc
{
  "groupId": "a",
  "attr": "2"
}
POST my-index-000001/_doc
{
  "groupId": "a",
  "attr": "3"
}
POST my-index-000001/_doc
{
  "groupId": "b",
  "attr": "5"
}
POST my-index-000001/_doc
{
  "groupId": "c",
  "attr": "1"
}
POST my-index-000001/_doc
{
  "groupId": "c",
  "attr": "3"
}

Query

POST /my-index-000001/_search
{
    "query": {
        "term": {
            "attr": "3"
        }
    }
}

The result I' d like to get is something like this.

[{
		"groupId": "a",
		"docs": [{
				"groupId": "a",
				"attr": "1"
			},{
				"groupId": "a",
				"attr": "2"
			},{
				"groupId": "a",
				"attr": "3"
			}
		]
	},{
		"groupId": "c",
		"docs": [{
				"groupId": "c",
				"attr": "1"
			},{
				"groupId": "c",
				"attr": "3"
			}
		]
	}
]

You might want to take a look at the top_hits aggregation.

Hey Alex, thanks for replying.

This is what I came up with, I get all documents grouped by groupId
How would I go about filtering by attr=3 and still getting all docs where groupId equals a and c?

POST /my-index-000001/_search
{
    "size": 0,
    "aggs": {
        "docs": {
            "terms": {
                "field": "groupId"
            },
            "aggs": {
                "result": {
                    "top_hits": {}
                }
            }
        }
    }
}

To give more context, I'd like to be able to get documents individually or grouped by groupId.
In case of getting documents grouped by groupId, I'd like to get all documents matching the filter criteria and also having the same groupId.
Hope it makes sense.

Would it make sense to sent a second search request with a proper filter by group id?

You mean to issue a second request filtering by the list of groupIds I get as a result of the first request?

I was hoping to get the data in one go but I guess issuing a second request is my best alternative.

Thanks Alex!

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