Coverage Report

Created: 2026-11-04 10:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/exprs/vsearch.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "exprs/vsearch.h"
19
20
#include <fmt/format.h>
21
22
#include <memory>
23
#include <roaring/roaring.hh>
24
25
#include "common/logging.h"
26
#include "common/status.h"
27
#include "core/column/column_const.h"
28
#include "exprs/function/function_search.h"
29
#include "exprs/vexpr_context.h"
30
#include "exprs/vliteral.h"
31
#include "exprs/vslot_ref.h"
32
#include "glog/logging.h"
33
#include "runtime/runtime_state.h"
34
#include "storage/index/inverted/inverted_index_reader.h"
35
#include "storage/schema.h"
36
#include "storage/segment/segment.h"
37
#include "storage/segment/variant/variant_column_reader.h"
38
39
namespace doris {
40
using namespace segment_v2;
41
42
namespace {
43
44
struct SearchInputBundle {
45
    std::unordered_map<std::string, IndexIterator*> iterators;
46
    std::unordered_map<std::string, IndexFieldNameAndTypePair> field_types;
47
    std::unordered_map<std::string, int> field_name_to_column_id;
48
    std::vector<int> column_indexes;
49
    ColumnsWithTypeAndName literal_args;
50
};
51
52
void add_search_binding_diagnostic(const IndexExecContext* index_context,
53
401
                                   const std::string& diagnostic) {
54
18.4E
    VLOG_DEBUG << diagnostic;
55
401
    if (index_context == nullptr) {
56
0
        return;
57
0
    }
58
401
    const auto& index_query_context = index_context->get_index_query_context();
59
401
    if (index_query_context != nullptr && index_query_context->stats != nullptr) {
60
396
        index_query_context->stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
61
396
    }
62
401
}
63
64
// A missing iterator is not evidence of a missing value: doc/sparse paths and
65
// old rowsets may contain values without an executable SEARCH index.
66
Status verify_missing_variant_path(const TSearchFieldBinding& binding, int column_index,
67
260
                                   IndexExecContext* index_context) {
68
260
    auto* segment = index_context->segment();
69
260
    if (segment == nullptr || !binding.__isset.parent_field_name ||
70
260
        !binding.__isset.subcolumn_path) {
71
1
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
72
1
                "SEARCH cannot establish missing path '{}'", binding.field_name);
73
1
    }
74
259
    const auto& read_schema = index_context->read_schema();
75
259
    DORIS_CHECK_GE(column_index, 0);
76
259
    DORIS_CHECK_LT(static_cast<size_t>(column_index), read_schema->num_column_ids());
77
259
    const auto& column = *read_schema->column(read_schema->column_id(column_index));
78
259
    const auto& opts = index_context->column_iter_opts();
79
259
    DORIS_CHECK(opts.stats != nullptr);
80
259
    const int32_t root_uid =
81
259
            column.parent_unique_id() >= 0 ? column.parent_unique_id() : column.unique_id();
82
259
    if (!segment->tablet_schema()->has_column_unique_id(root_uid)) {
83
4
        return Status::OK();
84
4
    }
85
255
    std::shared_ptr<ColumnReader> column_reader;
86
255
    Status st = segment->get_column_reader(root_uid, &column_reader, opts.stats, &opts.io_ctx);
87
255
    if (st.is<ErrorCode::NOT_FOUND>()) {
88
        // After DROP v(uid=1), ADD v(uid=2), an old segment cannot contain this scan's root.
89
        // Resolve by the current uid so historical values of the same name cannot match.
90
0
        return Status::OK();
91
0
    }
92
255
    RETURN_IF_ERROR(st);
93
255
    auto* reader = dynamic_cast<VariantColumnReader*>(column_reader.get());
94
255
    DORIS_CHECK(reader != nullptr);
95
255
    RETURN_IF_ERROR(reader->load_external_meta_once(opts.stats, &opts.io_ctx));
96
255
    const PathInData path(binding.subcolumn_path);
97
255
    const auto* stats = reader->get_stats();
98
    // Doc statistics enumerate stored paths without the sparse statistics limit. For example,
99
    // a segment containing only `string4` can prove `string5` absent even in doc mode.
100
    // An opaque root/ancestor value may contain the requested path, so it remains unavailable.
101
255
    bool in_doc = stats->existed_in_doc_value_column("") ||
102
256
                  stats->has_prefix_path_in_doc_value_column(path.get_path() + ".");
103
255
    std::string ancestor = path.get_path();
104
259
    while (!in_doc) {
105
259
        in_doc = stats->existed_in_doc_value_column(ancestor);
106
259
        const auto dot = ancestor.rfind('.');
107
259
        if (dot == std::string::npos) {
108
256
            break;
109
256
        }
110
3
        ancestor.resize(dot);
111
3
    }
112
    // Truncated sparse statistics cannot prove absence, nor can an existing unindexed path.
113
255
    if (reader->get_subcolumn_meta_by_path(path) != nullptr ||
114
255
        reader->has_prefix_path(path, opts.stats, &opts.io_ctx) ||
115
255
        reader->exist_in_sparse_column(path) || reader->is_exceeded_sparse_column_limit() ||
116
255
        in_doc || stats->has_nested_group) {
117
98
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
118
98
                "SEARCH index unavailable for Variant field '{}'", binding.field_name);
119
98
    }
120
157
    return Status::OK();
121
255
}
122
123
Status collect_slot_search_input(const VSearchExpr& expr, const VSlotRef& slot_ref,
124
                                 const TSearchFieldBinding* binding,
125
2.93k
                                 IndexExecContext* index_context, SearchInputBundle* bundle) {
126
2.93k
    DCHECK(index_context != nullptr);
127
2.93k
    DCHECK(bundle != nullptr);
128
129
    // VSlotRef::column_id() is the scan-schema position used by IndexExecContext.
130
2.93k
    const int column_index = slot_ref.column_id();
131
2.93k
    const std::string field_name =
132
2.93k
            binding != nullptr ? binding->field_name : slot_ref.column_name();
133
2.97k
    const bool is_variant_subcolumn = binding != nullptr && binding->__isset.is_variant_subcolumn &&
134
2.97k
                                      binding->is_variant_subcolumn;
135
136
2.93k
    bundle->field_name_to_column_id[field_name] = column_index;
137
138
2.93k
    auto* iterator = index_context->get_inverted_index_iterator_by_column_id(column_index);
139
2.93k
    if (iterator == nullptr) {
140
        // For example, `data.items.message` has its own SlotRef in the scan schema. The
141
        // storage layer may inherit index metadata from `data`, but it still constructs a
142
        // child iterator whose stored field name contains the complete Variant path.
143
262
        if (is_variant_subcolumn) {
144
261
            add_search_binding_diagnostic(
145
261
                    index_context,
146
261
                    fmt::format("[VariantSearchBinding] phase=collect_inputs "
147
261
                                "result=no_iterator logical_field={} column_index={} "
148
261
                                "reason=slot_iterator_missing",
149
261
                                field_name, column_index));
150
261
        }
151
262
        if (!is_variant_subcolumn) {
152
1
            return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
153
1
                    "SEARCH index unavailable for field '{}'", field_name);
154
1
        }
155
261
        RETURN_IF_ERROR(verify_missing_variant_path(*binding, column_index, index_context));
156
162
        return Status::OK();
157
261
    }
158
159
2.67k
    const auto* storage_name_type =
160
2.67k
            index_context->get_storage_name_and_type_by_column_id(column_index);
161
2.67k
    if (storage_name_type == nullptr) {
162
1
        return Status::InternalError("storage_name_type not found for column {} in {}",
163
1
                                     column_index, expr.expr_name());
164
1
    }
165
166
2.67k
    bundle->iterators.emplace(field_name, iterator);
167
2.67k
    bundle->field_types.emplace(field_name, *storage_name_type);
168
2.67k
    bundle->column_indexes.emplace_back(column_index);
169
2.67k
    if (is_variant_subcolumn) {
170
142
        add_search_binding_diagnostic(
171
142
                index_context,
172
142
                fmt::format("[VariantSearchBinding] phase=collect_inputs "
173
142
                            "result=direct_iterator logical_field={} column_index={} "
174
142
                            "stored_field={}",
175
142
                            field_name, column_index, storage_name_type->first));
176
142
    }
177
2.67k
    return Status::OK();
178
2.67k
}
179
180
0
const VSlotRef& variant_root_slot(const VExpr& expr) {
181
0
    const VExpr* root = &expr;
182
0
    while (root->fn().name.function_name == "element_at") {
183
0
        DORIS_CHECK(!root->children().empty());
184
0
        root = root->children().front().get();
185
0
    }
186
0
    DORIS_CHECK(root->is_slot_ref());
187
0
    return *assert_cast<const VSlotRef*>(root);
188
0
}
189
190
Status collect_search_inputs(const VSearchExpr& expr, VExprContext* context,
191
2.13k
                             SearchInputBundle* bundle) {
192
2.13k
    DCHECK(bundle != nullptr);
193
194
2.13k
    auto index_context = context->get_index_context();
195
2.13k
    if (index_context == nullptr) {
196
0
        LOG(WARNING) << "collect_search_inputs: No inverted index context available";
197
0
        return Status::InternalError("No inverted index context available");
198
0
    }
199
200
2.13k
    const auto& search_param = expr.get_search_param();
201
2.13k
    const auto& field_bindings = search_param.field_bindings;
202
203
2.13k
    size_t child_index = 0;
204
2.94k
    for (const auto& child : expr.children()) {
205
2.94k
        if (child->is_slot_ref()) {
206
2.93k
            auto* column_slot_ref = assert_cast<VSlotRef*>(child.get());
207
2.93k
            const TSearchFieldBinding* binding =
208
2.93k
                    child_index < field_bindings.size() ? &field_bindings[child_index] : nullptr;
209
2.93k
            RETURN_IF_ERROR(collect_slot_search_input(expr, *column_slot_ref, binding,
210
2.93k
                                                      index_context.get(), bundle));
211
2.83k
            ++child_index;
212
2.83k
        } else if (child->is_literal()) {
213
0
            auto* literal = assert_cast<VLiteral*>(child.get());
214
0
            bundle->literal_args.emplace_back(literal->get_column_ptr(), literal->get_data_type(),
215
0
                                              literal->expr_name());
216
10
        } else {
217
            // Check if this is ElementAt expression (for variant subcolumn access)
218
10
            if (child->expr_name() == "element_at" && child_index < field_bindings.size() &&
219
10
                field_bindings[child_index].__isset.is_variant_subcolumn &&
220
10
                field_bindings[child_index].is_variant_subcolumn) {
221
                // Variant subcolumn not materialized - skip, will create empty BitSetQuery in function_search
222
0
                add_search_binding_diagnostic(
223
0
                        index_context.get(),
224
0
                        fmt::format("[VariantSearchBinding] phase=collect_inputs "
225
0
                                    "result=unmaterialized_element_at logical_field={} "
226
0
                                    "parent_field={} sub_path={} reason=no_slot_ref",
227
0
                                    field_bindings[child_index].field_name,
228
0
                                    field_bindings[child_index].__isset.parent_field_name
229
0
                                            ? field_bindings[child_index].parent_field_name
230
0
                                            : "",
231
0
                                    field_bindings[child_index].__isset.subcolumn_path
232
0
                                            ? field_bindings[child_index].subcolumn_path
233
0
                                            : ""));
234
0
                RETURN_IF_ERROR(verify_missing_variant_path(field_bindings[child_index],
235
0
                                                            variant_root_slot(*child).column_id(),
236
0
                                                            index_context.get()));
237
0
                ++child_index;
238
0
                continue;
239
0
            }
240
241
            // Not a supported child type
242
10
            return Status::InvalidArgument("Unsupported child node type: {}", child->expr_name());
243
10
        }
244
2.94k
    }
245
246
2.02k
    return Status::OK();
247
2.13k
}
248
249
} // namespace
250
251
1.26k
VSearchExpr::VSearchExpr(const TExprNode& node) : VExpr(node) {
252
1.26k
    if (node.__isset.search_param) {
253
1.26k
        _search_param = node.search_param;
254
1.26k
        _original_dsl = _search_param.original_dsl;
255
1.26k
    }
256
1.26k
}
257
258
Status VSearchExpr::prepare(RuntimeState* state, const RowDescriptor& row_desc,
259
1.17k
                            VExprContext* context) {
260
1.17k
    RETURN_IF_ERROR(VExpr::prepare(state, row_desc, context));
261
1.17k
    const auto& query_options = state->query_options();
262
1.17k
    if (query_options.__isset.enable_inverted_index_query_cache) {
263
1.17k
        _enable_cache = query_options.enable_inverted_index_query_cache;
264
1.17k
    }
265
1.17k
    return Status::OK();
266
1.17k
}
267
268
395
const std::string& VSearchExpr::expr_name() const {
269
395
    static const std::string name = "VSearchExpr";
270
395
    return name;
271
395
}
272
273
Status VSearchExpr::execute_column(VExprContext* context, const Block* block, Selector* selector,
274
10
                                   size_t count, ColumnPtr& result_column) const {
275
10
    if (fast_execute(context, selector, count, result_column)) {
276
8
        return Status::OK();
277
8
    }
278
279
2
    return Status::InternalError("SearchExpr should not be executed without inverted index");
280
10
}
281
282
2.18k
Status VSearchExpr::evaluate_inverted_index(VExprContext* context, uint32_t segment_num_rows) {
283
2.18k
    if (_search_param.original_dsl.empty()) {
284
3
        return Status::InvalidArgument("search DSL is empty");
285
3
    }
286
287
2.18k
    auto index_context = context->get_index_context();
288
2.18k
    if (!index_context) {
289
15
        LOG(WARNING) << "VSearchExpr: No inverted index context available";
290
15
        return Status::OK();
291
15
    }
292
293
2.16k
    SearchInputBundle bundle;
294
2.16k
    RETURN_IF_ERROR(collect_search_inputs(*this, context, &bundle));
295
296
18.4E
    VLOG_DEBUG << "VSearchExpr: bundle.iterators.size()=" << bundle.iterators.size();
297
298
2.06k
    auto index_query_context = index_context->get_index_query_context();
299
300
2.06k
    auto function = std::make_shared<FunctionSearch>();
301
2.06k
    auto result_bitmap = InvertedIndexResultBitmap();
302
2.06k
    auto status = function->evaluate_inverted_index_with_search_param(
303
2.06k
            _search_param, bundle.field_types, bundle.iterators, segment_num_rows, result_bitmap,
304
2.06k
            _enable_cache, index_context.get(), bundle.field_name_to_column_id,
305
2.06k
            index_query_context);
306
307
2.06k
    if (!status.ok()) {
308
2
        LOG(WARNING) << "VSearchExpr: Function evaluation failed: " << status.to_string();
309
2
        return status;
310
2
    }
311
312
2.06k
    index_context->set_index_result_for_expr(this, result_bitmap);
313
2.69k
    for (int column_index : bundle.column_indexes) {
314
2.69k
        index_context->set_true_for_index_status(this, column_index);
315
2.69k
    }
316
317
2.06k
    return Status::OK();
318
2.06k
}
319
320
} // namespace doris