# Count distinct groups when using collapse

**URL:** <https://discuss.elastic.co/t/count-distinct-groups-when-using-collapse/333463>\
**Category:** Elasticsearch\
**Created:** [May 15, 2023, 1:11pm UTC](https://discuss.elastic.co/t/count-distinct-groups-when-using-collapse/333463 "2023-05-15T13:11:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dorian-marchal](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dorian-marchal/32/89333_2.png) [@dorian-marchal](https://discuss.elastic.co/u/dorian-marchal)\
**Post date:** [May 15, 2023, 1:11pm UTC](https://discuss.elastic.co/t/count-distinct-groups-when-using-collapse/333463/1 "2023-05-15T13:11:29Z")

</div>

When [collapsing](https://www.elastic.co/guide/en/elasticsearch/reference/current/collapse-search-results.html) results, the total number of hits (using `track_total_hits`) doesn't take collapsing into account, i.e. the total number of documents is returned, not the number of collapsed _groups_.

E.g. if I index 1508540 cars, from 116 brands, this query will return 1508540 in `hits.total.value`:

```auto
GET cars/_search?track_total_hits=true
{
  "collapse": {
    "field": "brand"
  }
}

```

If I want to count groups, I can use the `cardinality` aggregation.  
This query will return the expected 116 in `aggregations.brands_count.value` but this is really slow for large indexes, event with a low `precision_threshold`.

```auto
GET cars/_search?size=0&track_total_hits=false
{
  "aggs": {
    "brands_count": {
      "cardinality": {
        "field": "brand",
        "precision_threshold": 150
      }
    }
  }
}

```

I could create a `brands` index, but in this example, I would need to sort collapsed results based on individual car features, so it would not help me.

I found some Github issues talking about this ([here](https://github.com/elastic/elasticsearch/issues/27556) and [here](https://github.com/elastic/elasticsearch/issues/24130)), but they are from 2017.  
Do we have a way to count groups efficiently now? Is there some known workarounds?

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [June 12, 2023, 1:12pm UTC](https://discuss.elastic.co/t/count-distinct-groups-when-using-collapse/333463/2 "2023-06-12T13:12:02Z")

</div>

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