aboutsummaryrefslogtreecommitdiffstats
path: root/searchlib/src/vespa/searchlib/memoryindex/field_inverter.h
blob: 4e3934ba322c2aea07b45a230076ac90792f2f7d (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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include "i_field_index_remove_listener.h"
#include <vespa/document/annotation/span.h>
#include <vespa/searchlib/index/docidandfeatures.h>
#include <vespa/searchlib/util/token_extractor.h>
#include <vespa/vespalib/stllike/allocator.h>
#include <vespa/vespalib/stllike/hash_map.h>
#include <limits>

namespace search::index {
    class FieldLengthCalculator;
    class Schema;
}

namespace document {
    class Document;
    class FieldValue;
    class StringFieldValue;
    class ArrayFieldValue;
    class WeightedSetFieldValue;
}
namespace search::memoryindex {

class IOrderedFieldIndexInserter;
class FieldIndexRemover;

/**
 * Class used to invert a field for a set of documents, preparing for pushing changes into the corresponding FieldIndex.
 *
 * It creates a set of sorted {word, docId, features} tuples based on the field content of the documents,
 * and uses this when updating the posting lists of the FieldIndex.
 */
class FieldInverter : public IFieldIndexRemoveListener {
public:
    class PosInfo {
    public:
        uint32_t _wordNum;      // XXX: Initially word reference
        uint32_t _docId;
        uint32_t _elemId;
        uint32_t _wordPos;
        uint32_t _elemRef;  // Offset in _elems

        static constexpr uint32_t _elemRemoved = std::numeric_limits<uint32_t>::max();

        PosInfo() noexcept
            : _wordNum(0),
              _docId(0),
              _elemId(0),
              _wordPos(0),
              _elemRef(0)
        {
        }

        PosInfo(uint32_t wordRef,
                uint32_t docId,
                uint32_t elemId,
                uint32_t wordPos, uint32_t elemRef) noexcept
            : _wordNum(wordRef),
              _docId(docId),
              _elemId(elemId),
              _wordPos(wordPos),
              _elemRef(elemRef)
        {
        }

        PosInfo(uint32_t wordRef, uint32_t docId) noexcept
            : _wordNum(wordRef),
              _docId(docId),
              _elemId(_elemRemoved),
              _wordPos(0),
              _elemRef(0)
        {
        }

        bool removed() const { return _elemId == _elemRemoved; }

        bool operator<(const PosInfo &rhs) const {
            if (_wordNum != rhs._wordNum) {
                return _wordNum < rhs._wordNum;
            }
            if (_docId != rhs._docId) {
                return _docId < rhs._docId;
            }
            if (_elemId != rhs._elemId) {
                if (removed() != rhs.removed()) {
                    return removed() && !rhs.removed();
                }
                return _elemId < rhs._elemId;
            }
            return _wordPos < rhs._wordPos;
        }
    };

    // Max length of an indexed word. Longer words are dropped.
    static constexpr size_t max_word_len = 1_Mi;

private:
    using WordBuffer = std::vector<char, vespalib::allocator_large<char>>;

    class ElemInfo {
    public:
        const int32_t _weight;
        uint32_t _len;
        uint32_t _field_length;

        ElemInfo(int32_t weight)
            : _weight(weight),
              _len(0u),
              _field_length(0u)
        {
        }

        void setLen(uint32_t len) { _len = len; }
        uint32_t get_field_length() const { return _field_length; }
        void set_field_length(uint32_t field_length) { _field_length = field_length; }
    };

    using ElemInfoVec = std::vector<ElemInfo, vespalib::allocator_large<ElemInfo>>;
    using PosInfoVec = std::vector<PosInfo, vespalib::allocator_large<PosInfo>>;

    class CompareWordRef {
        const char *const _wordBuffer;

    public:
        CompareWordRef(const WordBuffer &wordBuffer)
            : _wordBuffer(&wordBuffer[0])
        {
        }

        const char *getWord(uint32_t wordRef) const {
            return &_wordBuffer[static_cast<size_t>(wordRef) << 2];
        }

        bool operator()(const uint32_t lhs, const uint32_t rhs) const {
            return strcmp(getWord(lhs), getWord(rhs)) < 0;
        }
    };

    /*
     * Range in _positions vector used to represent a document put.
     */
    class PositionRange {
        uint32_t _start;
        uint32_t _len;

    public:
        PositionRange(uint32_t start, uint32_t len)
            : _start(start),
              _len(len)
        {
        }

        bool operator<(const PositionRange &rhs) const {
            if (_start != rhs._start) {
                return _start < rhs._start;
            }
            return _len < rhs._len;
        }

        uint32_t getStart() const { return _start; }
        uint32_t getLen() const   { return _len; }
    };

    using UInt32Vector = std::vector<uint32_t, vespalib::allocator_large<uint32_t>>;
    // Current field state.
    const uint32_t                 _fieldId;   // current field id
    uint32_t                       _elem;      // current element
    uint32_t                       _wpos;      // current word pos
    uint32_t                       _docId;
    uint32_t                       _oldPosSize;

    const index::Schema           &_schema;
    linguistics::TokenExtractor    _token_extractor;

    WordBuffer                     _words;
    ElemInfoVec                    _elems;
    PosInfoVec                     _positions;
    index::DocIdAndPosOccFeatures  _features;
    UInt32Vector                   _wordRefs;

    using SpanTerm = linguistics::TokenExtractor::SpanTerm;
    std::vector<SpanTerm>          _terms;

    // Info about aborted and pending documents.
    std::vector<PositionRange>                  _abortedDocs;
    vespalib::hash_map<uint32_t, PositionRange> _pendingDocs;
    UInt32Vector                                _removeDocs;

    FieldIndexRemover                &_remover;
    IOrderedFieldIndexInserter       &_inserter;
    index::FieldLengthCalculator     &_calculator;

    void invertNormalDocTextField(const document::FieldValue &val, const document::Document& doc);

public:
    void startElement(int32_t weight);
    void endElement();

private:
    /**
     * Save the given word in the word buffer and return the word reference.
     */
    VESPA_DLL_LOCAL uint32_t saveWord(vespalib::stringref word);

    /**
     * Get pointer to saved word from a word reference.
     */
    const char *getWordFromRef(uint32_t wordRef) const {
        return &_words[static_cast<size_t>(wordRef) << 2];
    }

    /**
     * Get pointer to saved word from a word number.
     */
    const char *getWordFromNum(uint32_t wordNum) const {
        return getWordFromRef(_wordRefs[wordNum]);
    }

    /**
     * Get word number from word reference.
     */
    uint32_t getWordNum(uint32_t wordRef) const {
        const char *p = &_words[static_cast<size_t>(wordRef - 1) << 2];
        return *reinterpret_cast<const uint32_t *>(p);
    }

    /**
     * Update mapping from word reference to word number.
     */
    void updateWordNum(uint32_t wordRef, uint32_t wordNum) {
        char *p = &_words[static_cast<size_t>(wordRef - 1) << 2];
        *reinterpret_cast<uint32_t *>(p) = wordNum;
    }

    /**
     * Add a word reference to posting list (but don't step word pos).
     */
    void add(uint32_t wordRef) {
        _positions.emplace_back(wordRef, _docId, _elem, _wpos, _elems.size() - 1);
    }

    void stepWordPos() { ++_wpos; }

public:
    VESPA_DLL_LOCAL void
    processAnnotations(const document::StringFieldValue &value, const document::Document& doc);

    void push_documents_internal();

private:
    void processNormalDocTextField(const document::StringFieldValue &field, const document::Document& doc);
    void processNormalDocArrayTextField(const document::ArrayFieldValue &field, const document::Document& doc);
    void processNormalDocWeightedSetTextField(const document::WeightedSetFieldValue &field, const document::Document& doc);

    const index::Schema &getSchema() const { return _schema; }

    /**
     * Clear internal memory structures.
     */
    void reset();

    /**
     * Calculate word numbers and replace word references with word numbers in internal memory structures.
     */
    void sortWords();

    void moveNotAbortedDocs(uint32_t &dstIdx, uint32_t srcIdx, uint32_t nextTrimIdx);

    void trimAbortedDocs();

    /**
     * Abort a pending document that has already been inverted.
     */
    void abortPendingDoc(uint32_t docId);

public:
    /**
     * Create a new field inverter for the given fieldId, using the given schema.
     */
    FieldInverter(const index::Schema &schema, uint32_t fieldId,
                  FieldIndexRemover &remover,
                  IOrderedFieldIndexInserter &inserter,
                  index::FieldLengthCalculator &calculator);
    FieldInverter(const FieldInverter &) = delete;
    FieldInverter(const FieldInverter &&) = delete;
    FieldInverter &operator=(const FieldInverter &) = delete;
    FieldInverter &operator=(const FieldInverter &&) = delete;
    ~FieldInverter() override;

    /**
     * Apply pending removes using the given remover.
     *
     * The remover is tracking all {word, docId} tuples that should removed,
     * and forwards this to the remove() function in this class (via IFieldIndexRemoveListener interface).
     */
    void applyRemoves();

    /**
     * Push the current batch of inverted documents to the FieldIndex using the given inserter.
     */
    void pushDocuments();

    /**
     * Invert a normal text field, based on annotations.
     */
    void invertField(uint32_t docId, const std::unique_ptr<document::FieldValue> &val, const document::Document& doc);

    /**
     * Setup remove of word in old version of document.
     */
    void remove(const vespalib::stringref word, uint32_t docId) override;

    void removeDocument(uint32_t docId) {
        abortPendingDoc(docId);
        _removeDocs.push_back(docId);
    }

    void startDoc(uint32_t docId);

    void endDoc();

    void addWord(vespalib::stringref word, const document::Document& doc);
};

}