aboutsummaryrefslogtreecommitdiffstats
path: root/searchlib/src/vespa/searchlib/queryeval/nearsearch.cpp
blob: 1ac715ca92dddc8e320ac5af4f5ce61cc6492a9f (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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "nearsearch.h"
#include <vespa/vespalib/objects/visit.h>
#include <vespa/vespalib/util/priority_queue.h>
#include <limits>
#include <set>

#include <vespa/log/log.h>
LOG_SETUP(".nearsearch");

namespace search::queryeval {

namespace {

using search::fef::TermFieldMatchDataArray;
using search::fef::TermFieldMatchDataPositionKey;

template<typename T>
void setup_fields(uint32_t window, std::vector<T> &matchers, const TermFieldMatchDataArray &in) {
    std::set<uint32_t> fields;
    for (size_t i = 0; i < in.size(); ++i) {
        fields.insert(in[i]->getFieldId());
    }
    for (const auto& elem : fields) {
        matchers.push_back(T(window, elem, in));
    }
}

} // namespace search::queryeval::<unnamed>

NearSearchBase::NearSearchBase(Children terms,
                               const TermFieldMatchDataArray &data,
                               uint32_t window,
                               bool strict)
    : AndSearch(std::move(terms)),
      _data_size(data.size()),
      _window(window),
      _strict(strict)
{
}

void
NearSearchBase::visitMembers(vespalib::ObjectVisitor &visitor) const
{
    AndSearch::visitMembers(visitor);
    visit(visitor, "data_size", _data_size);
    visit(visitor, "window", _window);
    visit(visitor, "strict", _strict);
}

void
NearSearchBase::seekNext(uint32_t docId)
{
    LOG(debug, "seekNext(%d)", docId);
    const Children & terms(getChildren());
    SearchIterator &firstTerm = *terms[0];
    uint32_t nextId = firstTerm.getDocId();
    while ( ! isAtEnd(nextId)) {
        LOG(debug, "Looking for match in document %d.", nextId);
        bool foundHit = true;
        for (uint32_t i = 1, len = terms.size(); i < len; ++i) {
            SearchIterator &term = *terms[i];
            if (!term.seek(nextId)) {
                LOG(debug, "Term %d does not occur in document %d.", i, nextId);
                foundHit = false;
                if (term.getDocId() > nextId) {
                    nextId = term.getDocId();
                    LOG(debug, "Next document in which term %d occurs is %d.", i, nextId);
                } else {
                    ++nextId;
                    LOG(debug, "Bumping target document to %d.", nextId);
                }
                break;
            }
            LOG(debug, "Term %d occurs in document %d.", i, nextId);
        }
        if (foundHit) {
            LOG(debug, "All terms occur in document %d, check for match.", nextId);
            if (match(nextId)) {
                LOG(debug, "Document %d matches.", nextId);
                break;
            }
            ++nextId;
        }
        if ( ! isAtEnd(nextId)) {
            LOG(debug, "Seeking next document that contains term 0, starting at %d.", nextId);
            firstTerm.seek(nextId);
            nextId = firstTerm.getDocId();
            LOG(debug, "Next document that contains term 0 is %d.", nextId);
        }
    }
    if (isAtEnd(nextId)) {
        LOG(debug, "Reached end of document list.");
        setAtEnd();
    } else {
        setDocId(nextId);
    }
}

void
NearSearchBase::doSeek(uint32_t docId)
{
    LOG(debug, "doSeek(%d)", docId);
    const Children & terms(getChildren());
    bool foundHit = true;
    for (uint32_t i = 0, len = terms.size(); i < len; ++i) {
        if (! terms[i]->seek(docId)) {
            LOG(debug, "Term %d does not occur in document %d.", i, docId);
            foundHit = false;
            break;
        }
    }
    if (foundHit && match(docId)) {
        LOG(debug, "Document %d matches.", docId);
        setDocId(docId);
    } else if (_strict) {
        LOG(debug, "Document %d does not match, seeking next.", docId);
        seekNext(docId);
    }
}

NearSearch::NearSearch(Children terms,
                       const TermFieldMatchDataArray &data,
                       uint32_t window,
                       bool strict)
    : NearSearchBase(std::move(terms), data, window, strict),
      _matchers()
{
    setup_fields(window, _matchers, data);
}

namespace {

struct PosIter {
    search::fef::TermFieldMatchData::PositionsIterator curPos;
    search::fef::TermFieldMatchData::PositionsIterator endPos;

    bool operator< (const PosIter &other) const {
        // assumes none is at end
        TermFieldMatchDataPositionKey mykey = *curPos;
        TermFieldMatchDataPositionKey otherkey = *other.curPos;
        return mykey < otherkey;
    }
};

struct Iterators
{
    vespalib::PriorityQueue<PosIter> _queue;
    TermFieldMatchDataPositionKey _maxOcc;

    void update(TermFieldMatchDataPositionKey occ)
    {
        if (_queue.size() == 1 || _maxOcc < occ) { _maxOcc = occ; }
    }

    void add(const search::fef::TermFieldMatchData *term)
    {
        PosIter iter;
        iter.curPos = term->begin();
        iter.endPos = term->end();
        LOG_ASSERT(iter.curPos != iter.endPos);
        _queue.push(iter);
        update(*iter.curPos);
    }

    bool match(uint32_t window) {
        for (;;) {
            PosIter &front = _queue.front();
            TermFieldMatchDataPositionKey lastAllowed = *front.curPos;
            lastAllowed.setPosition(front.curPos->getPosition() + window);

            if (!(lastAllowed < _maxOcc)) {
                return true;
            }
            do {
                ++front.curPos;
                if (front.curPos == front.endPos) {
                    return false;
                }
                lastAllowed = *front.curPos;
                lastAllowed.setPosition(front.curPos->getPosition() + window);
            } while (lastAllowed < _maxOcc);

            update(*front.curPos);
            _queue.adjust();
        }
    }
};

} // namespace <unnamed>

bool
NearSearch::Matcher::match(uint32_t docId)
{
    Iterators pos;
    for (uint32_t i = 0, len = inputs().size(); i < len; ++i) {
        const search::fef::TermFieldMatchData *term = inputs()[i];
        if (term->getDocId() != docId || term->begin() == term->end()) {
            LOG(debug, "No occurrences found for term %d.", i);
            return false;
        }
        LOG(debug, "Got positions iterator for term %d.", i);
        pos.add(term);
    }

    // Look for matching window.
    return pos.match(window());
}

bool
NearSearch::match(uint32_t docId)
{
    // Retrieve position iterators for each term.
    doUnpack(docId);
    for (size_t i = 0; i < _matchers.size(); ++i) {
        if (_matchers[i].match(docId)) {
            return true;
        }
    }
    return false;
}

ONearSearch::ONearSearch(Children terms,
                         const TermFieldMatchDataArray &data,
                         uint32_t window,
                         bool strict)
    : NearSearchBase(std::move(terms), data, window, strict),
      _matchers()
{
    setup_fields(window, _matchers, data);
}

bool
ONearSearch::Matcher::match(uint32_t docId)
{
    uint32_t numTerms = inputs().size();
    PositionsIteratorList pos;
    for (uint32_t i = 0; i < numTerms; ++i) {
        const search::fef::TermFieldMatchData *term = inputs()[i];
        if (term->getDocId() != docId || term->begin() == term->end()) {
            LOG(debug, "No occurrences found for term %d.", i);
            return false;
        }
        LOG(debug, "Got positions iterator for term %d.", i);
        pos.push_back(term->begin());
    }
    if (numTerms < 2) return true; // 1 term is always near itself

    int32_t remain = window();

    TermFieldMatchDataPositionKey prevTermPos;
    TermFieldMatchDataPositionKey curTermPos;
    TermFieldMatchDataPositionKey lastAllowed;

    // Look for match for every occurrence of the first term.
    for ( ; pos[0] != inputs()[0]->end(); ++pos[0]) {
        TermFieldMatchDataPositionKey firstTermPos = *pos[0];
        lastAllowed = firstTermPos;
        lastAllowed.setPosition(firstTermPos.getPosition() + remain);
        if (lastAllowed < curTermPos) {
            // if we already know that we must seek onwards:
            continue;
        }
        prevTermPos = firstTermPos;
        LOG(spam, "Looking for match in window [%d, %d].",
            firstTermPos.getPosition(), lastAllowed.getPosition());
        for (uint32_t i = 1; i < numTerms; ++i) {
            LOG(spam, "Forwarding iterator for term %d beyond %d.", i, prevTermPos.getPosition());
            while (pos[i] != inputs()[i]->end() && !(prevTermPos < *pos[i])) {
                ++pos[i];
            }
            if (pos[i] == inputs()[i]->end()) {
                LOG(debug, "Reached end of occurrences for term %d without matching ONEAR.", i);
                return false;
            }
            curTermPos = *pos[i];
            if (lastAllowed < curTermPos) {
                // outside window
                break;
            }
            LOG(spam, "Current position for term %d is %d.", i, curTermPos.getPosition());
            if (i + 1 == numTerms) {
                LOG(debug, "ONEAR match found for document %d.", docId);
                // OK for all terms
                return true;
            }
            prevTermPos = curTermPos;
        }
    }
    LOG(debug, "No ONEAR match found for document %d.", docId);
    return false;
}

bool
ONearSearch::match(uint32_t docId)
{
    // Retrieve position iterators for each term.
    doUnpack(docId);
    for (size_t i = 0; i < _matchers.size(); ++i) {
        if (_matchers[i].match(docId)) {
            return true;
        }
    }
    return false;
}

}