When you enable the facetingAfterDistinct parameter in your search queries, you may see facet counts that look inconsistent with the number of hits after you refine on that facet. For example, a facet value might show a count of 2, but when you select that facet, you see more than 2 hits.
This behavior is expected when using distinct and facetingAfterDistinct together.
https://www.algolia.com/doc/api-reference/api-parameters/facetingAfterDistinct/#usage-notes
By default, facet counts are computed before applying distinct. When you set facetingAfterDistinct=true, facet counts are computed after applying distinct, so they are based on the deduplicated result set instead of all matching records.
At the same time, distinct groups records by the attribute configured in attributeForDistinct and keeps only the most relevant record (or top N records) per group. Facet counts with facetingAfterDistinct=true are therefore computed from the representative record(s) of each group, not from every record in the group.
If records in the same group don’t share the same facet values, facet counts can look inconsistent:
For each distinct group, only the kept record(s) contribute their facet values to the counts.
If another record in the same group matches a given facet value but isn’t the top-ranked variant, that group won’t be counted for that facet value.
When you then filter on that facet, the search may return more groups than were initially counted for that facet value, because the ranking and selected variant within each group can change with the new filters.
For example, suppose:
attributeForDistinct = "id"distinct = 1You facet on
options.sizeand usefacetingAfterDistinct=true.
After deduplication, there are 3 unique id values. Only 2 of the top-ranked records for these groups have options.size = "toddler", so the facet count for "toddler" is 2. The third id has a different top-ranked variant (with a different options.size), even though another record in that group has "toddler". When you filter on options.size = "toddler", the search can return all 3 groups, so you see more hits than the original facet count suggested.
To avoid these inconsistent counts:
Only use
facetingAfterDistinct=trueif all records sharing the same distinct key have identical facet values. Otherwise, facet counts may appear inconsistent.In order to handle variant data with multiple attributes for faceting, set
afterDistinctonly on facet attributes that are shared between all variants instead of enablingfacetingAfterDistinctfor all facets, and hide the counts for others in your UI.
If this doesn’t match your situation, there are other possible causes of facet and hit count discrepancies. In that case, refer to the Facet and hit count issues checklist for additional troubleshooting steps.