Coverage Report

Created: 2026-10-26 16:28

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
5
                                   const std::string& diagnostic) {
54
5
    VLOG_DEBUG << diagnostic;
55
5
    if (index_context == nullptr) {
56
0
        return;
57
0
    }
58
5
    const auto& index_query_context = index_context->get_index_query_context();
59
5
    if (index_query_context != nullptr && index_query_context->stats != nullptr) {
60
0
        index_query_context->stats->inverted_index_stats.add_binding_diagnostic(diagnostic);
61
0
    }
62
5
}
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
5
                                   IndexExecContext* index_context) {
68
5
    auto* segment = index_context->segment();
69
5
    if (segment == nullptr || !binding.__isset.parent_field_name ||
70
5
        !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
4
    const auto& read_schema = index_context->read_schema();
75
4
    DORIS_CHECK_GE(column_index, 0);
76
4
    DORIS_CHECK_LT(static_cast<size_t>(column_index), read_schema->num_column_ids());
77
4
    const auto& column = *read_schema->column(read_schema->column_id(column_index));
78
4
    const auto& opts = index_context->column_iter_opts();
79
4
    DORIS_CHECK(opts.stats != nullptr);
80
4
    const int32_t root_uid =
81
4
            column.parent_unique_id() >= 0 ? column.parent_unique_id() : column.unique_id();
82
4
    if (!segment->tablet_schema()->has_column_unique_id(root_uid)) {
83
4
        return Status::OK();
84
4
    }
85
0
    std::shared_ptr<ColumnReader> column_reader;
86
0
    Status st = segment->get_column_reader(root_uid, &column_reader, opts.stats, &opts.io_ctx);
87
0
    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
0
    RETURN_IF_ERROR(st);
93
0
    auto* reader = dynamic_cast<VariantColumnReader*>(column_reader.get());
94
0
    DORIS_CHECK(reader != nullptr);
95
0
    RETURN_IF_ERROR(reader->load_external_meta_once(opts.stats, &opts.io_ctx));
96
0
    const PathInData path(binding.subcolumn_path);
97
0
    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
0
    bool in_doc = stats->existed_in_doc_value_column("") ||
102
0
                  stats->has_prefix_path_in_doc_value_column(path.get_path() + ".");
103
0
    std::string ancestor = path.get_path();
104
0
    while (!in_doc) {
105
0
        in_doc = stats->existed_in_doc_value_column(ancestor);
106
0
        const auto dot = ancestor.rfind('.');
107
0
        if (dot == std::string::npos) {
108
0
            break;
109
0
        }
110
0
        ancestor.resize(dot);
111
0
    }
112
    // Truncated sparse statistics cannot prove absence, nor can an existing unindexed path.
113
0
    if (reader->get_subcolumn_meta_by_path(path) != nullptr ||
114
0
        reader->has_prefix_path(path, opts.stats, &opts.io_ctx) ||
115
0
        reader->exist_in_sparse_column(path) || reader->is_exceeded_sparse_column_limit() ||
116
0
        in_doc || stats->has_nested_group) {
117
0
        return Status::Error<ErrorCode::INVERTED_INDEX_NOT_SUPPORTED>(
118
0
                "SEARCH index unavailable for Variant field '{}'", binding.field_name);
119
0
    }
120
0
    return Status::OK();
121
0
}
122
123
Status collect_slot_search_input(const VSearchExpr& expr, const VSlotRef& slot_ref,
124
                                 const TSearchFieldBinding* binding,
125
8
                                 IndexExecContext* index_context, SearchInputBundle* bundle) {
126
8
    DCHECK(index_context != nullptr);
127
8
    DCHECK(bundle != nullptr);
128
129
    // VSlotRef::column_id() is the scan-schema position used by IndexExecContext.
130
8
    const int column_index = slot_ref.column_id();
131
8
    const std::string field_name =
132
8
            binding != nullptr ? binding->field_name : slot_ref.column_name();
133
8
    const bool is_variant_subcolumn = binding != nullptr && binding->__isset.is_variant_subcolumn &&
134
8
                                      binding->is_variant_subcolumn;
135
136
8
    bundle->field_name_to_column_id[field_name] = column_index;
137
138
8
    auto* iterator = index_context->get_inverted_index_iterator_by_column_id(column_index);
139
8
    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
6
        if (is_variant_subcolumn) {
144
5
            add_search_binding_diagnostic(
145
5
                    index_context,
146
5
                    fmt::format("[VariantSearchBinding] phase=collect_inputs "
147
5
                                "result=no_iterator logical_field={} column_index={} "
148
5
                                "reason=slot_iterator_missing",
149
5
                                field_name, column_index));
150
5
        }
151
6
        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
5
        RETURN_IF_ERROR(verify_missing_variant_path(*binding, column_index, index_context));
156
4
        return Status::OK();
157
5
    }
158
159
2
    const auto* storage_name_type =
160
2
            index_context->get_storage_name_and_type_by_column_id(column_index);
161
2
    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
1
    bundle->iterators.emplace(field_name, iterator);
167
1
    bundle->field_types.emplace(field_name, *storage_name_type);
168
1
    bundle->column_indexes.emplace_back(column_index);
169
1
    if (is_variant_subcolumn) {
170
0
        add_search_binding_diagnostic(
171
0
                index_context,
172
0
                fmt::format("[VariantSearchBinding] phase=collect_inputs "
173
0
                            "result=direct_iterator logical_field={} column_index={} "
174
0
                            "stored_field={}",
175
0
                            field_name, column_index, storage_name_type->first));
176
0
    }
177
1
    return Status::OK();
178
2
}
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
10
                             SearchInputBundle* bundle) {
192
10
    DCHECK(bundle != nullptr);
193
194
10
    auto index_context = context->get_index_context();
195
10
    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
10
    const auto& search_param = expr.get_search_param();
201
10
    const auto& field_bindings = search_param.field_bindings;
202
203
10
    size_t child_index = 0;
204
10
    for (const auto& child : expr.children()) {
205
9
        if (child->is_slot_ref()) {
206
8
            auto* column_slot_ref = assert_cast<VSlotRef*>(child.get());
207
8
            const TSearchFieldBinding* binding =
208
8
                    child_index < field_bindings.size() ? &field_bindings[child_index] : nullptr;
209
8
            RETURN_IF_ERROR(collect_slot_search_input(expr, *column_slot_ref, binding,
210
8
                                                      index_context.get(), bundle));
211
5
            ++child_index;
212
5
        } 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
1
        } else {
217
            // Check if this is ElementAt expression (for variant subcolumn access)
218
1
            if (child->expr_name() == "element_at" && child_index < field_bindings.size() &&
219
1
                field_bindings[child_index].__isset.is_variant_subcolumn &&
220
1
                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
1
            return Status::InvalidArgument("Unsupported child node type: {}", child->expr_name());
243
1
        }
244
9
    }
245
246
6
    return Status::OK();
247
10
}
248
249
} // namespace
250
251
91
VSearchExpr::VSearchExpr(const TExprNode& node) : VExpr(node) {
252
91
    if (node.__isset.search_param) {
253
87
        _search_param = node.search_param;
254
87
        _original_dsl = _search_param.original_dsl;
255
87
    }
256
91
}
257
258
Status VSearchExpr::prepare(RuntimeState* state, const RowDescriptor& row_desc,
259
0
                            VExprContext* context) {
260
0
    RETURN_IF_ERROR(VExpr::prepare(state, row_desc, context));
261
0
    const auto& query_options = state->query_options();
262
0
    if (query_options.__isset.enable_inverted_index_query_cache) {
263
0
        _enable_cache = query_options.enable_inverted_index_query_cache;
264
0
    }
265
0
    return Status::OK();
266
0
}
267
268
4
const std::string& VSearchExpr::expr_name() const {
269
4
    static const std::string name = "VSearchExpr";
270
4
    return name;
271
4
}
272
273
Status VSearchExpr::execute_column(VExprContext* context, const Block* block, Selector* selector,
274
3
                                   size_t count, ColumnPtr& result_column) const {
275
3
    if (fast_execute(context, selector, count, result_column)) {
276
1
        return Status::OK();
277
1
    }
278
279
2
    return Status::InternalError("SearchExpr should not be executed without inverted index");
280
3
}
281
282
28
Status VSearchExpr::evaluate_inverted_index(VExprContext* context, uint32_t segment_num_rows) {
283
28
    if (_search_param.original_dsl.empty()) {
284
3
        return Status::InvalidArgument("search DSL is empty");
285
3
    }
286
287
25
    auto index_context = context->get_index_context();
288
25
    if (!index_context) {
289
15
        LOG(WARNING) << "VSearchExpr: No inverted index context available";
290
15
        return Status::OK();
291
15
    }
292
293
10
    SearchInputBundle bundle;
294
10
    RETURN_IF_ERROR(collect_search_inputs(*this, context, &bundle));
295
296
6
    VLOG_DEBUG << "VSearchExpr: bundle.iterators.size()=" << bundle.iterators.size();
297
298
6
    auto index_query_context = index_context->get_index_query_context();
299
300
6
    auto function = std::make_shared<FunctionSearch>();
301
6
    auto result_bitmap = InvertedIndexResultBitmap();
302
6
    auto status = function->evaluate_inverted_index_with_search_param(
303
6
            _search_param, bundle.field_types, bundle.iterators, segment_num_rows, result_bitmap,
304
6
            _enable_cache, index_context.get(), bundle.field_name_to_column_id,
305
6
            index_query_context);
306
307
6
    if (!status.ok()) {
308
2
        LOG(WARNING) << "VSearchExpr: Function evaluation failed: " << status.to_string();
309
2
        return status;
310
2
    }
311
312
4
    index_context->set_index_result_for_expr(this, result_bitmap);
313
4
    for (int column_index : bundle.column_indexes) {
314
0
        index_context->set_true_for_index_status(this, column_index);
315
0
    }
316
317
4
    return Status::OK();
318
6
}
319
320
} // namespace doris