private void collapse(Result result, Map<String, Integer> knownCollapses, Result resultSource,
                          String[] collapseFields, Properties queryProperties, int globalCollapseSize) {
        for (Hit unknownHit : resultSource.hits()) {
            if (!(unknownHit instanceof FastHit hit)) {
                result.hits().add(unknownHit);
                continue;
            }

            boolean addHit = true;
            for (String collapseField : collapseFields) {
                Object peek = hit.getField(collapseField);
                String collapseId = peek != null ? peek.toString() : null;
                if (collapseId == null) continue;

                // prepending the fieldname is necessary to distinguish between values in the different collapsefields
                // @ cannot occur in fieldnames
                String collapseKey = collapseField + "@" + collapseId;

                if (knownCollapses.containsKey(collapseKey)) {
                    int numHitsThisField = knownCollapses.get(collapseKey);
                    int collapseSize = getCollapseSize(queryProperties, collapseField, globalCollapseSize);

                    if (numHitsThisField < collapseSize) {
                        ++numHitsThisField;
                        knownCollapses.put(collapseKey, numHitsThisField);
                    } else {
                        addHit = false;
                        // immediate return, so that following collapseFields do not record the fieldvalues of this hit
                        // needed for sequential collapsing, otherwise later collapsefields would remove too many hits
                        break;
                    }
                } else {
                    knownCollapses.put(collapseKey, 1);
                }
            }

            if (addHit)
                result.hits().add(hit);
        }
    }
Collapse logic. Preserves only maxHitsPerField hits
for each unique value of the collapsing parameters.
Uses collapsefields sequentially.
container-search/src/main/java/com/yahoo/prelude/searcher/FieldCollapsingSearcher.java