summaryrefslogtreecommitdiffstats
path: root/container-search/src/main/java/com/yahoo/prelude/searcher/FieldCollapsingSearcher.java
blob: 0559bd808bc103fc72030e8378d366636822c1e6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.searcher;

import com.yahoo.component.annotation.Inject;
import com.yahoo.component.chain.dependencies.After;
import com.yahoo.component.chain.dependencies.Before;
import com.yahoo.container.QrSearchersConfig;
import com.yahoo.prelude.fastsearch.FastHit;
import com.yahoo.processing.request.CompoundName;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.query.Properties;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.PhaseNames;

import java.util.Arrays;
import java.util.Map;

/**
 * A searcher which does parameterized collapsing.
 *
 * @author Steinar Knutsen
 */
@After(PhaseNames.RAW_QUERY)
@Before(PhaseNames.TRANSFORMED_QUERY)
public class FieldCollapsingSearcher extends Searcher {

    private static final CompoundName collapse = CompoundName.from("collapse");
    private static final CompoundName collapsefield = CompoundName.from("collapsefield");
    private static final CompoundName collapsesize = CompoundName.from("collapsesize");
    private static final CompoundName collapseSummaryName = CompoundName.from("collapse.summary");

    /** Separator used for the fieldnames in collapsefield */
    private static final String separator = ",";

    /** Maximum number of queries to send next searcher */
    private static final int maxQueries = 4;

    /**
     * The max number of hits that will be preserved per unique
     * value of the collapsing parameter,
     * if no field-specific value is configured.
     */
    private int defaultCollapseSize;

    /**
     * The factor by which to scale up the requested number of hits
     * from the next searcher in the chain, because collapsing will
     * likely delete many hits.
     */
    private double extraFactor;

    /** Create this searcher using default values for all settings */
    public FieldCollapsingSearcher() {
        this(1, 2.0);
    }

    @Inject
    @SuppressWarnings("unused")
    public FieldCollapsingSearcher(QrSearchersConfig config) {
        QrSearchersConfig.Com.Yahoo.Prelude.Searcher.FieldCollapsingSearcher
                s = config.com().yahoo().prelude().searcher().FieldCollapsingSearcher();

        init(s.collapsesize(), s.extrafactor());
    }

    /**
     * Creates a collapser
     *
     * @param collapseSize the maximum number of hits to keep per
     *        field the default max number of hits in each collapsed group
     * @param extraFactor the percentage by which to scale up the
     *        requested number of hits, to allow some hits to be removed
     *        without refetching
     */
    public FieldCollapsingSearcher(int collapseSize, double extraFactor) {
        init(collapseSize, extraFactor);
    }

    private void init(int collapseSize, double extraFactor) {
        this.defaultCollapseSize = collapseSize;
        this.extraFactor = extraFactor;
    }

    /**
     * First fetch result from the next searcher in the chain.
     * If collapse is active, do collapsing.
     * Otherwise, act as a simple pass through
     */
    @Override
    public Result search(com.yahoo.search.Query query, Execution execution) {
        String collapseFieldParam = query.properties().getString(collapsefield);

        if (collapseFieldParam == null) return execution.search(query);

        String[] collapseFields = collapseFieldParam.split(separator);

        int globalCollapseSize = query.properties().getInteger(collapsesize, defaultCollapseSize);

        query.properties().set(collapse, "0");

        int hitsToRequest = query.getHits() != 0 ? (int) Math.ceil((query.getOffset() + query.getHits() + 1) * extraFactor) : 0;
        int nextOffset = 0;
        int hitsAfterCollapse;
        boolean moreHitsAvailable = true;
        Map<String, Integer> knownCollapses = new java.util.HashMap<>();
        Result result = new Result(query);
        int performedQueries = 0;
        Result resultSource;
        String collapseSummary = query.properties().getString(collapseSummaryName);
        String summaryClass = (collapseSummary == null)
                              ? query.getPresentation().getSummary() : collapseSummary;
        query.trace("Collapsing by '" + Arrays.toString(collapseFields) + "' using summary '" + collapseSummary + "'", 2);

        do {
            resultSource = search(query.clone(), execution, nextOffset, hitsToRequest);
            fill(resultSource, summaryClass, execution);

            collapse(result, knownCollapses, resultSource,
                collapseFields, query.properties(), globalCollapseSize
            );

            hitsAfterCollapse = result.getHitCount();
            if (resultSource.getTotalHitCount() < (hitsToRequest + nextOffset)) {
                // the searcher downstream has no more hits
                moreHitsAvailable = false;
            }
            nextOffset += hitsToRequest;
            if (hitsAfterCollapse < query.getOffset() + query.getHits()) {
                hitsToRequest = (int) Math.ceil(hitsToRequest * extraFactor);
            }
            ++performedQueries;

        } while (hitsToRequest != 0
                && (hitsAfterCollapse < query.getOffset() + query.getHits())
                && moreHitsAvailable
                && (performedQueries <= maxQueries));

        // Set correct meta information
        result.mergeWith(resultSource);
        // Keep only (offset,.. offset+hits) hits
        result.hits().trim(query.getOffset(), query.getHits());
        // Mark query as query with collapsing
        query.properties().set(collapse, "1");
        return result;
    }

    private Result search(Query query, Execution execution, int offset, int hits) {
        query.setOffset(offset);
        query.setHits(hits);
        return execution.search(query);
    }

    /**
     * Collapse logic. Preserves only maxHitsPerField hits
     * for each unique value of the collapsing parameters.
     * Uses collapsefields sequentially.
     */
    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);
            }
        }
    }

    private int getCollapseSize(Properties properties, String fieldName, int globalCollapseSize) {
        Integer fieldCollapseSize = properties.getInteger(collapsesize.append(fieldName));

        if (fieldCollapseSize != null) {
            return fieldCollapseSize;
        }

        return globalCollapseSize;
    }
}