summaryrefslogtreecommitdiffstats
path: root/searchlib/src/vespa/searchlib/attribute/multivalueattribute.hpp
blob: e009a3b69f68f5020c3c93a173f6ede6697d8b66 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include "address_space_components.h"
#include <vespa/searchlib/attribute/multivalueattribute.h>
#include <vespa/vespalib/stllike/hash_map.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <vespa/vespalib/util/memory_allocator.h>

namespace search {

namespace multivalueattribute {

constexpr size_t SMALL_MEMORY_PAGE_SIZE = 4 * 1024;
constexpr bool enable_free_lists = true;

}

template <typename B, typename M>
MultiValueAttribute<B, M>::
MultiValueAttribute(const vespalib::string &baseFileName,
                    const AttributeVector::Config &cfg)
    : B(baseFileName, cfg),
      _mvMapping(MultiValueMapping::optimizedConfigForHugePage(1023,
                                                               vespalib::alloc::MemoryAllocator::HUGEPAGE_SIZE,
                                                               multivalueattribute::SMALL_MEMORY_PAGE_SIZE,
                                                               8 * 1024,
                                                               cfg.getGrowStrategy().getMultiValueAllocGrowFactor(),
                                                               multivalueattribute::enable_free_lists),
                 cfg.getGrowStrategy().to_generic_strategy(), this->get_memory_allocator())
{
}

template <typename B, typename M>
MultiValueAttribute<B, M>::~MultiValueAttribute() = default;

template <typename B, typename M>
int32_t MultiValueAttribute<B, M>::getWeight(DocId doc, uint32_t idx) const
{
    MultiValueArrayRef values(this->_mvMapping.get(doc));
    return ((idx < values.size()) ? values[idx].weight() : 1);
}

namespace {

template <typename T>
struct HashFn {
    using type = vespalib::hash<T>;
};

template <>
struct HashFn<vespalib::datastore::EntryRef> {
    struct EntryRefHasher {
        size_t operator() (const vespalib::datastore::EntryRef& v) const noexcept {
            return v.ref();
        }
    };
    using type = EntryRefHasher;
};

}

template <typename B, typename M>
void
MultiValueAttribute<B, M>::applyAttributeChanges(DocumentValues & docValues)
{
    if (this->hasArrayType()) {
        apply_attribute_changes_to_array(docValues);
        return;
    } else if (this->hasWeightedSetType()) {
        apply_attribute_changes_to_wset(docValues);
        return;
    }
}

template <typename B, typename M>
void
MultiValueAttribute<B, M>::apply_attribute_changes_to_array(DocumentValues& docValues)
{
    // compute new values for each document with changes
    auto iterable = this->_changes.getDocIdInsertOrder();
    for (auto current(iterable.begin()), end(iterable.end()); (current != end); ) {
        DocId doc = current->_doc;
        // find last clear doc
        auto last_clear_doc = end;
        for (auto iter = current; (iter != end) && (iter->_doc == doc); ++iter) {
            if (iter->_type == ChangeBase::CLEARDOC) {
                last_clear_doc = iter;
            }
        }
        // use last clear doc if found
        if (last_clear_doc != end) {
            current = last_clear_doc;
        }
        MultiValueArrayRef old_values(_mvMapping.get(doc));
        ValueVector new_values(old_values.cbegin(), old_values.cend());
        vespalib::hash_map<NonAtomicValueType, size_t, typename HashFn<NonAtomicValueType>::type> tombstones;

        // iterate through all changes for this document
        for (; (current != end) && (current->_doc == doc); ++current) {
            if (current->_type == ChangeBase::CLEARDOC) {
                new_values.clear();
                tombstones.clear();
                continue;
            }
            NonAtomicValueType data;
            bool hasData = extractChangeData(*current, data);
            if (!hasData) {
                continue;
            }
            if (current->_type == ChangeBase::APPEND) {
                if constexpr (std::is_same_v<ValueType, NonAtomicValueType>) {
                    new_values.emplace_back(data, current->_weight);
                } else {
                    new_values.emplace_back(ValueType(data), current->_weight);
                }
            } else if (current->_type == ChangeBase::REMOVE) {
                // Defer all removals to the very end by tracking when, during value vector build time,
                // a removal was encountered for a particular value. All values < this index will be ignored.
                tombstones[data] = new_values.size();
            }
        }
        // Optimize for the case where nothing was explicitly removed.
        if (!tombstones.empty()) {
            ValueVector culled;
            culled.reserve(new_values.size());
            if constexpr (std::is_same_v<ValueType, NonAtomicValueType>) {
                for (size_t i = 0; i < new_values.size(); ++i) {
                    auto iter = tombstones.find(new_values[i].value());
                    if (iter == tombstones.end() || (iter->second <= i)) {
                        culled.emplace_back(new_values[i]);
                    }
                }
            } else {
                for (size_t i = 0; i < new_values.size(); ++i) {
                    auto iter = tombstones.find(new_values[i].value_ref().load_relaxed());
                    if (iter == tombstones.end() || (iter->second <= i)) {
                        culled.emplace_back(new_values[i]);
                    }
                }
            }
            culled.swap(new_values);
        }
        this->checkSetMaxValueCount(new_values.size());
        docValues.emplace_back(doc, std::move(new_values));
    }
}

template <typename B, typename M>
void
MultiValueAttribute<B, M>::apply_attribute_changes_to_wset(DocumentValues& docValues)
{
    // compute new values for each document with changes
    auto iterable = this->_changes.getDocIdInsertOrder();
    for (auto current(iterable.begin()), end(iterable.end()); (current != end); ) {
        const DocId doc = current->_doc;
        // find last clear doc
        auto last_clear_doc = end;
        size_t max_elems_inserted = 0;
        for (auto iter = current; (iter != end) && (iter->_doc == doc); ++iter) {
            if (iter->_type == ChangeBase::CLEARDOC) {
                last_clear_doc = iter;
            }
            ++max_elems_inserted;
        }
        // use last clear doc if found
        if (last_clear_doc != end) {
            current = last_clear_doc;
        }
        MultiValueArrayRef old_values(_mvMapping.get(doc));
        vespalib::hash_map<NonAtomicValueType, int32_t, typename HashFn<NonAtomicValueType>::type> wset_inserted;
        wset_inserted.resize((old_values.size() + max_elems_inserted) * 2);
        for (const auto& e : old_values) {
            if constexpr (std::is_same_v<ValueType, NonAtomicValueType>) {
                wset_inserted[e.value()] = e.weight();
            } else {
                wset_inserted[e.value_ref().load_relaxed()] = e.weight();
            }
        }
        // iterate through all changes for this document
        for (; (current != end) && (current->_doc == doc); ++current) {
            if (current->_type == ChangeBase::CLEARDOC) {
                wset_inserted.clear();
                continue;
            }
            NonAtomicValueType data;
            bool hasData = extractChangeData(*current, data);
            if (!hasData) {
                continue;
            }
            if (current->_type == ChangeBase::APPEND) {
                wset_inserted[data] = current->_weight;
            } else if (current->_type == ChangeBase::REMOVE) {
                wset_inserted.erase(data);
            } else if ((current->_type >= ChangeBase::INCREASEWEIGHT) && (current->_type <= ChangeBase::SETWEIGHT)) {
                auto existing = wset_inserted.find(data);
                if (existing != wset_inserted.end()) {
                    existing->second = this->applyWeightChange(existing->second, *current);
                    if ((existing->second == 0) && this->getInternalCollectionType().removeIfZero()) {
                        wset_inserted.erase(existing);
                    }
                } else if (this->getInternalCollectionType().createIfNonExistant()) {
                    int32_t weight = this->applyWeightChange(0, *current);
                    if (weight != 0 || !this->getInternalCollectionType().removeIfZero()) {
                        wset_inserted.insert(std::make_pair(data, weight));
                    }
                }
            }
        }
        std::vector<MultiValueType> new_values;
        new_values.reserve(wset_inserted.size());
        if constexpr (std::is_same_v<ValueType, NonAtomicValueType>) {
            wset_inserted.for_each([&new_values](const auto& e){ new_values.emplace_back(e.first, e.second); });
        } else {
            wset_inserted.for_each([&new_values](const auto& e){ new_values.emplace_back(ValueType(e.first), e.second); });
        }

        this->checkSetMaxValueCount(new_values.size());
        docValues.emplace_back(doc, std::move(new_values));
    }
}

template <typename B, typename M>
void
MultiValueAttribute<B, M>::populate_address_space_usage(AddressSpaceUsage& usage) const
{
    B::populate_address_space_usage(usage);
    usage.set(AddressSpaceComponents::multi_value, _mvMapping.getAddressSpaceUsage());
}

template <typename B, typename M>
bool
MultiValueAttribute<B, M>::addDoc(DocId & doc)
{
    bool incGen = this->_mvMapping.isFull();
    this->_mvMapping.addDoc(doc);
    this->incNumDocs();
    this->updateUncommittedDocIdLimit(doc);
    incGen |= onAddDoc(doc);
    if (incGen) {
        this->incGeneration();
    } else
        this->removeAllOldGenerations();
    return true;
}

template <typename B, typename M>
void
MultiValueAttribute<B, M>::onAddDocs(DocId  lidLimit) {
    this->_mvMapping.reserve(lidLimit);
}


template <typename B, typename M>
uint32_t
MultiValueAttribute<B, M>::getValueCount(DocId doc) const
{
    if (doc >= this->getNumDocs()) {
        return 0;
    }
    MultiValueArrayRef values(this->_mvMapping.get(doc));
    return values.size();
}


template <typename B, typename M>
uint64_t
MultiValueAttribute<B, M>::getTotalValueCount() const
{
    return _mvMapping.getTotalValueCnt();
}


template <typename B, typename M>
void
MultiValueAttribute<B, M>::clearDocs(DocId lidLow, DocId lidLimit)
{
    _mvMapping.clearDocs(lidLow, lidLimit, [this](uint32_t docId) { this->clearDoc(docId); });
}


template <typename B, typename M>
void
MultiValueAttribute<B, M>::onShrinkLidSpace()
{
    uint32_t committedDocIdLimit = this->getCommittedDocIdLimit();
    _mvMapping.shrink(committedDocIdLimit);
    this->setNumDocs(committedDocIdLimit);
}


} // namespace search