Coverage Report

Created: 2026-03-26 14:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/segment/segment_iterator.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 "storage/segment/segment_iterator.h"
19
20
#include <assert.h>
21
#include <gen_cpp/Exprs_types.h>
22
#include <gen_cpp/Opcodes_types.h>
23
#include <gen_cpp/Types_types.h>
24
#include <gen_cpp/olap_file.pb.h>
25
26
#include <algorithm>
27
#include <boost/iterator/iterator_facade.hpp>
28
#include <cstdint>
29
#include <memory>
30
#include <numeric>
31
#include <set>
32
#include <unordered_map>
33
#include <utility>
34
#include <vector>
35
36
#include "cloud/config.h"
37
#include "common/compiler_util.h" // IWYU pragma: keep
38
#include "common/config.h"
39
#include "common/consts.h"
40
#include "common/exception.h"
41
#include "common/logging.h"
42
#include "common/metrics/doris_metrics.h"
43
#include "common/object_pool.h"
44
#include "common/status.h"
45
#include "core/assert_cast.h"
46
#include "core/block/column_with_type_and_name.h"
47
#include "core/column/column.h"
48
#include "core/column/column_const.h"
49
#include "core/column/column_nothing.h"
50
#include "core/column/column_nullable.h"
51
#include "core/column/column_string.h"
52
#include "core/column/column_variant.h"
53
#include "core/column/column_vector.h"
54
#include "core/data_type/data_type.h"
55
#include "core/data_type/data_type_factory.hpp"
56
#include "core/data_type/data_type_number.h"
57
#include "core/data_type/define_primitive_type.h"
58
#include "core/field.h"
59
#include "core/string_ref.h"
60
#include "core/typeid_cast.h"
61
#include "core/types.h"
62
#include "exprs/function/array/function_array_index.h"
63
#include "exprs/vexpr.h"
64
#include "exprs/vexpr_context.h"
65
#include "exprs/virtual_slot_ref.h"
66
#include "exprs/vliteral.h"
67
#include "exprs/vslot_ref.h"
68
#include "io/cache/cached_remote_file_reader.h"
69
#include "io/fs/file_reader.h"
70
#include "io/io_common.h"
71
#include "runtime/query_context.h"
72
#include "runtime/runtime_predicate.h"
73
#include "runtime/runtime_state.h"
74
#include "runtime/thread_context.h"
75
#include "storage/compaction/collection_similarity.h"
76
#include "storage/field.h"
77
#include "storage/id_manager.h"
78
#include "storage/index/ann/ann_index.h"
79
#include "storage/index/ann/ann_index_iterator.h"
80
#include "storage/index/ann/ann_index_reader.h"
81
#include "storage/index/ann/ann_topn_runtime.h"
82
#include "storage/index/index_file_reader.h"
83
#include "storage/index/index_iterator.h"
84
#include "storage/index/index_query_context.h"
85
#include "storage/index/index_reader_helper.h"
86
#include "storage/index/indexed_column_reader.h"
87
#include "storage/index/inverted/inverted_index_reader.h"
88
#include "storage/index/ordinal_page_index.h"
89
#include "storage/index/primary_key_index.h"
90
#include "storage/index/short_key_index.h"
91
#include "storage/iterators.h"
92
#include "storage/olap_common.h"
93
#include "storage/predicate/bloom_filter_predicate.h"
94
#include "storage/predicate/column_predicate.h"
95
#include "storage/predicate/like_column_predicate.h"
96
#include "storage/schema.h"
97
#include "storage/segment/column_reader.h"
98
#include "storage/segment/column_reader_cache.h"
99
#include "storage/segment/condition_cache.h"
100
#include "storage/segment/row_ranges.h"
101
#include "storage/segment/segment.h"
102
#include "storage/segment/segment_prefetcher.h"
103
#include "storage/segment/variant/variant_column_reader.h"
104
#include "storage/segment/virtual_column_iterator.h"
105
#include "storage/tablet/tablet_schema.h"
106
#include "storage/types.h"
107
#include "storage/utils.h"
108
#include "util/concurrency_stats.h"
109
#include "util/defer_op.h"
110
#include "util/simd/bits.h"
111
112
namespace doris {
113
using namespace ErrorCode;
114
namespace segment_v2 {
115
116
#include "common/compile_check_begin.h"
117
118
5.63k
SegmentIterator::~SegmentIterator() = default;
119
120
5.63k
void SegmentIterator::_init_row_bitmap_by_condition_cache() {
121
    // Only dispose need column predicate and expr cal in condition cache
122
5.63k
    if (!_col_predicates.empty() ||
123
5.63k
        (_enable_common_expr_pushdown && !_remaining_conjunct_roots.empty())) {
124
0
        if (_opts.condition_cache_digest) {
125
0
            auto* condition_cache = ConditionCache::instance();
126
0
            ConditionCache::CacheKey cache_key(_opts.rowset_id, _segment->id(),
127
0
                                               _opts.condition_cache_digest);
128
129
            // Increment search count when digest != 0
130
0
            DorisMetrics::instance()->condition_cache_search_count->increment(1);
131
132
0
            ConditionCacheHandle handle;
133
0
            _find_condition_cache = condition_cache->lookup(cache_key, &handle);
134
135
            // Increment hit count if cache lookup is successful
136
0
            if (_find_condition_cache) {
137
0
                DorisMetrics::instance()->condition_cache_hit_count->increment(1);
138
0
                if (_opts.runtime_state) {
139
0
                    VLOG_DEBUG << "Condition cache hit, query id: "
140
0
                               << print_id(_opts.runtime_state->query_id())
141
0
                               << ", segment id: " << _segment->id()
142
0
                               << ", cache digest: " << _opts.condition_cache_digest
143
0
                               << ", rowset id: " << _opts.rowset_id.to_string();
144
0
                }
145
0
            }
146
147
0
            auto num_rows = _segment->num_rows();
148
0
            if (_find_condition_cache) {
149
0
                const auto& filter_result = *(handle.get_filter_result());
150
0
                int64_t filtered_blocks = 0;
151
0
                for (int i = 0; i < filter_result.size(); i++) {
152
0
                    if (!filter_result[i]) {
153
0
                        _row_bitmap.removeRange(
154
0
                                i * CONDITION_CACHE_OFFSET,
155
0
                                i * CONDITION_CACHE_OFFSET + CONDITION_CACHE_OFFSET);
156
0
                        filtered_blocks++;
157
0
                    }
158
0
                }
159
                // Record condition_cache hit segment number
160
0
                _opts.stats->condition_cache_hit_seg_nums++;
161
                // Record rows filtered by condition cache hit
162
0
                _opts.stats->condition_cache_filtered_rows +=
163
0
                        filtered_blocks * SegmentIterator::CONDITION_CACHE_OFFSET;
164
0
            } else {
165
0
                _condition_cache = std::make_shared<std::vector<bool>>(
166
0
                        num_rows / CONDITION_CACHE_OFFSET + 1, false);
167
0
            }
168
0
        }
169
5.63k
    } else {
170
5.63k
        _opts.condition_cache_digest = 0;
171
5.63k
    }
172
5.63k
}
173
174
// A fast range iterator for roaring bitmap. Output ranges use closed-open form, like [from, to).
175
// Example:
176
//   input bitmap:  [0 1 4 5 6 7 10 15 16 17 18 19]
177
//   output ranges: [0,2), [4,8), [10,11), [15,20) (when max_range_size=10)
178
//   output ranges: [0,2), [4,7), [7,8), [10,11), [15,18), [18,20) (when max_range_size=3)
179
class SegmentIterator::BitmapRangeIterator {
180
public:
181
0
    BitmapRangeIterator() = default;
182
5.63k
    virtual ~BitmapRangeIterator() = default;
183
184
5.63k
    explicit BitmapRangeIterator(const roaring::Roaring& bitmap) {
185
5.63k
        roaring_init_iterator(&bitmap.roaring, &_iter);
186
5.63k
    }
187
188
0
    bool has_more_range() const { return !_eof; }
189
190
12.1k
    [[nodiscard]] static uint32_t get_batch_size() { return kBatchSize; }
191
192
    // read next range into [*from, *to) whose size <= max_range_size.
193
    // return false when there is no more range.
194
0
    virtual bool next_range(const uint32_t max_range_size, uint32_t* from, uint32_t* to) {
195
0
        if (_eof) {
196
0
            return false;
197
0
        }
198
199
0
        *from = _buf[_buf_pos];
200
0
        uint32_t range_size = 0;
201
0
        uint32_t expect_val = _buf[_buf_pos]; // this initial value just make first batch valid
202
203
        // if array is contiguous sequence then the following conditions need to be met :
204
        // a_0: x
205
        // a_1: x+1
206
        // a_2: x+2
207
        // ...
208
        // a_p: x+p
209
        // so we can just use (a_p-a_0)-p to check conditions
210
        // and should notice the previous batch needs to be continuous with the current batch
211
0
        while (!_eof && range_size + _buf_size - _buf_pos <= max_range_size &&
212
0
               expect_val == _buf[_buf_pos] &&
213
0
               _buf[_buf_size - 1] - _buf[_buf_pos] == _buf_size - 1 - _buf_pos) {
214
0
            range_size += _buf_size - _buf_pos;
215
0
            expect_val = _buf[_buf_size - 1] + 1;
216
0
            _read_next_batch();
217
0
        }
218
219
        // promise remain range not will reach next batch
220
0
        if (!_eof && range_size < max_range_size && expect_val == _buf[_buf_pos]) {
221
0
            do {
222
0
                _buf_pos++;
223
0
                range_size++;
224
0
            } while (range_size < max_range_size && _buf[_buf_pos] == _buf[_buf_pos - 1] + 1);
225
0
        }
226
0
        *to = *from + range_size;
227
0
        return true;
228
0
    }
229
230
    // read batch_size of rowids from roaring bitmap into buf array
231
23.1k
    virtual uint32_t read_batch_rowids(rowid_t* buf, uint32_t batch_size) {
232
23.1k
        return roaring::api::roaring_read_uint32_iterator(&_iter, buf, batch_size);
233
23.1k
    }
234
235
private:
236
0
    void _read_next_batch() {
237
0
        _buf_pos = 0;
238
0
        _buf_size = roaring::api::roaring_read_uint32_iterator(&_iter, _buf, kBatchSize);
239
0
        _eof = (_buf_size == 0);
240
0
    }
241
242
    static const uint32_t kBatchSize = 256;
243
    roaring::api::roaring_uint32_iterator_t _iter;
244
    uint32_t _buf[kBatchSize];
245
    uint32_t _buf_pos = 0;
246
    uint32_t _buf_size = 0;
247
    bool _eof = false;
248
};
249
250
// A backward range iterator for roaring bitmap. Output ranges use closed-open form, like [from, to).
251
// Example:
252
//   input bitmap:  [0 1 4 5 6 7 10 15 16 17 18 19]
253
//   output ranges: , [15,20), [10,11), [4,8), [0,2) (when max_range_size=10)
254
//   output ranges: [17,20), [15,17), [10,11), [5,8), [4, 5), [0,2) (when max_range_size=3)
255
class SegmentIterator::BackwardBitmapRangeIterator : public SegmentIterator::BitmapRangeIterator {
256
public:
257
0
    explicit BackwardBitmapRangeIterator(const roaring::Roaring& bitmap) {
258
0
        roaring_init_iterator_last(&bitmap.roaring, &_riter);
259
0
        _rowid_count = cast_set<uint32_t>(roaring_bitmap_get_cardinality(&bitmap.roaring));
260
0
        _rowid_left = _rowid_count;
261
0
    }
262
263
0
    bool has_more_range() const { return !_riter.has_value; }
264
265
    // read next range into [*from, *to) whose size <= max_range_size.
266
    // return false when there is no more range.
267
0
    bool next_range(const uint32_t max_range_size, uint32_t* from, uint32_t* to) override {
268
0
        if (!_riter.has_value) {
269
0
            return false;
270
0
        }
271
272
0
        uint32_t range_size = 0;
273
0
        *to = _riter.current_value + 1;
274
275
0
        do {
276
0
            *from = _riter.current_value;
277
0
            range_size++;
278
0
            roaring_previous_uint32_iterator(&_riter);
279
0
        } while (range_size < max_range_size && _riter.has_value &&
280
0
                 _riter.current_value + 1 == *from);
281
282
0
        return true;
283
0
    }
284
    /**
285
     * Reads a batch of row IDs from a roaring bitmap, starting from the end and moving backwards.
286
     * This function retrieves the last `batch_size` row IDs from the bitmap and stores them in the provided buffer.
287
     * It updates the internal state to track how many row IDs are left to read in subsequent calls.
288
     *
289
     * The row IDs are read in reverse order, but stored in the buffer maintaining their original order in the bitmap.
290
     *
291
     * Example:
292
     *   input bitmap: [0 1 4 5 6 7 10 15 16 17 18 19]
293
     *   If the bitmap has 12 elements and batch_size is set to 5, the function will first read [15, 16, 17, 18, 19]
294
     *   into the buffer, leaving 7 elements left. In the next call with batch_size 5, it will read [4, 5, 6, 7, 10].
295
     *
296
     */
297
0
    uint32_t read_batch_rowids(rowid_t* buf, uint32_t batch_size) override {
298
0
        if (!_riter.has_value || _rowid_left == 0) {
299
0
            return 0;
300
0
        }
301
302
0
        if (_rowid_count <= batch_size) {
303
0
            roaring_bitmap_to_uint32_array(_riter.parent,
304
0
                                           buf); // Fill 'buf' with '_rowid_count' elements.
305
0
            uint32_t num_read = _rowid_left;     // Save the number of row IDs read.
306
0
            _rowid_left = 0;                     // No row IDs left after this operation.
307
0
            return num_read;                     // Return the number of row IDs read.
308
0
        }
309
310
0
        uint32_t read_size = std::min(batch_size, _rowid_left);
311
0
        uint32_t num_read = 0; // Counter for the number of row IDs read.
312
313
        // Read row IDs into the buffer in reverse order.
314
0
        while (num_read < read_size && _riter.has_value) {
315
0
            buf[read_size - num_read - 1] = _riter.current_value;
316
0
            num_read++;
317
0
            _rowid_left--; // Decrement the count of remaining row IDs.
318
0
            roaring_previous_uint32_iterator(&_riter);
319
0
        }
320
321
        // Return the actual number of row IDs read.
322
0
        return num_read;
323
0
    }
324
325
private:
326
    roaring::api::roaring_uint32_iterator_t _riter;
327
    uint32_t _rowid_count;
328
    uint32_t _rowid_left;
329
};
330
331
SegmentIterator::SegmentIterator(std::shared_ptr<Segment> segment, SchemaSPtr schema)
332
5.63k
        : _segment(std::move(segment)),
333
5.63k
          _schema(schema),
334
5.63k
          _column_iterators(_schema->num_columns()),
335
5.63k
          _index_iterators(_schema->num_columns()),
336
5.63k
          _cur_rowid(0),
337
5.63k
          _lazy_materialization_read(false),
338
5.63k
          _lazy_inited(false),
339
5.63k
          _inited(false),
340
5.63k
          _pool(new ObjectPool) {}
341
342
11.1k
Status SegmentIterator::init(const StorageReadOptions& opts) {
343
11.1k
    auto status = _init_impl(opts);
344
11.1k
    if (!status.ok()) {
345
0
        _segment->update_healthy_status(status);
346
0
    }
347
11.1k
    return status;
348
11.1k
}
349
350
11.1k
Status SegmentIterator::_init_impl(const StorageReadOptions& opts) {
351
    // get file handle from file descriptor of segment
352
11.1k
    if (_inited) {
353
5.49k
        return Status::OK();
354
5.49k
    }
355
5.63k
    _opts = opts;
356
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_timer_ns);
357
5.63k
    _inited = true;
358
5.63k
    _file_reader = _segment->_file_reader;
359
5.63k
    _col_predicates.clear();
360
361
5.63k
    for (const auto& predicate : opts.column_predicates) {
362
0
        if (!_segment->can_apply_predicate_safely(predicate->column_id(), *_schema,
363
0
                                                  _opts.target_cast_type_for_variants, _opts)) {
364
0
            continue;
365
0
        }
366
0
        _col_predicates.emplace_back(predicate);
367
0
    }
368
5.63k
    _tablet_id = opts.tablet_id;
369
    // Read options will not change, so that just resize here
370
5.63k
    _block_rowids.resize(_opts.block_row_max);
371
372
5.63k
    _remaining_conjunct_roots = opts.remaining_conjunct_roots;
373
374
5.63k
    if (_schema->rowid_col_idx() > 0) {
375
0
        _record_rowids = true;
376
0
    }
377
378
5.63k
    _virtual_column_exprs = _opts.virtual_column_exprs;
379
5.63k
    _vir_cid_to_idx_in_block = _opts.vir_cid_to_idx_in_block;
380
5.63k
    _score_runtime = _opts.score_runtime;
381
5.63k
    _ann_topn_runtime = _opts.ann_topn_runtime;
382
383
5.63k
    if (opts.output_columns != nullptr) {
384
1.29k
        _output_columns = *(opts.output_columns);
385
1.29k
    }
386
387
5.63k
    _storage_name_and_type.resize(_schema->columns().size());
388
5.63k
    auto storage_format = _opts.tablet_schema->get_inverted_index_storage_format();
389
34.2k
    for (int i = 0; i < _schema->columns().size(); ++i) {
390
28.6k
        const StorageField* col = _schema->column(i);
391
28.6k
        if (col) {
392
12.6k
            auto storage_type = _segment->get_data_type_of(col->get_desc(), _opts);
393
12.6k
            if (storage_type == nullptr) {
394
0
                storage_type = DataTypeFactory::instance().create_data_type(col->get_desc(),
395
0
                                                                            col->is_nullable());
396
0
            }
397
            // Currently, when writing a lucene index, the field of the document is column_name, and the column name is
398
            // bound to the index field. Since version 1.2, the data file storage has been changed from column_name to
399
            // column_unique_id, allowing the column name to be changed. Due to current limitations, previous inverted
400
            // index data cannot be used after Doris changes the column name. Column names also support Unicode
401
            // characters, which may cause other problems with indexing in non-ASCII characters.
402
            // After consideration, it was decided to change the field name from column_name to column_unique_id in
403
            // format V2, while format V1 continues to use column_name.
404
12.6k
            std::string field_name;
405
12.6k
            if (storage_format == InvertedIndexStorageFormatPB::V1) {
406
9.98k
                field_name = col->name();
407
9.98k
            } else {
408
2.68k
                if (col->is_extracted_column()) {
409
                    // variant sub col
410
                    // field_name format: parent_unique_id.sub_col_name
411
0
                    field_name = std::to_string(col->parent_unique_id()) + "." + col->name();
412
2.68k
                } else {
413
2.68k
                    field_name = std::to_string(col->unique_id());
414
2.68k
                }
415
2.68k
            }
416
12.6k
            _storage_name_and_type[i] = std::make_pair(field_name, storage_type);
417
12.6k
            if (int32_t uid = col->get_unique_id(); !_variant_sparse_column_cache.contains(uid)) {
418
12.6k
                DCHECK(uid >= 0);
419
12.6k
                _variant_sparse_column_cache.emplace(uid,
420
12.6k
                                                     std::make_unique<PathToBinaryColumnCache>());
421
12.6k
            }
422
12.6k
        }
423
28.6k
    }
424
425
5.63k
    RETURN_IF_ERROR(init_iterators());
426
427
5.63k
    RETURN_IF_ERROR(_construct_compound_expr_context());
428
5.63k
    _enable_common_expr_pushdown = !_common_expr_ctxs_push_down.empty();
429
5.63k
    VLOG_DEBUG << fmt::format(
430
0
            "Segment iterator init, virtual_column_exprs size: {}, "
431
0
            "_vir_cid_to_idx_in_block size: {}, common_expr_pushdown size: {}",
432
0
            _opts.virtual_column_exprs.size(), _opts.vir_cid_to_idx_in_block.size(),
433
0
            _common_expr_ctxs_push_down.size());
434
5.63k
    _initialize_predicate_results();
435
5.63k
    return Status::OK();
436
5.63k
}
437
438
5.63k
void SegmentIterator::_initialize_predicate_results() {
439
    // Initialize from _col_predicates
440
5.63k
    for (auto pred : _col_predicates) {
441
0
        int cid = pred->column_id();
442
0
        _column_predicate_index_exec_status[cid][pred] = false;
443
0
    }
444
445
5.63k
    _calculate_expr_in_remaining_conjunct_root();
446
5.63k
}
447
448
5.63k
Status SegmentIterator::init_iterators() {
449
5.63k
    RETURN_IF_ERROR(_init_return_column_iterators());
450
5.63k
    RETURN_IF_ERROR(_init_index_iterators());
451
5.63k
    return Status::OK();
452
5.63k
}
453
454
23.1k
Status SegmentIterator::_lazy_init(Block* block) {
455
23.1k
    if (_lazy_inited) {
456
17.4k
        return Status::OK();
457
17.4k
    }
458
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->block_init_ns);
459
5.63k
    DorisMetrics::instance()->segment_read_total->increment(1);
460
5.63k
    _row_bitmap.addRange(0, _segment->num_rows());
461
5.63k
    _init_row_bitmap_by_condition_cache();
462
463
    // z-order can not use prefix index
464
5.63k
    if (_segment->_tablet_schema->sort_type() != SortType::ZORDER &&
465
5.63k
        _segment->_tablet_schema->cluster_key_uids().empty()) {
466
5.63k
        RETURN_IF_ERROR(_get_row_ranges_by_keys());
467
5.63k
    }
468
5.63k
    RETURN_IF_ERROR(_get_row_ranges_by_column_conditions());
469
5.63k
    RETURN_IF_ERROR(_vec_init_lazy_materialization());
470
    // Remove rows that have been marked deleted
471
5.63k
    if (_opts.delete_bitmap.count(segment_id()) > 0 &&
472
5.63k
        _opts.delete_bitmap.at(segment_id()) != nullptr) {
473
25
        size_t pre_size = _row_bitmap.cardinality();
474
25
        _row_bitmap -= *(_opts.delete_bitmap.at(segment_id()));
475
25
        _opts.stats->rows_del_by_bitmap += (pre_size - _row_bitmap.cardinality());
476
25
        VLOG_DEBUG << "read on segment: " << segment_id() << ", delete bitmap cardinality: "
477
0
                   << _opts.delete_bitmap.at(segment_id())->cardinality() << ", "
478
0
                   << _opts.stats->rows_del_by_bitmap << " rows deleted by bitmap";
479
25
    }
480
481
5.63k
    if (!_opts.row_ranges.is_empty()) {
482
0
        _row_bitmap &= RowRanges::ranges_to_roaring(_opts.row_ranges);
483
0
    }
484
485
5.63k
    _prepare_score_column_materialization();
486
487
5.63k
    RETURN_IF_ERROR(_apply_ann_topn_predicate());
488
489
5.63k
    if (_opts.read_orderby_key_reverse) {
490
0
        _range_iter.reset(new BackwardBitmapRangeIterator(_row_bitmap));
491
5.63k
    } else {
492
5.63k
        _range_iter.reset(new BitmapRangeIterator(_row_bitmap));
493
5.63k
    }
494
495
    // If the row bitmap size is smaller than block_row_max, there's no need to reserve that many column rows.
496
5.63k
    auto nrows_reserve_limit = std::min(_row_bitmap.cardinality(), uint64_t(_opts.block_row_max));
497
5.63k
    if (_lazy_materialization_read || _opts.record_rowids || _is_need_expr_eval) {
498
894
        _block_rowids.resize(_opts.block_row_max);
499
894
    }
500
5.63k
    _current_return_columns.resize(_schema->columns().size());
501
502
5.63k
    _vec_init_char_column_id(block);
503
18.3k
    for (size_t i = 0; i < _schema->column_ids().size(); i++) {
504
12.6k
        ColumnId cid = _schema->column_ids()[i];
505
12.6k
        const auto* column_desc = _schema->column(cid);
506
12.6k
        if (_is_pred_column[cid]) {
507
467
            auto storage_column_type = _storage_name_and_type[cid].second;
508
            // Char type is special , since char type's computational datatype is same with string,
509
            // both are DataTypeString, but DataTypeString only return FieldType::OLAP_FIELD_TYPE_STRING
510
            // in get_storage_field_type.
511
467
            RETURN_IF_CATCH_EXCEPTION(
512
                    // Here, cid will not go out of bounds
513
                    // because the size of _current_return_columns equals _schema->tablet_columns().size()
514
467
                    _current_return_columns[cid] = Schema::get_predicate_column_ptr(
515
467
                            _is_char_type[cid] ? FieldType::OLAP_FIELD_TYPE_CHAR
516
467
                                               : storage_column_type->get_storage_field_type(),
517
467
                            storage_column_type->is_nullable(), _opts.io_ctx.reader_type));
518
467
            _current_return_columns[cid]->set_rowset_segment_id(
519
467
                    {_segment->rowset_id(), _segment->id()});
520
467
            _current_return_columns[cid]->reserve(nrows_reserve_limit);
521
12.2k
        } else if (i >= block->columns()) {
522
            // This column needs to be scanned, but doesn't need to be returned upward. (delete sign)
523
            // if i >= block->columns means the column and not the pred_column means `column i` is
524
            // a delete condition column. but the column is not effective in the segment. so we just
525
            // create a column to hold the data.
526
            // a. origin data -> b. delete condition -> c. new load data
527
            // the segment of c do not effective delete condition, but it still need read the column
528
            // to match the schema.
529
            // TODO: skip read the not effective delete column to speed up segment read.
530
0
            _current_return_columns[cid] = Schema::get_data_type_ptr(*column_desc)->create_column();
531
0
            _current_return_columns[cid]->reserve(nrows_reserve_limit);
532
0
        }
533
12.6k
    }
534
535
    // Additional deleted filter condition will be materialized column be at the end of the block,
536
    // after _output_column_by_sel_idx  will be erase, we not need to filter it,
537
    // so erase it from _columns_to_filter in the first next_batch.
538
    // Eg:
539
    //      `delete from table where a = 10;`
540
    //      `select b from table;`
541
    // a column only effective in segment iterator, the block from query engine only contain the b column,
542
    // so no need to filter a column by expr.
543
5.63k
    for (auto it = _columns_to_filter.begin(); it != _columns_to_filter.end();) {
544
0
        if (*it >= block->columns()) {
545
0
            it = _columns_to_filter.erase(it);
546
0
        } else {
547
0
            ++it;
548
0
        }
549
0
    }
550
551
5.63k
    _lazy_inited = true;
552
553
5.63k
    _init_segment_prefetchers();
554
555
5.63k
    return Status::OK();
556
5.63k
}
557
558
5.63k
void SegmentIterator::_init_segment_prefetchers() {
559
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_segment_prefetchers_timer_ns);
560
5.63k
    if (!config::is_cloud_mode()) {
561
5.63k
        return;
562
5.63k
    }
563
0
    static std::vector<ReaderType> supported_reader_types {
564
0
            ReaderType::READER_QUERY, ReaderType::READER_BASE_COMPACTION,
565
0
            ReaderType::READER_CUMULATIVE_COMPACTION, ReaderType::READER_FULL_COMPACTION};
566
0
    if (std::ranges::none_of(supported_reader_types,
567
0
                             [&](ReaderType t) { return _opts.io_ctx.reader_type == t; })) {
568
0
        return;
569
0
    }
570
    // Initialize segment prefetcher for predicate and non-predicate columns
571
0
    bool is_query = (_opts.io_ctx.reader_type == ReaderType::READER_QUERY);
572
0
    bool enable_prefetch = is_query ? config::enable_query_segment_file_cache_prefetch
573
0
                                    : config::enable_compaction_segment_file_cache_prefetch;
574
0
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
575
0
            "[verbose] SegmentIterator _init_segment_prefetchers, is_query={}, enable_prefetch={}, "
576
0
            "_row_bitmap.isEmpty()={}, row_bitmap.cardinality()={}, tablet={}, rowset={}, "
577
0
            "segment={}, predicate_column_ids={}, common_expr_column_ids={}",
578
0
            is_query, enable_prefetch, _row_bitmap.isEmpty(), _row_bitmap.cardinality(),
579
0
            _opts.tablet_id, _opts.rowset_id.to_string(), segment_id(),
580
0
            fmt::join(_predicate_column_ids, ","), fmt::join(_common_expr_column_ids, ","));
581
0
    if (enable_prefetch && !_row_bitmap.isEmpty()) {
582
0
        int window_size =
583
0
                1 + (is_query ? config::query_segment_file_cache_prefetch_block_size
584
0
                              : config::compaction_segment_file_cache_prefetch_block_size);
585
0
        LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
586
0
                "[verbose] SegmentIterator prefetch config: window_size={}", window_size);
587
0
        if (window_size > 0 &&
588
0
            !_column_iterators.empty()) { // ensure init_iterators has been called
589
0
            SegmentPrefetcherConfig prefetch_config(window_size,
590
0
                                                    config::file_cache_each_block_size);
591
0
            for (auto cid : _schema->column_ids()) {
592
0
                auto& column_iter = _column_iterators[cid];
593
0
                if (column_iter == nullptr) {
594
0
                    continue;
595
0
                }
596
0
                const auto* tablet_column = _schema->column(cid);
597
0
                SegmentPrefetchParams params {
598
0
                        .config = prefetch_config,
599
0
                        .read_options = _opts,
600
0
                };
601
0
                LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
602
0
                        "[verbose] SegmentIterator init_segment_prefetchers, "
603
0
                        "tablet={}, rowset={}, segment={}, column_id={}, col_name={}, type={}",
604
0
                        _opts.tablet_id, _opts.rowset_id.to_string(), segment_id(), cid,
605
0
                        tablet_column->name(), tablet_column->type());
606
0
                Status st = column_iter->init_prefetcher(params);
607
0
                if (!st.ok()) {
608
0
                    LOG_IF(WARNING, config::enable_segment_prefetch_verbose_log) << fmt::format(
609
0
                            "[verbose] failed to init prefetcher for column_id={}, "
610
0
                            "tablet={}, rowset={}, segment={}, error={}",
611
0
                            cid, _opts.tablet_id, _opts.rowset_id.to_string(), segment_id(),
612
0
                            st.to_string());
613
0
                }
614
0
            }
615
616
            // for compaction, it's guaranteed that all rows are read, so we can prefetch all data blocks
617
0
            PrefetcherInitMethod init_method = (is_query && _row_bitmap.cardinality() < num_rows())
618
0
                                                       ? PrefetcherInitMethod::FROM_ROWIDS
619
0
                                                       : PrefetcherInitMethod::ALL_DATA_BLOCKS;
620
0
            std::map<PrefetcherInitMethod, std::vector<SegmentPrefetcher*>> prefetchers;
621
0
            for (const auto& column_iter : _column_iterators) {
622
0
                if (column_iter != nullptr) {
623
0
                    column_iter->collect_prefetchers(prefetchers, init_method);
624
0
                }
625
0
            }
626
0
            for (auto& [method, prefetcher_vec] : prefetchers) {
627
0
                if (method == PrefetcherInitMethod::ALL_DATA_BLOCKS) {
628
0
                    for (auto* prefetcher : prefetcher_vec) {
629
0
                        prefetcher->build_all_data_blocks();
630
0
                    }
631
0
                } else if (method == PrefetcherInitMethod::FROM_ROWIDS && !prefetcher_vec.empty()) {
632
0
                    SegmentPrefetcher::build_blocks_by_rowids(_row_bitmap, prefetcher_vec);
633
0
                }
634
0
            }
635
0
        }
636
0
    }
637
0
}
638
639
5.63k
Status SegmentIterator::_get_row_ranges_by_keys() {
640
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_keys_ns);
641
5.63k
    DorisMetrics::instance()->segment_row_total->increment(num_rows());
642
643
    // fast path for empty segment or empty key ranges
644
5.63k
    if (_row_bitmap.isEmpty() || _opts.key_ranges.empty()) {
645
5.63k
        return Status::OK();
646
5.63k
    }
647
648
    // Read & seek key columns is a waste of time when no key column in _schema
649
0
    if (std::none_of(
650
0
                _schema->columns().begin(), _schema->columns().end(), [&](const StorageField* col) {
651
0
                    return col && _opts.tablet_schema->column_by_uid(col->unique_id()).is_key();
652
0
                })) {
653
0
        return Status::OK();
654
0
    }
655
656
0
    RowRanges result_ranges;
657
0
    for (auto& key_range : _opts.key_ranges) {
658
0
        rowid_t lower_rowid = 0;
659
0
        rowid_t upper_rowid = num_rows();
660
0
        RETURN_IF_ERROR(_prepare_seek(key_range));
661
0
        if (key_range.upper_key != nullptr) {
662
            // If client want to read upper_bound, the include_upper is true. So we
663
            // should get the first ordinal at which key is larger than upper_bound.
664
            // So we call _lookup_ordinal with include_upper's negate
665
0
            RETURN_IF_ERROR(_lookup_ordinal(*key_range.upper_key, !key_range.include_upper,
666
0
                                            num_rows(), &upper_rowid));
667
0
        }
668
0
        if (upper_rowid > 0 && key_range.lower_key != nullptr) {
669
0
            RETURN_IF_ERROR(_lookup_ordinal(*key_range.lower_key, key_range.include_lower,
670
0
                                            upper_rowid, &lower_rowid));
671
0
        }
672
0
        auto row_range = RowRanges::create_single(lower_rowid, upper_rowid);
673
0
        RowRanges::ranges_union(result_ranges, row_range, &result_ranges);
674
0
    }
675
0
    size_t pre_size = _row_bitmap.cardinality();
676
0
    _row_bitmap &= RowRanges::ranges_to_roaring(result_ranges);
677
0
    _opts.stats->rows_key_range_filtered += (pre_size - _row_bitmap.cardinality());
678
679
0
    return Status::OK();
680
0
}
681
682
// Set up environment for the following seek.
683
0
Status SegmentIterator::_prepare_seek(const StorageReadOptions::KeyRange& key_range) {
684
0
    std::vector<const StorageField*> key_fields;
685
0
    std::set<uint32_t> column_set;
686
0
    if (key_range.lower_key != nullptr) {
687
0
        for (auto cid : key_range.lower_key->schema()->column_ids()) {
688
0
            column_set.emplace(cid);
689
0
            key_fields.emplace_back(key_range.lower_key->column_schema(cid));
690
0
        }
691
0
    }
692
0
    if (key_range.upper_key != nullptr) {
693
0
        for (auto cid : key_range.upper_key->schema()->column_ids()) {
694
0
            if (column_set.count(cid) == 0) {
695
0
                key_fields.emplace_back(key_range.upper_key->column_schema(cid));
696
0
                column_set.emplace(cid);
697
0
            }
698
0
        }
699
0
    }
700
0
    if (!_seek_schema) {
701
0
        _seek_schema = std::make_unique<Schema>(key_fields, key_fields.size());
702
0
    }
703
    // todo(wb) need refactor here, when using pk to search, _seek_block is useless
704
0
    if (_seek_block.size() == 0) {
705
0
        _seek_block.resize(_seek_schema->num_column_ids());
706
0
        int i = 0;
707
0
        for (auto cid : _seek_schema->column_ids()) {
708
0
            auto column_desc = _seek_schema->column(cid);
709
0
            _seek_block[i] = Schema::get_column_by_field(*column_desc);
710
0
            i++;
711
0
        }
712
0
    }
713
714
    // create used column iterator
715
0
    for (auto cid : _seek_schema->column_ids()) {
716
0
        if (_column_iterators[cid] == nullptr) {
717
            // TODO: Do we need this?
718
0
            if (_virtual_column_exprs.contains(cid)) {
719
0
                _column_iterators[cid] = std::make_unique<VirtualColumnIterator>();
720
0
                continue;
721
0
            }
722
723
0
            RETURN_IF_ERROR(_segment->new_column_iterator(_opts.tablet_schema->column(cid),
724
0
                                                          &_column_iterators[cid], &_opts,
725
0
                                                          &_variant_sparse_column_cache));
726
0
            ColumnIteratorOptions iter_opts {
727
0
                    .use_page_cache = _opts.use_page_cache,
728
0
                    .file_reader = _file_reader.get(),
729
0
                    .stats = _opts.stats,
730
0
                    .io_ctx = _opts.io_ctx,
731
0
            };
732
0
            RETURN_IF_ERROR(_column_iterators[cid]->init(iter_opts));
733
0
        }
734
0
    }
735
736
0
    return Status::OK();
737
0
}
738
739
5.63k
Status SegmentIterator::_get_row_ranges_by_column_conditions() {
740
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_column_conditions_ns);
741
5.63k
    if (_row_bitmap.isEmpty()) {
742
0
        return Status::OK();
743
0
    }
744
745
5.63k
    {
746
5.63k
        if (_opts.runtime_state &&
747
5.63k
            _opts.runtime_state->query_options().enable_inverted_index_query &&
748
5.63k
            (has_index_in_iterators() || !_common_expr_ctxs_push_down.empty())) {
749
0
            SCOPED_RAW_TIMER(&_opts.stats->inverted_index_filter_timer);
750
0
            size_t input_rows = _row_bitmap.cardinality();
751
            // Only apply column-level inverted index if we have iterators
752
0
            if (has_index_in_iterators()) {
753
0
                RETURN_IF_ERROR(_apply_inverted_index());
754
0
            }
755
            // Always apply expr-level index (e.g., search expressions) if we have common_expr_pushdown
756
            // This allows search expressions with variant subcolumns to be evaluated even when
757
            // the segment doesn't have all subcolumns
758
0
            RETURN_IF_ERROR(_apply_index_expr());
759
0
            for (auto it = _common_expr_ctxs_push_down.begin();
760
0
                 it != _common_expr_ctxs_push_down.end();) {
761
0
                if ((*it)->all_expr_inverted_index_evaluated()) {
762
0
                    const auto* result = (*it)->get_index_context()->get_index_result_for_expr(
763
0
                            (*it)->root().get());
764
0
                    if (result != nullptr) {
765
0
                        _row_bitmap &= *result->get_data_bitmap();
766
0
                        auto root = (*it)->root();
767
0
                        auto iter_find = std::find(_remaining_conjunct_roots.begin(),
768
0
                                                   _remaining_conjunct_roots.end(), root);
769
0
                        if (iter_find != _remaining_conjunct_roots.end()) {
770
0
                            _remaining_conjunct_roots.erase(iter_find);
771
0
                        }
772
0
                        it = _common_expr_ctxs_push_down.erase(it);
773
0
                    }
774
0
                } else {
775
0
                    ++it;
776
0
                }
777
0
            }
778
0
            _opts.condition_cache_digest =
779
0
                    _common_expr_ctxs_push_down.empty() ? 0 : _opts.condition_cache_digest;
780
0
            _opts.stats->rows_inverted_index_filtered += (input_rows - _row_bitmap.cardinality());
781
0
            for (auto cid : _schema->column_ids()) {
782
0
                bool result_true = _check_all_conditions_passed_inverted_index_for_column(cid);
783
0
                if (result_true) {
784
0
                    _need_read_data_indices[cid] = false;
785
0
                }
786
0
            }
787
0
        }
788
5.63k
    }
789
790
5.63k
    DBUG_EXECUTE_IF("segment_iterator.inverted_index.filtered_rows", {
791
5.63k
        LOG(INFO) << "Debug Point: segment_iterator.inverted_index.filtered_rows: "
792
5.63k
                  << _opts.stats->rows_inverted_index_filtered;
793
5.63k
        auto filtered_rows = DebugPoints::instance()->get_debug_param_or_default<int32_t>(
794
5.63k
                "segment_iterator.inverted_index.filtered_rows", "filtered_rows", -1);
795
5.63k
        if (filtered_rows != _opts.stats->rows_inverted_index_filtered) {
796
5.63k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
797
5.63k
                    "filtered_rows: {} not equal to expected: {}",
798
5.63k
                    _opts.stats->rows_inverted_index_filtered, filtered_rows);
799
5.63k
        }
800
5.63k
    })
801
802
5.63k
    DBUG_EXECUTE_IF("segment_iterator.apply_inverted_index", {
803
5.63k
        LOG(INFO) << "Debug Point: segment_iterator.apply_inverted_index";
804
5.63k
        if (!_common_expr_ctxs_push_down.empty() || !_col_predicates.empty()) {
805
5.63k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
806
5.63k
                    "it is failed to apply inverted index, common_expr_ctxs_push_down: {}, "
807
5.63k
                    "col_predicates: {}",
808
5.63k
                    _common_expr_ctxs_push_down.size(), _col_predicates.size());
809
5.63k
        }
810
5.63k
    })
811
812
5.63k
    if (!_row_bitmap.isEmpty() &&
813
5.63k
        (!_opts.topn_filter_source_node_ids.empty() || !_opts.col_id_to_predicates.empty() ||
814
5.63k
         _opts.delete_condition_predicates->num_of_column_predicate() > 0)) {
815
467
        RowRanges condition_row_ranges = RowRanges::create_single(_segment->num_rows());
816
467
        RETURN_IF_ERROR(_get_row_ranges_from_conditions(&condition_row_ranges));
817
467
        size_t pre_size = _row_bitmap.cardinality();
818
467
        _row_bitmap &= RowRanges::ranges_to_roaring(condition_row_ranges);
819
467
        _opts.stats->rows_conditions_filtered += (pre_size - _row_bitmap.cardinality());
820
467
    }
821
822
5.63k
    DBUG_EXECUTE_IF("bloom_filter_must_filter_data", {
823
5.63k
        if (_opts.stats->rows_bf_filtered == 0) {
824
5.63k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
825
5.63k
                    "Bloom filter did not filter the data.");
826
5.63k
        }
827
5.63k
    })
828
829
    // TODO(hkp): calculate filter rate to decide whether to
830
    // use zone map/bloom filter/secondary index or not.
831
5.63k
    return Status::OK();
832
5.63k
}
833
834
0
bool SegmentIterator::_column_has_ann_index(int32_t cid) {
835
0
    bool has_ann_index = _index_iterators[cid] != nullptr &&
836
0
                         _index_iterators[cid]->get_reader(AnnIndexReaderType::ANN);
837
838
0
    return has_ann_index;
839
0
}
840
841
5.63k
Status SegmentIterator::_apply_ann_topn_predicate() {
842
5.63k
    if (_ann_topn_runtime == nullptr) {
843
5.63k
        return Status::OK();
844
5.63k
    }
845
846
0
    VLOG_DEBUG << fmt::format("Try apply ann topn: {}", _ann_topn_runtime->debug_string());
847
0
    size_t src_col_idx = _ann_topn_runtime->get_src_column_idx();
848
0
    ColumnId src_cid = _schema->column_id(src_col_idx);
849
0
    IndexIterator* ann_index_iterator = _index_iterators[src_cid].get();
850
0
    bool has_ann_index = _column_has_ann_index(src_cid);
851
0
    bool has_common_expr_push_down = !_common_expr_ctxs_push_down.empty();
852
0
    bool has_column_predicate = std::any_of(_is_pred_column.begin(), _is_pred_column.end(),
853
0
                                            [](bool is_pred) { return is_pred; });
854
0
    if (!has_ann_index || has_common_expr_push_down || has_column_predicate) {
855
0
        VLOG_DEBUG << fmt::format(
856
0
                "Ann topn can not be evaluated by ann index, has_ann_index: {}, "
857
0
                "has_common_expr_push_down: {}, has_column_predicate: {}",
858
0
                has_ann_index, has_common_expr_push_down, has_column_predicate);
859
        // Disable index-only scan on ann indexed column.
860
0
        _need_read_data_indices[src_cid] = true;
861
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
862
0
        return Status::OK();
863
0
    }
864
865
    // Process asc & desc according to the type of metric
866
0
    auto index_reader = ann_index_iterator->get_reader(AnnIndexReaderType::ANN);
867
0
    auto ann_index_reader = dynamic_cast<AnnIndexReader*>(index_reader.get());
868
0
    DCHECK(ann_index_reader != nullptr);
869
0
    if (ann_index_reader->get_metric_type() == AnnIndexMetric::IP) {
870
0
        if (_ann_topn_runtime->is_asc()) {
871
0
            VLOG_DEBUG << fmt::format(
872
0
                    "Asc topn for inner product can not be evaluated by ann index");
873
            // Disable index-only scan on ann indexed column.
874
0
            _need_read_data_indices[src_cid] = true;
875
0
            _opts.stats->ann_fall_back_brute_force_cnt += 1;
876
0
            return Status::OK();
877
0
        }
878
0
    } else {
879
0
        if (!_ann_topn_runtime->is_asc()) {
880
0
            VLOG_DEBUG << fmt::format("Desc topn for l2/cosine can not be evaluated by ann index");
881
            // Disable index-only scan on ann indexed column.
882
0
            _need_read_data_indices[src_cid] = true;
883
0
            _opts.stats->ann_fall_back_brute_force_cnt += 1;
884
0
            return Status::OK();
885
0
        }
886
0
    }
887
888
0
    if (ann_index_reader->get_metric_type() != _ann_topn_runtime->get_metric_type()) {
889
0
        VLOG_DEBUG << fmt::format(
890
0
                "Ann topn metric type {} not match index metric type {}, can not be evaluated by "
891
0
                "ann index",
892
0
                metric_to_string(_ann_topn_runtime->get_metric_type()),
893
0
                metric_to_string(ann_index_reader->get_metric_type()));
894
        // Disable index-only scan on ann indexed column.
895
0
        _need_read_data_indices[src_cid] = true;
896
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
897
0
        return Status::OK();
898
0
    }
899
900
0
    size_t pre_size = _row_bitmap.cardinality();
901
0
    size_t rows_of_segment = _segment->num_rows();
902
0
    if (static_cast<double>(pre_size) < static_cast<double>(rows_of_segment) * 0.3) {
903
0
        VLOG_DEBUG << fmt::format(
904
0
                "Ann topn predicate input rows {} < 30% of segment rows {}, will not use ann index "
905
0
                "to "
906
0
                "filter",
907
0
                pre_size, rows_of_segment);
908
        // Disable index-only scan on ann indexed column.
909
0
        _need_read_data_indices[src_cid] = true;
910
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
911
0
        return Status::OK();
912
0
    }
913
0
    IColumn::MutablePtr result_column;
914
0
    std::unique_ptr<std::vector<uint64_t>> result_row_ids;
915
0
    segment_v2::AnnIndexStats ann_index_stats;
916
917
    // Try to load ANN index before search
918
0
    auto ann_index_iterator_casted =
919
0
            dynamic_cast<segment_v2::AnnIndexIterator*>(ann_index_iterator);
920
0
    if (ann_index_iterator_casted == nullptr) {
921
0
        VLOG_DEBUG << "Failed to cast index iterator to AnnIndexIterator, fallback to brute force";
922
0
        _need_read_data_indices[src_cid] = true;
923
0
        _opts.stats->ann_fall_back_brute_force_cnt += 1;
924
0
        return Status::OK();
925
0
    }
926
927
    // Track load index timing
928
0
    {
929
0
        SCOPED_TIMER(&(ann_index_stats.load_index_costs_ns));
930
0
        if (!ann_index_iterator_casted->try_load_index()) {
931
0
            VLOG_DEBUG << "Failed to load ANN index, fallback to brute force search";
932
0
            _need_read_data_indices[src_cid] = true;
933
0
            _opts.stats->ann_fall_back_brute_force_cnt += 1;
934
0
            return Status::OK();
935
0
        }
936
0
        double load_costs_ms =
937
0
                static_cast<double>(ann_index_stats.load_index_costs_ns.value()) / 1000000.0;
938
0
        DorisMetrics::instance()->ann_index_load_costs_ms->increment(
939
0
                static_cast<int64_t>(load_costs_ms));
940
0
    }
941
942
0
    RETURN_IF_ERROR(_ann_topn_runtime->evaluate_vector_ann_search(
943
0
            ann_index_iterator_casted, &_row_bitmap, rows_of_segment, result_column, result_row_ids,
944
0
            ann_index_stats));
945
946
0
    VLOG_DEBUG << fmt::format("Ann topn filtered {} - {} = {} rows", pre_size,
947
0
                              _row_bitmap.cardinality(), pre_size - _row_bitmap.cardinality());
948
949
0
    int64_t rows_filterd = pre_size - _row_bitmap.cardinality();
950
0
    _opts.stats->rows_ann_index_topn_filtered += rows_filterd;
951
0
    _opts.stats->ann_index_load_ns += ann_index_stats.load_index_costs_ns.value();
952
0
    _opts.stats->ann_topn_search_ns += ann_index_stats.search_costs_ns.value();
953
0
    _opts.stats->ann_index_topn_engine_search_ns += ann_index_stats.engine_search_ns.value();
954
0
    _opts.stats->ann_index_topn_result_process_ns +=
955
0
            ann_index_stats.result_process_costs_ns.value();
956
0
    _opts.stats->ann_index_topn_engine_convert_ns += ann_index_stats.engine_convert_ns.value();
957
0
    _opts.stats->ann_index_topn_engine_prepare_ns += ann_index_stats.engine_prepare_ns.value();
958
0
    _opts.stats->ann_index_topn_search_cnt += 1;
959
0
    const size_t dst_col_idx = _ann_topn_runtime->get_dest_column_idx();
960
0
    ColumnIterator* column_iter = _column_iterators[_schema->column_id(dst_col_idx)].get();
961
0
    DCHECK(column_iter != nullptr);
962
0
    VirtualColumnIterator* virtual_column_iter = dynamic_cast<VirtualColumnIterator*>(column_iter);
963
0
    DCHECK(virtual_column_iter != nullptr);
964
0
    VLOG_DEBUG << fmt::format(
965
0
            "Virtual column iterator, column_idx {}, is materialized with {} rows", dst_col_idx,
966
0
            result_row_ids->size());
967
    // reference count of result_column should be 1, so move will not issue any data copy.
968
0
    virtual_column_iter->prepare_materialization(std::move(result_column),
969
0
                                                 std::move(result_row_ids));
970
971
0
    _need_read_data_indices[src_cid] = false;
972
0
    VLOG_DEBUG << fmt::format(
973
0
            "Enable ANN index-only scan for src column cid {} (skip reading data pages)", src_cid);
974
975
0
    return Status::OK();
976
0
}
977
978
467
Status SegmentIterator::_get_row_ranges_from_conditions(RowRanges* condition_row_ranges) {
979
467
    std::set<int32_t> cids;
980
467
    for (auto& entry : _opts.col_id_to_predicates) {
981
0
        cids.insert(entry.first);
982
0
    }
983
984
467
    {
985
467
        SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_dict_ns);
986
        /// Low cardinality optimization is currently not very stable, so to prevent data corruption,
987
        /// we are temporarily disabling its use in data compaction.
988
        // TODO: enable it in not only ReaderTyper::READER_QUERY but also other reader types.
989
467
        if (_opts.io_ctx.reader_type == ReaderType::READER_QUERY) {
990
0
            RowRanges dict_row_ranges = RowRanges::create_single(num_rows());
991
0
            for (auto cid : cids) {
992
0
                if (!_segment->can_apply_predicate_safely(
993
0
                            cid, *_schema, _opts.target_cast_type_for_variants, _opts)) {
994
0
                    continue;
995
0
                }
996
0
                DCHECK(_opts.col_id_to_predicates.count(cid) > 0);
997
0
                RETURN_IF_ERROR(_column_iterators[cid]->get_row_ranges_by_dict(
998
0
                        _opts.col_id_to_predicates.at(cid).get(), &dict_row_ranges));
999
1000
0
                if (dict_row_ranges.is_empty()) {
1001
0
                    break;
1002
0
                }
1003
0
            }
1004
1005
0
            if (dict_row_ranges.is_empty()) {
1006
0
                RowRanges::ranges_intersection(*condition_row_ranges, dict_row_ranges,
1007
0
                                               condition_row_ranges);
1008
0
                _opts.stats->segment_dict_filtered++;
1009
0
                _opts.stats->filtered_segment_number++;
1010
0
                return Status::OK();
1011
0
            }
1012
0
        }
1013
467
    }
1014
1015
467
    size_t pre_size = 0;
1016
467
    {
1017
467
        SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_bf_ns);
1018
        // first filter data by bloom filter index
1019
        // bloom filter index only use CondColumn
1020
467
        RowRanges bf_row_ranges = RowRanges::create_single(num_rows());
1021
467
        for (auto& cid : cids) {
1022
0
            DCHECK(_opts.col_id_to_predicates.count(cid) > 0);
1023
0
            if (!_segment->can_apply_predicate_safely(cid, *_schema,
1024
0
                                                      _opts.target_cast_type_for_variants, _opts)) {
1025
0
                continue;
1026
0
            }
1027
            // get row ranges by bf index of this column,
1028
0
            RowRanges column_bf_row_ranges = RowRanges::create_single(num_rows());
1029
0
            RETURN_IF_ERROR(_column_iterators[cid]->get_row_ranges_by_bloom_filter(
1030
0
                    _opts.col_id_to_predicates.at(cid).get(), &column_bf_row_ranges));
1031
0
            RowRanges::ranges_intersection(bf_row_ranges, column_bf_row_ranges, &bf_row_ranges);
1032
0
        }
1033
1034
467
        pre_size = condition_row_ranges->count();
1035
467
        RowRanges::ranges_intersection(*condition_row_ranges, bf_row_ranges, condition_row_ranges);
1036
467
        _opts.stats->rows_bf_filtered += (pre_size - condition_row_ranges->count());
1037
467
    }
1038
1039
0
    {
1040
467
        SCOPED_RAW_TIMER(&_opts.stats->generate_row_ranges_by_zonemap_ns);
1041
467
        RowRanges zone_map_row_ranges = RowRanges::create_single(num_rows());
1042
        // second filter data by zone map
1043
467
        for (const auto& cid : cids) {
1044
0
            DCHECK(_opts.col_id_to_predicates.count(cid) > 0);
1045
0
            if (!_segment->can_apply_predicate_safely(cid, *_schema,
1046
0
                                                      _opts.target_cast_type_for_variants, _opts)) {
1047
0
                continue;
1048
0
            }
1049
            // do not check zonemap if predicate does not support zonemap
1050
0
            if (!_opts.col_id_to_predicates.at(cid)->support_zonemap()) {
1051
0
                VLOG_DEBUG << "skip zonemap for column " << cid;
1052
0
                continue;
1053
0
            }
1054
            // get row ranges by zone map of this column,
1055
0
            RowRanges column_row_ranges = RowRanges::create_single(num_rows());
1056
0
            RETURN_IF_ERROR(_column_iterators[cid]->get_row_ranges_by_zone_map(
1057
0
                    _opts.col_id_to_predicates.at(cid).get(),
1058
0
                    _opts.del_predicates_for_zone_map.count(cid) > 0
1059
0
                            ? &(_opts.del_predicates_for_zone_map.at(cid))
1060
0
                            : nullptr,
1061
0
                    &column_row_ranges));
1062
            // intersect different columns's row ranges to get final row ranges by zone map
1063
0
            RowRanges::ranges_intersection(zone_map_row_ranges, column_row_ranges,
1064
0
                                           &zone_map_row_ranges);
1065
0
        }
1066
1067
467
        pre_size = condition_row_ranges->count();
1068
467
        RowRanges::ranges_intersection(*condition_row_ranges, zone_map_row_ranges,
1069
467
                                       condition_row_ranges);
1070
1071
467
        size_t pre_size2 = condition_row_ranges->count();
1072
467
        RowRanges::ranges_intersection(*condition_row_ranges, zone_map_row_ranges,
1073
467
                                       condition_row_ranges);
1074
467
        _opts.stats->rows_stats_rp_filtered += (pre_size2 - condition_row_ranges->count());
1075
467
        _opts.stats->rows_stats_filtered += (pre_size - condition_row_ranges->count());
1076
467
    }
1077
1078
0
    return Status::OK();
1079
467
}
1080
1081
0
bool SegmentIterator::_is_literal_node(const TExprNodeType::type& node_type) {
1082
0
    switch (node_type) {
1083
0
    case TExprNodeType::BOOL_LITERAL:
1084
0
    case TExprNodeType::INT_LITERAL:
1085
0
    case TExprNodeType::LARGE_INT_LITERAL:
1086
0
    case TExprNodeType::FLOAT_LITERAL:
1087
0
    case TExprNodeType::DECIMAL_LITERAL:
1088
0
    case TExprNodeType::STRING_LITERAL:
1089
0
    case TExprNodeType::DATE_LITERAL:
1090
0
    case TExprNodeType::TIMEV2_LITERAL:
1091
0
        return true;
1092
0
    default:
1093
0
        return false;
1094
0
    }
1095
0
}
1096
1097
0
Status SegmentIterator::_extract_common_expr_columns(const VExprSPtr& expr) {
1098
0
    auto& children = expr->children();
1099
0
    for (int i = 0; i < children.size(); ++i) {
1100
0
        RETURN_IF_ERROR(_extract_common_expr_columns(children[i]));
1101
0
    }
1102
1103
0
    auto node_type = expr->node_type();
1104
0
    if (node_type == TExprNodeType::SLOT_REF) {
1105
0
        auto slot_expr = std::dynamic_pointer_cast<doris::VSlotRef>(expr);
1106
0
        _is_common_expr_column[_schema->column_id(slot_expr->column_id())] = true;
1107
0
        _common_expr_columns.insert(_schema->column_id(slot_expr->column_id()));
1108
0
    } else if (node_type == TExprNodeType::VIRTUAL_SLOT_REF) {
1109
0
        std::shared_ptr<VirtualSlotRef> virtual_slot_ref =
1110
0
                std::dynamic_pointer_cast<VirtualSlotRef>(expr);
1111
0
        RETURN_IF_ERROR(_extract_common_expr_columns(virtual_slot_ref->get_virtual_column_expr()));
1112
0
    }
1113
1114
0
    return Status::OK();
1115
0
}
1116
1117
0
bool SegmentIterator::_check_apply_by_inverted_index(std::shared_ptr<ColumnPredicate> pred) {
1118
0
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_inverted_index_query) {
1119
0
        return false;
1120
0
    }
1121
0
    auto pred_column_id = pred->column_id();
1122
0
    if (_index_iterators[pred_column_id] == nullptr) {
1123
        //this column without inverted index
1124
0
        return false;
1125
0
    }
1126
1127
0
    if (_inverted_index_not_support_pred_type(pred->type())) {
1128
0
        return false;
1129
0
    }
1130
1131
0
    if (pred->type() == PredicateType::IN_LIST || pred->type() == PredicateType::NOT_IN_LIST) {
1132
        // in_list or not_in_list predicate produced by runtime filter
1133
0
        if (pred->is_runtime_filter()) {
1134
0
            return false;
1135
0
        }
1136
0
    }
1137
1138
    // UNTOKENIZED strings exceed ignore_above, they are written as null, causing range query errors
1139
0
    if (PredicateTypeTraits::is_range(pred->type()) &&
1140
0
        !IndexReaderHelper::has_bkd_index(_index_iterators[pred_column_id].get())) {
1141
0
        return false;
1142
0
    }
1143
1144
    // Function filter no apply inverted index
1145
0
    if (dynamic_cast<LikeColumnPredicate<TYPE_CHAR>*>(pred.get()) != nullptr ||
1146
0
        dynamic_cast<LikeColumnPredicate<TYPE_STRING>*>(pred.get()) != nullptr) {
1147
0
        return false;
1148
0
    }
1149
1150
0
    bool handle_by_fulltext = _column_has_fulltext_index(pred_column_id);
1151
0
    if (handle_by_fulltext) {
1152
        // when predicate is leafNode of andNode,
1153
        // can apply 'match query' and 'equal query' and 'list query' for fulltext index.
1154
0
        return pred->type() == PredicateType::MATCH || pred->type() == PredicateType::IS_NULL ||
1155
0
               pred->type() == PredicateType::IS_NOT_NULL ||
1156
0
               PredicateTypeTraits::is_equal_or_list(pred->type());
1157
0
    }
1158
1159
0
    return true;
1160
0
}
1161
1162
// TODO: optimization when all expr can not evaluate by inverted/ann index,
1163
0
Status SegmentIterator::_apply_index_expr() {
1164
0
    for (const auto& expr_ctx : _common_expr_ctxs_push_down) {
1165
0
        if (Status st = expr_ctx->evaluate_inverted_index(num_rows()); !st.ok()) {
1166
0
            if (_downgrade_without_index(st) || st.code() == ErrorCode::NOT_IMPLEMENTED_ERROR) {
1167
0
                continue;
1168
0
            } else {
1169
                // other code is not to be handled, we should just break
1170
0
                LOG(WARNING) << "failed to evaluate inverted index for expr_ctx: "
1171
0
                             << expr_ctx->root()->debug_string()
1172
0
                             << ", error msg: " << st.to_string();
1173
0
                return st;
1174
0
            }
1175
0
        }
1176
0
    }
1177
1178
    // Evaluate inverted index for virtual column MATCH expressions (projections).
1179
    // Unlike common exprs which filter rows, these only compute index result bitmaps
1180
    // for later materialization via fast_execute().
1181
0
    for (auto& [cid, expr_ctx] : _virtual_column_exprs) {
1182
0
        if (expr_ctx->get_index_context() == nullptr) {
1183
0
            continue;
1184
0
        }
1185
0
        if (Status st = expr_ctx->evaluate_inverted_index(num_rows()); !st.ok()) {
1186
0
            if (_downgrade_without_index(st) || st.code() == ErrorCode::NOT_IMPLEMENTED_ERROR) {
1187
0
                continue;
1188
0
            } else {
1189
0
                LOG(WARNING) << "failed to evaluate inverted index for virtual column expr: "
1190
0
                             << expr_ctx->root()->debug_string()
1191
0
                             << ", error msg: " << st.to_string();
1192
0
                return st;
1193
0
            }
1194
0
        }
1195
0
    }
1196
1197
    // Apply ann range search
1198
0
    for (const auto& expr_ctx : _common_expr_ctxs_push_down) {
1199
0
        segment_v2::AnnIndexStats ann_index_stats;
1200
0
        size_t origin_rows = _row_bitmap.cardinality();
1201
0
        RETURN_IF_ERROR(expr_ctx->evaluate_ann_range_search(
1202
0
                _index_iterators, _schema->column_ids(), _column_iterators,
1203
0
                _common_expr_to_slotref_map, _row_bitmap, ann_index_stats));
1204
0
        _opts.stats->rows_ann_index_range_filtered += (origin_rows - _row_bitmap.cardinality());
1205
0
        _opts.stats->ann_index_load_ns += ann_index_stats.load_index_costs_ns.value();
1206
0
        _opts.stats->ann_index_range_search_ns += ann_index_stats.search_costs_ns.value();
1207
0
        _opts.stats->ann_range_engine_search_ns += ann_index_stats.engine_search_ns.value();
1208
0
        _opts.stats->ann_range_result_convert_ns += ann_index_stats.result_process_costs_ns.value();
1209
0
        _opts.stats->ann_range_engine_convert_ns += ann_index_stats.engine_convert_ns.value();
1210
0
        _opts.stats->ann_range_pre_process_ns += ann_index_stats.engine_prepare_ns.value();
1211
0
        _opts.stats->ann_fall_back_brute_force_cnt += ann_index_stats.fall_back_brute_force_cnt;
1212
0
    }
1213
1214
0
    for (auto it = _common_expr_ctxs_push_down.begin(); it != _common_expr_ctxs_push_down.end();) {
1215
0
        if ((*it)->root()->ann_range_search_executedd()) {
1216
0
            _opts.stats->ann_index_range_search_cnt++;
1217
0
            it = _common_expr_ctxs_push_down.erase(it);
1218
0
        } else {
1219
0
            ++it;
1220
0
        }
1221
0
    }
1222
    // TODO:Do we need to remove these expr root from _remaining_conjunct_roots?
1223
1224
0
    return Status::OK();
1225
0
}
1226
1227
0
bool SegmentIterator::_downgrade_without_index(Status res, bool need_remaining) {
1228
0
    bool is_fallback =
1229
0
            _opts.runtime_state->query_options().enable_fallback_on_missing_inverted_index;
1230
0
    if ((res.code() == ErrorCode::INVERTED_INDEX_FILE_NOT_FOUND && is_fallback) ||
1231
0
        res.code() == ErrorCode::INVERTED_INDEX_BYPASS ||
1232
0
        res.code() == ErrorCode::INVERTED_INDEX_EVALUATE_SKIPPED ||
1233
0
        (res.code() == ErrorCode::INVERTED_INDEX_NO_TERMS && need_remaining) ||
1234
0
        res.code() == ErrorCode::INVERTED_INDEX_FILE_CORRUPTED) {
1235
        // 1. INVERTED_INDEX_FILE_NOT_FOUND means index file has not been built,
1236
        //    usually occurs when creating a new index, queries can be downgraded
1237
        //    without index.
1238
        // 2. INVERTED_INDEX_BYPASS means the hit of condition by index
1239
        //    has reached the optimal limit, downgrade without index query can
1240
        //    improve query performance.
1241
        // 3. INVERTED_INDEX_EVALUATE_SKIPPED means the inverted index is not
1242
        //    suitable for executing this predicate, skipped it and filter data
1243
        //    by function later.
1244
        // 4. INVERTED_INDEX_NO_TERMS means the column has fulltext index,
1245
        //    but the column condition value no terms in specified parser,
1246
        //    such as: where A = '' and B = ','
1247
        //    the predicate of A and B need downgrade without index query.
1248
        // 5. INVERTED_INDEX_FILE_CORRUPTED means the index file is corrupted,
1249
        //    such as when index segment files are not generated
1250
        // above case can downgrade without index query
1251
0
        _opts.stats->inverted_index_downgrade_count++;
1252
0
        if (!res.is<ErrorCode::INVERTED_INDEX_BYPASS>()) {
1253
0
            LOG(INFO) << "will downgrade without index to evaluate predicate, because of res: "
1254
0
                      << res;
1255
0
        } else {
1256
0
            VLOG_DEBUG << "will downgrade without index to evaluate predicate, because of res: "
1257
0
                       << res;
1258
0
        }
1259
0
        return true;
1260
0
    }
1261
0
    return false;
1262
0
}
1263
1264
0
bool SegmentIterator::_column_has_fulltext_index(int32_t cid) {
1265
0
    bool has_fulltext_index =
1266
0
            _index_iterators[cid] != nullptr &&
1267
0
            _index_iterators[cid]->get_reader(InvertedIndexReaderType::FULLTEXT) &&
1268
0
            _index_iterators[cid]->get_reader(InvertedIndexReaderType::STRING_TYPE) == nullptr;
1269
1270
0
    return has_fulltext_index;
1271
0
}
1272
1273
0
inline bool SegmentIterator::_inverted_index_not_support_pred_type(const PredicateType& type) {
1274
0
    return type == PredicateType::BF || type == PredicateType::BITMAP_FILTER;
1275
0
}
1276
1277
Status SegmentIterator::_apply_inverted_index_on_column_predicate(
1278
        std::shared_ptr<ColumnPredicate> pred,
1279
0
        std::vector<std::shared_ptr<ColumnPredicate>>& remaining_predicates, bool* continue_apply) {
1280
0
    if (!_check_apply_by_inverted_index(pred)) {
1281
0
        remaining_predicates.emplace_back(pred);
1282
0
    } else {
1283
0
        bool need_remaining_after_evaluate = _column_has_fulltext_index(pred->column_id()) &&
1284
0
                                             PredicateTypeTraits::is_equal_or_list(pred->type());
1285
0
        Status res =
1286
0
                pred->evaluate(_storage_name_and_type[pred->column_id()],
1287
0
                               _index_iterators[pred->column_id()].get(), num_rows(), &_row_bitmap);
1288
0
        if (!res.ok()) {
1289
0
            if (_downgrade_without_index(res, need_remaining_after_evaluate)) {
1290
0
                remaining_predicates.emplace_back(pred);
1291
0
                return Status::OK();
1292
0
            }
1293
0
            LOG(WARNING) << "failed to evaluate index"
1294
0
                         << ", column predicate type: " << pred->pred_type_string(pred->type())
1295
0
                         << ", error msg: " << res;
1296
0
            return res;
1297
0
        }
1298
1299
0
        if (_row_bitmap.isEmpty()) {
1300
            // all rows have been pruned, no need to process further predicates
1301
0
            *continue_apply = false;
1302
0
        }
1303
1304
0
        if (need_remaining_after_evaluate) {
1305
0
            remaining_predicates.emplace_back(pred);
1306
0
            return Status::OK();
1307
0
        }
1308
0
        if (!pred->is_runtime_filter()) {
1309
0
            _column_predicate_index_exec_status[pred->column_id()][pred] = true;
1310
0
        }
1311
0
    }
1312
0
    return Status::OK();
1313
0
}
1314
1315
43.4k
bool SegmentIterator::_need_read_data(ColumnId cid) {
1316
43.4k
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_no_need_read_data_opt) {
1317
0
        return true;
1318
0
    }
1319
    // only support DUP_KEYS and UNIQUE_KEYS with MOW
1320
43.4k
    if (!((_opts.tablet_schema->keys_type() == KeysType::DUP_KEYS ||
1321
43.4k
           (_opts.tablet_schema->keys_type() == KeysType::UNIQUE_KEYS &&
1322
16.3k
            _opts.enable_unique_key_merge_on_write)))) {
1323
12.0k
        return true;
1324
12.0k
    }
1325
    // this is a virtual column, we always need to read data
1326
31.3k
    if (this->_vir_cid_to_idx_in_block.contains(cid)) {
1327
0
        return true;
1328
0
    }
1329
1330
    // if there is a delete predicate, we always need to read data
1331
31.3k
    if (_has_delete_predicate(cid)) {
1332
4.03k
        return true;
1333
4.03k
    }
1334
27.2k
    if (_output_columns.count(-1)) {
1335
        // if _output_columns contains -1, it means that the light
1336
        // weight schema change may not be enabled or other reasons
1337
        // caused the column unique_id not be set, to prevent errors
1338
        // occurring, return true here that column data needs to be read
1339
0
        return true;
1340
0
    }
1341
    // Check the following conditions:
1342
    // 1. If the column represented by the unique ID is an inverted index column (indicated by '_need_read_data_indices.count(unique_id) > 0 && !_need_read_data_indices[unique_id]')
1343
    //    and it's not marked for projection in '_output_columns'.
1344
    // 2. Or, if the column is an inverted index column and it's marked for projection in '_output_columns',
1345
    //    and the operation is a push down of the 'COUNT_ON_INDEX' aggregation function.
1346
    // If any of the above conditions are met, log a debug message indicating that there's no need to read data for the indexed column.
1347
    // Then, return false.
1348
27.2k
    const auto& column = _opts.tablet_schema->column(cid);
1349
    // Different subcolumns may share the same parent_unique_id, so we choose to abandon this optimization.
1350
27.2k
    if (column.is_extracted_column() &&
1351
27.2k
        _opts.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
1352
1
        return true;
1353
1
    }
1354
27.2k
    int32_t unique_id = column.unique_id();
1355
27.2k
    if (unique_id < 0) {
1356
1
        unique_id = column.parent_unique_id();
1357
1
    }
1358
27.2k
    if ((_need_read_data_indices.contains(cid) && !_need_read_data_indices[cid] &&
1359
27.2k
         !_output_columns.contains(unique_id)) ||
1360
27.2k
        (_need_read_data_indices.contains(cid) && !_need_read_data_indices[cid] &&
1361
27.2k
         _output_columns.count(unique_id) == 1 &&
1362
27.2k
         _opts.push_down_agg_type_opt == TPushAggOp::COUNT_ON_INDEX)) {
1363
1
        VLOG_DEBUG << "SegmentIterator no need read data for column: "
1364
0
                   << _opts.tablet_schema->column_by_uid(unique_id).name();
1365
1
        return false;
1366
1
    }
1367
27.2k
    return true;
1368
27.2k
}
1369
1370
0
Status SegmentIterator::_apply_inverted_index() {
1371
0
    std::vector<std::shared_ptr<ColumnPredicate>> remaining_predicates;
1372
0
    std::set<std::shared_ptr<ColumnPredicate>> no_need_to_pass_column_predicate_set;
1373
1374
0
    for (auto pred : _col_predicates) {
1375
0
        if (no_need_to_pass_column_predicate_set.count(pred) > 0) {
1376
0
            continue;
1377
0
        } else {
1378
0
            bool continue_apply = true;
1379
0
            RETURN_IF_ERROR(_apply_inverted_index_on_column_predicate(pred, remaining_predicates,
1380
0
                                                                      &continue_apply));
1381
0
            if (!continue_apply) {
1382
0
                break;
1383
0
            }
1384
0
        }
1385
0
    }
1386
1387
0
    _col_predicates = std::move(remaining_predicates);
1388
0
    return Status::OK();
1389
0
}
1390
1391
/**
1392
 * @brief Checks if all conditions related to a specific column have passed in both
1393
 * `_column_predicate_inverted_index_status` and `_common_expr_inverted_index_status`.
1394
 *
1395
 * This function first checks the conditions in `_column_predicate_inverted_index_status`
1396
 * for the given `ColumnId`. If all conditions pass, it sets `default_return` to `true`.
1397
 * It then checks the conditions in `_common_expr_inverted_index_status` for the same column.
1398
 *
1399
 * The function returns `true` if all conditions in both maps pass. If any condition fails
1400
 * in either map, the function immediately returns `false`. If the column does not exist
1401
 * in one of the maps, the function returns `default_return`.
1402
 *
1403
 * @param cid The ColumnId of the column to check.
1404
 * @param default_return The default value to return if the column is not found in the status maps.
1405
 * @return true if all conditions in both status maps pass, or if the column is not found
1406
 *         and `default_return` is true.
1407
 * @return false if any condition in either status map fails, or if the column is not found
1408
 *         and `default_return` is false.
1409
 */
1410
bool SegmentIterator::_check_all_conditions_passed_inverted_index_for_column(ColumnId cid,
1411
0
                                                                             bool default_return) {
1412
    // If common_expr_pushdown is disabled, we cannot guarantee that all conditions are processed by the inverted index.
1413
    // Consider a scenario where there is a column predicate and an expression involving the same column in the SQL query,
1414
    // such as 'a < 0' and 'abs(a) > 1'. This could potentially lead to errors.
1415
0
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_common_expr_pushdown) {
1416
0
        return false;
1417
0
    }
1418
0
    auto pred_it = _column_predicate_index_exec_status.find(cid);
1419
0
    if (pred_it != _column_predicate_index_exec_status.end()) {
1420
0
        const auto& pred_map = pred_it->second;
1421
0
        bool pred_passed = std::all_of(pred_map.begin(), pred_map.end(),
1422
0
                                       [](const auto& pred_entry) { return pred_entry.second; });
1423
0
        if (!pred_passed) {
1424
0
            return false;
1425
0
        } else {
1426
0
            default_return = true;
1427
0
        }
1428
0
    }
1429
1430
0
    auto expr_it = _common_expr_index_exec_status.find(cid);
1431
0
    if (expr_it != _common_expr_index_exec_status.end()) {
1432
0
        const auto& expr_map = expr_it->second;
1433
0
        return std::all_of(expr_map.begin(), expr_map.end(),
1434
0
                           [](const auto& expr_entry) { return expr_entry.second; });
1435
0
    }
1436
0
    return default_return;
1437
0
}
1438
1439
5.63k
Status SegmentIterator::_init_return_column_iterators() {
1440
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_return_column_iterators_timer_ns);
1441
5.63k
    if (_cur_rowid >= num_rows()) {
1442
0
        return Status::OK();
1443
0
    }
1444
1445
12.6k
    for (auto cid : _schema->column_ids()) {
1446
12.6k
        if (_schema->column(cid)->name() == BeConsts::ROWID_COL) {
1447
0
            _column_iterators[cid].reset(
1448
0
                    new RowIdColumnIterator(_opts.tablet_id, _opts.rowset_id, _segment->id()));
1449
0
            continue;
1450
0
        }
1451
1452
12.6k
        if (_schema->column(cid)->name().starts_with(BeConsts::GLOBAL_ROWID_COL)) {
1453
0
            auto& id_file_map = _opts.runtime_state->get_id_file_map();
1454
0
            uint32_t file_id = id_file_map->get_file_mapping_id(std::make_shared<FileMapping>(
1455
0
                    _opts.tablet_id, _opts.rowset_id, _segment->id()));
1456
0
            _column_iterators[cid].reset(new RowIdColumnIteratorV2(
1457
0
                    IdManager::ID_VERSION, BackendOptions::get_backend_id(), file_id));
1458
0
            continue;
1459
0
        }
1460
1461
12.6k
        if (_schema->column(cid)->name().starts_with(BeConsts::VIRTUAL_COLUMN_PREFIX)) {
1462
0
            _column_iterators[cid] = std::make_unique<VirtualColumnIterator>();
1463
0
            continue;
1464
0
        }
1465
1466
12.6k
        std::set<ColumnId> del_cond_id_set;
1467
12.6k
        _opts.delete_condition_predicates->get_all_column_ids(del_cond_id_set);
1468
12.6k
        std::vector<bool> tmp_is_pred_column;
1469
12.6k
        tmp_is_pred_column.resize(_schema->columns().size(), false);
1470
12.6k
        for (auto predicate : _col_predicates) {
1471
0
            auto p_cid = predicate->column_id();
1472
0
            tmp_is_pred_column[p_cid] = true;
1473
0
        }
1474
        // handle delete_condition
1475
12.6k
        for (auto d_cid : del_cond_id_set) {
1476
1.32k
            tmp_is_pred_column[d_cid] = true;
1477
1.32k
        }
1478
1479
12.6k
        if (_column_iterators[cid] == nullptr) {
1480
12.6k
            RETURN_IF_ERROR(_segment->new_column_iterator(_opts.tablet_schema->column(cid),
1481
12.6k
                                                          &_column_iterators[cid], &_opts,
1482
12.6k
                                                          &_variant_sparse_column_cache));
1483
12.6k
            ColumnIteratorOptions iter_opts {
1484
12.6k
                    .use_page_cache = _opts.use_page_cache,
1485
                    // If the col is predicate column, then should read the last page to check
1486
                    // if the column is full dict encoding
1487
12.6k
                    .is_predicate_column = tmp_is_pred_column[cid],
1488
12.6k
                    .file_reader = _file_reader.get(),
1489
12.6k
                    .stats = _opts.stats,
1490
12.6k
                    .io_ctx = _opts.io_ctx,
1491
12.6k
            };
1492
12.6k
            RETURN_IF_ERROR(_column_iterators[cid]->init(iter_opts));
1493
12.6k
        }
1494
12.6k
    }
1495
1496
5.63k
#ifndef NDEBUG
1497
5.63k
    for (auto pair : _vir_cid_to_idx_in_block) {
1498
0
        ColumnId vir_col_cid = pair.first;
1499
0
        DCHECK(_column_iterators[vir_col_cid] != nullptr)
1500
0
                << "Virtual column iterator for " << vir_col_cid << " should not be null";
1501
0
        ColumnIterator* column_iter = _column_iterators[vir_col_cid].get();
1502
0
        DCHECK(dynamic_cast<VirtualColumnIterator*>(column_iter) != nullptr)
1503
0
                << "Virtual column iterator for " << vir_col_cid
1504
0
                << " should be VirtualColumnIterator";
1505
0
    }
1506
5.63k
#endif
1507
5.63k
    return Status::OK();
1508
5.63k
}
1509
1510
5.63k
Status SegmentIterator::_init_index_iterators() {
1511
5.63k
    SCOPED_RAW_TIMER(&_opts.stats->segment_iterator_init_index_iterators_timer_ns);
1512
5.63k
    if (_cur_rowid >= num_rows()) {
1513
0
        return Status::OK();
1514
0
    }
1515
1516
5.63k
    _index_query_context = std::make_shared<IndexQueryContext>();
1517
5.63k
    _index_query_context->io_ctx = &_opts.io_ctx;
1518
5.63k
    _index_query_context->stats = _opts.stats;
1519
5.63k
    _index_query_context->runtime_state = _opts.runtime_state;
1520
1521
5.63k
    if (_score_runtime) {
1522
0
        _index_query_context->collection_statistics = _opts.collection_statistics;
1523
0
        _index_query_context->collection_similarity = std::make_shared<CollectionSimilarity>();
1524
0
        _index_query_context->query_limit = _score_runtime->get_limit();
1525
0
        _index_query_context->is_asc = _score_runtime->is_asc();
1526
0
    }
1527
1528
    // Inverted index iterators
1529
12.6k
    for (auto cid : _schema->column_ids()) {
1530
        // Use segment’s own index_meta, for compatibility with future indexing needs to default to lowercase.
1531
12.6k
        if (_index_iterators[cid] == nullptr) {
1532
            // In the _opts.tablet_schema, the sub-column type information for the variant is FieldType::OLAP_FIELD_TYPE_VARIANT.
1533
            // This is because the sub-column is created in create_materialized_variant_column.
1534
            // We use this column to locate the metadata for the inverted index, which requires a unique_id and path.
1535
12.6k
            const auto& column = _opts.tablet_schema->column(cid);
1536
12.6k
            std::vector<const TabletIndex*> inverted_indexs;
1537
            // Keep shared_ptr alive to prevent use-after-free when accessing raw pointers
1538
12.6k
            TabletIndexes inverted_indexs_holder;
1539
            // If the column is an extracted column, we need to find the sub-column in the parent column reader.
1540
12.6k
            std::shared_ptr<ColumnReader> column_reader;
1541
12.6k
            if (column.is_extracted_column()) {
1542
0
                if (!_segment->_column_reader_cache->get_column_reader(
1543
0
                            column.parent_unique_id(), &column_reader, _opts.stats) ||
1544
0
                    column_reader == nullptr) {
1545
0
                    continue;
1546
0
                }
1547
0
                auto* variant_reader = assert_cast<VariantColumnReader*>(column_reader.get());
1548
0
                DataTypePtr data_type = _storage_name_and_type[cid].second;
1549
0
                if (data_type != nullptr &&
1550
0
                    data_type->get_primitive_type() == PrimitiveType::TYPE_VARIANT) {
1551
0
                    DataTypePtr inferred_type;
1552
0
                    Status st = variant_reader->infer_data_type_for_path(
1553
0
                            &inferred_type, column, _opts, _segment->_column_reader_cache.get());
1554
0
                    if (st.ok() && inferred_type != nullptr) {
1555
0
                        data_type = inferred_type;
1556
0
                    }
1557
0
                }
1558
0
                inverted_indexs_holder =
1559
0
                        variant_reader->find_subcolumn_tablet_indexes(column, data_type);
1560
                // Extract raw pointers from shared_ptr for iteration
1561
0
                for (const auto& index_ptr : inverted_indexs_holder) {
1562
0
                    inverted_indexs.push_back(index_ptr.get());
1563
0
                }
1564
0
            }
1565
            // If the column is not an extracted column, we can directly get the inverted index metadata from the tablet schema.
1566
12.6k
            else {
1567
12.6k
                inverted_indexs = _segment->_tablet_schema->inverted_indexs(column);
1568
12.6k
            }
1569
12.6k
            for (const auto& inverted_index : inverted_indexs) {
1570
2.56k
                RETURN_IF_ERROR(_segment->new_index_iterator(column, inverted_index, _opts,
1571
2.56k
                                                             &_index_iterators[cid]));
1572
2.56k
            }
1573
12.6k
            if (_index_iterators[cid] != nullptr) {
1574
2.55k
                _index_iterators[cid]->set_context(_index_query_context);
1575
2.55k
            }
1576
12.6k
        }
1577
12.6k
    }
1578
1579
    // Ann index iterators
1580
12.6k
    for (auto cid : _schema->column_ids()) {
1581
12.6k
        if (_index_iterators[cid] == nullptr) {
1582
10.1k
            const auto& column = _opts.tablet_schema->column(cid);
1583
10.1k
            const auto* index_meta = _segment->_tablet_schema->ann_index(column);
1584
10.1k
            if (index_meta) {
1585
1
                RETURN_IF_ERROR(_segment->new_index_iterator(column, index_meta, _opts,
1586
1
                                                             &_index_iterators[cid]));
1587
1588
1
                if (_index_iterators[cid] != nullptr) {
1589
1
                    _index_iterators[cid]->set_context(_index_query_context);
1590
1
                }
1591
1
            }
1592
10.1k
        }
1593
12.6k
    }
1594
1595
5.63k
    return Status::OK();
1596
5.63k
}
1597
1598
Status SegmentIterator::_lookup_ordinal(const RowCursor& key, bool is_include, rowid_t upper_bound,
1599
0
                                        rowid_t* rowid) {
1600
0
    if (_segment->_tablet_schema->keys_type() == UNIQUE_KEYS &&
1601
0
        _segment->get_primary_key_index() != nullptr) {
1602
0
        return _lookup_ordinal_from_pk_index(key, is_include, rowid);
1603
0
    }
1604
0
    return _lookup_ordinal_from_sk_index(key, is_include, upper_bound, rowid);
1605
0
}
1606
1607
// look up one key to get its ordinal at which can get data by using short key index.
1608
// 'upper_bound' is defined the max ordinal the function will search.
1609
// We use upper_bound to reduce search times.
1610
// If we find a valid ordinal, it will be set in rowid and with Status::OK()
1611
// If we can not find a valid key in this segment, we will set rowid to upper_bound
1612
// Otherwise return error.
1613
// 1. get [start, end) ordinal through short key index
1614
// 2. binary search to find exact ordinal that match the input condition
1615
// Make is_include template to reduce branch
1616
Status SegmentIterator::_lookup_ordinal_from_sk_index(const RowCursor& key, bool is_include,
1617
0
                                                      rowid_t upper_bound, rowid_t* rowid) {
1618
0
    const ShortKeyIndexDecoder* sk_index_decoder = _segment->get_short_key_index();
1619
0
    DCHECK(sk_index_decoder != nullptr);
1620
1621
0
    std::string index_key;
1622
0
    key.encode_key_with_padding(&index_key, _segment->_tablet_schema->num_short_key_columns(),
1623
0
                                is_include);
1624
1625
0
    const auto& key_col_ids = key.schema()->column_ids();
1626
0
    _convert_rowcursor_to_short_key(key, key_col_ids.size());
1627
1628
0
    ssize_t start_block_id = 0;
1629
0
    auto start_iter = sk_index_decoder->lower_bound(index_key);
1630
0
    if (start_iter.valid()) {
1631
        // Because previous block may contain this key, so we should set rowid to
1632
        // last block's first row.
1633
0
        start_block_id = start_iter.ordinal();
1634
0
        if (start_block_id > 0) {
1635
0
            start_block_id--;
1636
0
        }
1637
0
    } else {
1638
        // When we don't find a valid index item, which means all short key is
1639
        // smaller than input key, this means that this key may exist in the last
1640
        // row block. so we set the rowid to first row of last row block.
1641
0
        start_block_id = sk_index_decoder->num_items() - 1;
1642
0
    }
1643
0
    rowid_t start = cast_set<rowid_t>(start_block_id) * sk_index_decoder->num_rows_per_block();
1644
1645
0
    rowid_t end = upper_bound;
1646
0
    auto end_iter = sk_index_decoder->upper_bound(index_key);
1647
0
    if (end_iter.valid()) {
1648
0
        end = cast_set<rowid_t>(end_iter.ordinal()) * sk_index_decoder->num_rows_per_block();
1649
0
    }
1650
1651
    // binary search to find the exact key
1652
0
    while (start < end) {
1653
0
        rowid_t mid = (start + end) / 2;
1654
0
        RETURN_IF_ERROR(_seek_and_peek(mid));
1655
0
        int cmp = _compare_short_key_with_seek_block(key_col_ids);
1656
0
        if (cmp > 0) {
1657
0
            start = mid + 1;
1658
0
        } else if (cmp == 0) {
1659
0
            if (is_include) {
1660
                // lower bound
1661
0
                end = mid;
1662
0
            } else {
1663
                // upper bound
1664
0
                start = mid + 1;
1665
0
            }
1666
0
        } else {
1667
0
            end = mid;
1668
0
        }
1669
0
    }
1670
1671
0
    *rowid = start;
1672
0
    return Status::OK();
1673
0
}
1674
1675
Status SegmentIterator::_lookup_ordinal_from_pk_index(const RowCursor& key, bool is_include,
1676
0
                                                      rowid_t* rowid) {
1677
0
    DCHECK(_segment->_tablet_schema->keys_type() == UNIQUE_KEYS);
1678
0
    const PrimaryKeyIndexReader* pk_index_reader = _segment->get_primary_key_index();
1679
0
    DCHECK(pk_index_reader != nullptr);
1680
1681
0
    std::string index_key;
1682
0
    key.encode_key_with_padding<true>(&index_key, _segment->_tablet_schema->num_key_columns(),
1683
0
                                      is_include);
1684
0
    if (index_key < _segment->min_key()) {
1685
0
        *rowid = 0;
1686
0
        return Status::OK();
1687
0
    } else if (index_key > _segment->max_key()) {
1688
0
        *rowid = num_rows();
1689
0
        return Status::OK();
1690
0
    }
1691
0
    bool exact_match = false;
1692
1693
0
    std::unique_ptr<segment_v2::IndexedColumnIterator> index_iterator;
1694
0
    RETURN_IF_ERROR(pk_index_reader->new_iterator(&index_iterator, _opts.stats));
1695
1696
0
    Status status = index_iterator->seek_at_or_after(&index_key, &exact_match);
1697
0
    if (UNLIKELY(!status.ok())) {
1698
0
        *rowid = num_rows();
1699
0
        if (status.is<ENTRY_NOT_FOUND>()) {
1700
0
            return Status::OK();
1701
0
        }
1702
0
        return status;
1703
0
    }
1704
0
    *rowid = cast_set<rowid_t>(index_iterator->get_current_ordinal());
1705
1706
    // The sequence column needs to be removed from primary key index when comparing key
1707
0
    bool has_seq_col = _segment->_tablet_schema->has_sequence_col();
1708
    // Used to get key range from primary key index,
1709
    // for mow with cluster key table, we should get key range from short key index.
1710
0
    DCHECK(_segment->_tablet_schema->cluster_key_uids().empty());
1711
1712
    // if full key is exact_match, the primary key without sequence column should also the same
1713
0
    if (has_seq_col && !exact_match) {
1714
0
        size_t seq_col_length =
1715
0
                _segment->_tablet_schema->column(_segment->_tablet_schema->sequence_col_idx())
1716
0
                        .length() +
1717
0
                1;
1718
0
        auto index_type = DataTypeFactory::instance().create_data_type(
1719
0
                _segment->_pk_index_reader->type_info()->type(), 1, 0);
1720
0
        auto index_column = index_type->create_column();
1721
0
        size_t num_to_read = 1;
1722
0
        size_t num_read = num_to_read;
1723
0
        RETURN_IF_ERROR(index_iterator->next_batch(&num_read, index_column));
1724
0
        DCHECK(num_to_read == num_read);
1725
1726
0
        Slice sought_key =
1727
0
                Slice(index_column->get_data_at(0).data, index_column->get_data_at(0).size);
1728
0
        Slice sought_key_without_seq =
1729
0
                Slice(sought_key.get_data(), sought_key.get_size() - seq_col_length);
1730
1731
        // compare key
1732
0
        if (Slice(index_key).compare(sought_key_without_seq) == 0) {
1733
0
            exact_match = true;
1734
0
        }
1735
0
    }
1736
1737
    // find the key in primary key index, and the is_include is false, so move
1738
    // to the next row.
1739
0
    if (exact_match && !is_include) {
1740
0
        *rowid += 1;
1741
0
    }
1742
0
    return Status::OK();
1743
0
}
1744
1745
// seek to the row and load that row to _key_cursor
1746
0
Status SegmentIterator::_seek_and_peek(rowid_t rowid) {
1747
0
    {
1748
0
        _opts.stats->block_init_seek_num += 1;
1749
0
        SCOPED_RAW_TIMER(&_opts.stats->block_init_seek_ns);
1750
0
        RETURN_IF_ERROR(_seek_columns(_seek_schema->column_ids(), rowid));
1751
0
    }
1752
0
    size_t num_rows = 1;
1753
1754
    //note(wb) reset _seek_block for memory reuse
1755
    // it is easier to use row based memory layout for clear memory
1756
0
    for (int i = 0; i < _seek_block.size(); i++) {
1757
0
        _seek_block[i]->clear();
1758
0
    }
1759
0
    RETURN_IF_ERROR(_read_columns(_seek_schema->column_ids(), _seek_block, num_rows));
1760
0
    return Status::OK();
1761
0
}
1762
1763
0
Status SegmentIterator::_seek_columns(const std::vector<ColumnId>& column_ids, rowid_t pos) {
1764
0
    for (auto cid : column_ids) {
1765
0
        if (!_need_read_data(cid)) {
1766
0
            continue;
1767
0
        }
1768
0
        RETURN_IF_ERROR(_column_iterators[cid]->seek_to_ordinal(pos));
1769
0
    }
1770
0
    return Status::OK();
1771
0
}
1772
1773
/* ---------------------- for vectorization implementation  ---------------------- */
1774
1775
/**
1776
 *  For storage layer data type, can be measured from two perspectives:
1777
 *  1 Whether the type can be read in a fast way(batch read using SIMD)
1778
 *    Such as integer type and float type, this type can be read in SIMD way.
1779
 *    For the type string/bitmap/hll, they can not be read in batch way, so read this type data is slow.
1780
 *   If a type can be read fast, we can try to eliminate Lazy Materialization, because we think for this type, seek cost > read cost.
1781
 *   This is an estimate, if we want more precise cost, statistics collection is necessary(this is a todo).
1782
 *   In short, when returned non-pred columns contains string/hll/bitmap, we using Lazy Materialization.
1783
 *   Otherwise, we disable it.
1784
 *
1785
 *   When Lazy Materialization enable, we need to read column at least two times.
1786
 *   First time to read Pred col, second time to read non-pred.
1787
 *   Here's an interesting question to research, whether read Pred col once is the best plan.
1788
 *   (why not read Pred col twice or more?)
1789
 *
1790
 *   When Lazy Materialization disable, we just need to read once.
1791
 *
1792
 *
1793
 *  2 Whether the predicate type can be evaluate in a fast way(using SIMD to eval pred)
1794
 *    Such as integer type and float type, they can be eval fast.
1795
 *    But for BloomFilter/string/date, they eval slow.
1796
 *    If a type can be eval fast, we use vectorization to eval it.
1797
 *    Otherwise, we use short-circuit to eval it.
1798
 *
1799
 *
1800
 */
1801
1802
// todo(wb) need a UT here
1803
5.63k
Status SegmentIterator::_vec_init_lazy_materialization() {
1804
5.63k
    _is_pred_column.resize(_schema->columns().size(), false);
1805
1806
    // including short/vec/delete pred
1807
5.63k
    std::set<ColumnId> pred_column_ids;
1808
5.63k
    _lazy_materialization_read = false;
1809
1810
5.63k
    std::set<ColumnId> del_cond_id_set;
1811
5.63k
    _opts.delete_condition_predicates->get_all_column_ids(del_cond_id_set);
1812
1813
5.63k
    std::set<std::shared_ptr<const ColumnPredicate>> delete_predicate_set {};
1814
5.63k
    _opts.delete_condition_predicates->get_all_column_predicate(delete_predicate_set);
1815
5.63k
    for (auto predicate : delete_predicate_set) {
1816
467
        if (PredicateTypeTraits::is_range(predicate->type())) {
1817
327
            _delete_range_column_ids.push_back(predicate->column_id());
1818
327
        } else if (PredicateTypeTraits::is_bloom_filter(predicate->type())) {
1819
0
            _delete_bloom_filter_column_ids.push_back(predicate->column_id());
1820
0
        }
1821
467
    }
1822
1823
    // Step1: extract columns that can be lazy materialization
1824
5.63k
    if (!_col_predicates.empty() || !del_cond_id_set.empty()) {
1825
467
        std::set<ColumnId> short_cir_pred_col_id_set; // using set for distinct cid
1826
467
        std::set<ColumnId> vec_pred_col_id_set;
1827
1828
467
        for (auto predicate : _col_predicates) {
1829
0
            auto cid = predicate->column_id();
1830
0
            _is_pred_column[cid] = true;
1831
0
            pred_column_ids.insert(cid);
1832
1833
            // check pred using short eval or vec eval
1834
0
            if (_can_evaluated_by_vectorized(predicate)) {
1835
0
                vec_pred_col_id_set.insert(cid);
1836
0
                _pre_eval_block_predicate.push_back(predicate);
1837
0
            } else {
1838
0
                short_cir_pred_col_id_set.insert(cid);
1839
0
                _short_cir_eval_predicate.push_back(predicate);
1840
0
            }
1841
0
            if (predicate->is_runtime_filter()) {
1842
0
                _filter_info_id.push_back(predicate);
1843
0
            }
1844
0
        }
1845
1846
        // handle delete_condition
1847
467
        if (!del_cond_id_set.empty()) {
1848
467
            short_cir_pred_col_id_set.insert(del_cond_id_set.begin(), del_cond_id_set.end());
1849
467
            pred_column_ids.insert(del_cond_id_set.begin(), del_cond_id_set.end());
1850
1851
467
            for (auto cid : del_cond_id_set) {
1852
467
                _is_pred_column[cid] = true;
1853
467
            }
1854
467
        }
1855
1856
467
        _vec_pred_column_ids.assign(vec_pred_col_id_set.cbegin(), vec_pred_col_id_set.cend());
1857
467
        _short_cir_pred_column_ids.assign(short_cir_pred_col_id_set.cbegin(),
1858
467
                                          short_cir_pred_col_id_set.cend());
1859
467
    }
1860
1861
5.63k
    if (!_vec_pred_column_ids.empty()) {
1862
0
        _is_need_vec_eval = true;
1863
0
    }
1864
5.63k
    if (!_short_cir_pred_column_ids.empty()) {
1865
467
        _is_need_short_eval = true;
1866
467
    }
1867
1868
    // ColumnId to column index in block
1869
    // ColumnId will contail all columns in tablet schema, including virtual columns and global rowid column,
1870
5.63k
    _schema_block_id_map.resize(_schema->columns().size(), -1);
1871
    // Use cols read by query to initialize _schema_block_id_map.
1872
    // We need to know the index of each column in the block.
1873
    // There is an assumption here that the columns in the block are in the same order as in the read schema.
1874
    // TODO: A probelm is that, delete condition columns will exist in _schema->column_ids but not in block if
1875
    // delete column is not read by the query.
1876
18.3k
    for (int i = 0; i < _schema->num_column_ids(); i++) {
1877
12.6k
        auto cid = _schema->column_id(i);
1878
12.6k
        _schema_block_id_map[cid] = i;
1879
12.6k
    }
1880
1881
    // Step2: extract columns that can execute expr context
1882
5.63k
    _is_common_expr_column.resize(_schema->columns().size(), false);
1883
5.63k
    if (_enable_common_expr_pushdown && !_remaining_conjunct_roots.empty()) {
1884
0
        for (auto expr : _remaining_conjunct_roots) {
1885
0
            RETURN_IF_ERROR(_extract_common_expr_columns(expr));
1886
0
        }
1887
0
        if (!_common_expr_columns.empty()) {
1888
0
            _is_need_expr_eval = true;
1889
0
            for (auto cid : _schema->column_ids()) {
1890
                // pred column also needs to be filtered by expr, exclude additional delete condition column.
1891
                // if delete condition column not in the block, no filter is needed
1892
                // and will be removed from _columns_to_filter in the first next_batch.
1893
0
                if (_is_common_expr_column[cid] || _is_pred_column[cid]) {
1894
0
                    auto loc = _schema_block_id_map[cid];
1895
0
                    _columns_to_filter.push_back(loc);
1896
0
                }
1897
0
            }
1898
1899
0
            for (auto pair : _vir_cid_to_idx_in_block) {
1900
0
                _columns_to_filter.push_back(cast_set<ColumnId>(pair.second));
1901
0
            }
1902
0
        }
1903
0
    }
1904
1905
    // Step 3: fill non predicate columns and second read column
1906
    // if _schema columns size equal to pred_column_ids size, lazy_materialization_read is false,
1907
    // all columns are lazy materialization columns without non predicte column.
1908
    // If common expr pushdown exists, and expr column is not contained in lazy materialization columns,
1909
    // add to second read column, which will be read after lazy materialization
1910
5.63k
    if (_schema->column_ids().size() > pred_column_ids.size()) {
1911
        // pred_column_ids maybe empty, so that could not set _lazy_materialization_read = true here
1912
        // has to check there is at least one predicate column
1913
12.6k
        for (auto cid : _schema->column_ids()) {
1914
12.6k
            if (!_is_pred_column[cid]) {
1915
12.2k
                if (_is_need_vec_eval || _is_need_short_eval) {
1916
862
                    _lazy_materialization_read = true;
1917
862
                }
1918
12.2k
                if (_is_common_expr_column[cid]) {
1919
0
                    _common_expr_column_ids.push_back(cid);
1920
12.2k
                } else {
1921
12.2k
                    _non_predicate_columns.push_back(cid);
1922
12.2k
                }
1923
12.2k
            }
1924
12.6k
        }
1925
5.57k
    }
1926
1927
    // Step 4: fill first read columns
1928
5.63k
    if (_lazy_materialization_read) {
1929
        // insert pred cid to first_read_columns
1930
410
        for (auto cid : pred_column_ids) {
1931
410
            _predicate_column_ids.push_back(cid);
1932
410
        }
1933
5.22k
    } else if (!_is_need_vec_eval && !_is_need_short_eval && !_is_need_expr_eval) {
1934
16.5k
        for (int i = 0; i < _schema->num_column_ids(); i++) {
1935
11.3k
            auto cid = _schema->column_id(i);
1936
11.3k
            _predicate_column_ids.push_back(cid);
1937
11.3k
        }
1938
5.16k
    } else {
1939
57
        if (_is_need_vec_eval || _is_need_short_eval) {
1940
            // TODO To refactor, because we suppose lazy materialization is better performance.
1941
            // pred exits, but we can eliminate lazy materialization
1942
            // insert pred/non-pred cid to first read columns
1943
57
            std::set<ColumnId> pred_id_set;
1944
57
            pred_id_set.insert(_short_cir_pred_column_ids.begin(),
1945
57
                               _short_cir_pred_column_ids.end());
1946
57
            pred_id_set.insert(_vec_pred_column_ids.begin(), _vec_pred_column_ids.end());
1947
1948
57
            DCHECK(_common_expr_column_ids.empty());
1949
            // _non_predicate_column_ids must be empty. Otherwise _lazy_materialization_read must not false.
1950
114
            for (int i = 0; i < _schema->num_column_ids(); i++) {
1951
57
                auto cid = _schema->column_id(i);
1952
57
                if (pred_id_set.find(cid) != pred_id_set.end()) {
1953
57
                    _predicate_column_ids.push_back(cid);
1954
57
                }
1955
57
            }
1956
57
        } else if (_is_need_expr_eval) {
1957
0
            DCHECK(!_is_need_vec_eval && !_is_need_short_eval);
1958
0
            for (auto cid : _common_expr_columns) {
1959
0
                _predicate_column_ids.push_back(cid);
1960
0
            }
1961
0
        }
1962
57
    }
1963
1964
5.63k
    VLOG_DEBUG << fmt::format(
1965
0
            "Laze materialization init end. "
1966
0
            "lazy_materialization_read: {}, "
1967
0
            "_col_predicates size: {}, "
1968
0
            "_cols_read_by_column_predicate: [{}], "
1969
0
            "_non_predicate_columns: [{}], "
1970
0
            "_cols_read_by_common_expr: [{}], "
1971
0
            "columns_to_filter: [{}], "
1972
0
            "_schema_block_id_map: [{}]",
1973
0
            _lazy_materialization_read, _col_predicates.size(),
1974
0
            fmt::join(_predicate_column_ids, ","), fmt::join(_non_predicate_columns, ","),
1975
0
            fmt::join(_common_expr_column_ids, ","), fmt::join(_columns_to_filter, ","),
1976
0
            fmt::join(_schema_block_id_map, ","));
1977
5.63k
    return Status::OK();
1978
5.63k
}
1979
1980
0
bool SegmentIterator::_can_evaluated_by_vectorized(std::shared_ptr<ColumnPredicate> predicate) {
1981
0
    auto cid = predicate->column_id();
1982
0
    FieldType field_type = _schema->column(cid)->type();
1983
0
    if (field_type == FieldType::OLAP_FIELD_TYPE_VARIANT) {
1984
        // Use variant cast dst type
1985
0
        field_type = _opts.target_cast_type_for_variants[_schema->column(cid)->name()]
1986
0
                             ->get_storage_field_type();
1987
0
    }
1988
0
    switch (predicate->type()) {
1989
0
    case PredicateType::EQ:
1990
0
    case PredicateType::NE:
1991
0
    case PredicateType::LE:
1992
0
    case PredicateType::LT:
1993
0
    case PredicateType::GE:
1994
0
    case PredicateType::GT: {
1995
0
        if (field_type == FieldType::OLAP_FIELD_TYPE_VARCHAR ||
1996
0
            field_type == FieldType::OLAP_FIELD_TYPE_CHAR ||
1997
0
            field_type == FieldType::OLAP_FIELD_TYPE_STRING) {
1998
0
            return config::enable_low_cardinality_optimize &&
1999
0
                   _opts.io_ctx.reader_type == ReaderType::READER_QUERY &&
2000
0
                   _column_iterators[cid]->is_all_dict_encoding();
2001
0
        } else if (field_type == FieldType::OLAP_FIELD_TYPE_DECIMAL) {
2002
0
            return false;
2003
0
        }
2004
0
        return true;
2005
0
    }
2006
0
    default:
2007
0
        return false;
2008
0
    }
2009
0
}
2010
2011
12.6k
bool SegmentIterator::_has_char_type(const StorageField& column_desc) {
2012
12.6k
    switch (column_desc.type()) {
2013
0
    case FieldType::OLAP_FIELD_TYPE_CHAR:
2014
0
        return true;
2015
2
    case FieldType::OLAP_FIELD_TYPE_ARRAY:
2016
2
        return _has_char_type(*column_desc.get_sub_field(0));
2017
0
    case FieldType::OLAP_FIELD_TYPE_MAP:
2018
0
        return _has_char_type(*column_desc.get_sub_field(0)) ||
2019
0
               _has_char_type(*column_desc.get_sub_field(1));
2020
0
    case FieldType::OLAP_FIELD_TYPE_STRUCT:
2021
0
        for (int idx = 0; idx < column_desc.get_sub_field_count(); ++idx) {
2022
0
            if (_has_char_type(*column_desc.get_sub_field(idx))) {
2023
0
                return true;
2024
0
            }
2025
0
        }
2026
0
        return false;
2027
12.6k
    default:
2028
12.6k
        return false;
2029
12.6k
    }
2030
12.6k
};
2031
2032
5.63k
void SegmentIterator::_vec_init_char_column_id(Block* block) {
2033
5.63k
    if (!_char_type_idx.empty()) {
2034
0
        return;
2035
0
    }
2036
5.63k
    _is_char_type.resize(_schema->columns().size(), false);
2037
18.3k
    for (size_t i = 0; i < _schema->num_column_ids(); i++) {
2038
12.6k
        auto cid = _schema->column_id(i);
2039
12.6k
        const StorageField* column_desc = _schema->column(cid);
2040
2041
        // The additional deleted filter condition will be in the materialized column at the end of the block.
2042
        // After _output_column_by_sel_idx, it will be erased, so we do not need to shrink it.
2043
12.6k
        if (i < block->columns()) {
2044
12.6k
            if (_has_char_type(*column_desc)) {
2045
0
                _char_type_idx.emplace_back(i);
2046
0
            }
2047
12.6k
        }
2048
2049
12.6k
        if (column_desc->type() == FieldType::OLAP_FIELD_TYPE_CHAR) {
2050
0
            _is_char_type[cid] = true;
2051
0
        }
2052
12.6k
    }
2053
5.63k
}
2054
2055
bool SegmentIterator::_prune_column(ColumnId cid, MutableColumnPtr& column, bool fill_defaults,
2056
43.4k
                                    size_t num_of_defaults) {
2057
43.4k
    if (_need_read_data(cid)) {
2058
43.4k
        return false;
2059
43.4k
    }
2060
0
    if (!fill_defaults) {
2061
0
        return true;
2062
0
    }
2063
0
    if (column->is_nullable()) {
2064
0
        auto nullable_col_ptr = reinterpret_cast<ColumnNullable*>(column.get());
2065
0
        nullable_col_ptr->get_null_map_column().insert_many_defaults(num_of_defaults);
2066
0
        nullable_col_ptr->get_nested_column_ptr()->insert_many_defaults(num_of_defaults);
2067
0
    } else {
2068
        // assert(column->is_const());
2069
0
        column->insert_many_defaults(num_of_defaults);
2070
0
    }
2071
0
    return true;
2072
0
}
2073
2074
Status SegmentIterator::_read_columns(const std::vector<ColumnId>& column_ids,
2075
0
                                      MutableColumns& column_block, size_t nrows) {
2076
0
    for (auto cid : column_ids) {
2077
0
        auto& column = column_block[cid];
2078
0
        size_t rows_read = nrows;
2079
0
        if (_prune_column(cid, column, true, rows_read)) {
2080
0
            continue;
2081
0
        }
2082
0
        RETURN_IF_ERROR(_column_iterators[cid]->next_batch(&rows_read, column));
2083
0
        if (nrows != rows_read) {
2084
0
            return Status::Error<ErrorCode::INTERNAL_ERROR>("nrows({}) != rows_read({})", nrows,
2085
0
                                                            rows_read);
2086
0
        }
2087
0
    }
2088
0
    return Status::OK();
2089
0
}
2090
2091
Status SegmentIterator::_init_current_block(Block* block,
2092
                                            std::vector<MutableColumnPtr>& current_columns,
2093
23.1k
                                            uint32_t nrows_read_limit) {
2094
23.1k
    block->clear_column_data(_schema->num_column_ids());
2095
2096
67.5k
    for (size_t i = 0; i < _schema->num_column_ids(); i++) {
2097
44.4k
        auto cid = _schema->column_id(i);
2098
44.4k
        const auto* column_desc = _schema->column(cid);
2099
2100
44.4k
        auto file_column_type = _storage_name_and_type[cid].second;
2101
44.4k
        auto expected_type = Schema::get_data_type_ptr(*column_desc);
2102
44.4k
        if (!_is_pred_column[cid] && !file_column_type->equals(*expected_type)) {
2103
            // The storage layer type is different from schema needed type, so we use storage
2104
            // type to read columns instead of schema type for safety
2105
0
            VLOG_DEBUG << fmt::format(
2106
0
                    "Recreate column with expected type {}, file column type {}, col_name {}, "
2107
0
                    "col_path {}",
2108
0
                    block->get_by_position(i).type->get_name(), file_column_type->get_name(),
2109
0
                    column_desc->name(),
2110
0
                    column_desc->path() == nullptr ? "" : column_desc->path()->get_path());
2111
            // TODO reuse
2112
0
            current_columns[cid] = file_column_type->create_column();
2113
0
            current_columns[cid]->reserve(nrows_read_limit);
2114
44.4k
        } else {
2115
            // the column in block must clear() here to insert new data
2116
44.4k
            if (_is_pred_column[cid] ||
2117
44.4k
                i >= block->columns()) { //todo(wb) maybe we can release it after output block
2118
4.66k
                if (current_columns[cid].get() == nullptr) {
2119
0
                    return Status::InternalError(
2120
0
                            "SegmentIterator meet invalid column, id={}, name={}", cid,
2121
0
                            _schema->column(cid)->name());
2122
0
                }
2123
4.66k
                current_columns[cid]->clear();
2124
39.7k
            } else { // non-predicate column
2125
39.7k
                current_columns[cid] = std::move(*block->get_by_position(i).column).mutate();
2126
39.7k
                current_columns[cid]->reserve(nrows_read_limit);
2127
39.7k
            }
2128
44.4k
        }
2129
44.4k
    }
2130
2131
23.1k
    for (auto entry : _virtual_column_exprs) {
2132
0
        auto cid = entry.first;
2133
0
        current_columns[cid] = ColumnNothing::create(0);
2134
0
        current_columns[cid]->reserve(nrows_read_limit);
2135
0
    }
2136
2137
23.1k
    return Status::OK();
2138
23.1k
}
2139
2140
17.5k
Status SegmentIterator::_output_non_pred_columns(Block* block) {
2141
17.5k
    SCOPED_RAW_TIMER(&_opts.stats->output_col_ns);
2142
17.5k
    VLOG_DEBUG << fmt::format(
2143
0
            "Output non-predicate columns, _non_predicate_columns: [{}], "
2144
0
            "_schema_block_id_map: [{}]",
2145
0
            fmt::join(_non_predicate_columns, ","), fmt::join(_schema_block_id_map, ","));
2146
17.5k
    RETURN_IF_ERROR(_convert_to_expected_type(_non_predicate_columns));
2147
27.5k
    for (auto cid : _non_predicate_columns) {
2148
27.5k
        auto loc = _schema_block_id_map[cid];
2149
        // Whether a delete predicate column gets output depends on how the caller builds
2150
        // the block passed to next_batch(). Both calling paths now build the block with
2151
        // only the output schema (return_columns), so delete predicate columns are skipped:
2152
        //
2153
        // 1) VMergeIterator path: block_reset() builds _block using the output schema
2154
        //    (return_columns only), e.g. block has 2 columns {c1, c2}.
2155
        //    Here loc=2 for delete predicate c3, block->columns()=2, so loc < block->columns()
2156
        //    is false, and c3 is skipped.
2157
        //
2158
        // 2) VUnionIterator path: the caller's block is built with only return_columns
2159
        //    (output schema), e.g. block has 2 columns {c1, c2}.
2160
        //    Here loc=2 for c3, block->columns()=2, so loc < block->columns() is false,
2161
        //    and c3 is skipped — same behavior as the VMergeIterator path.
2162
27.5k
        if (loc < block->columns()) {
2163
27.5k
            bool column_in_block_is_nothing = check_and_get_column<const ColumnNothing>(
2164
27.5k
                    block->get_by_position(loc).column.get());
2165
27.5k
            bool column_is_normal = !_vir_cid_to_idx_in_block.contains(cid);
2166
27.5k
            bool return_column_is_nothing =
2167
27.5k
                    check_and_get_column<const ColumnNothing>(_current_return_columns[cid].get());
2168
27.5k
            VLOG_DEBUG << fmt::format(
2169
0
                    "Cid {} loc {}, column_in_block_is_nothing {}, column_is_normal {}, "
2170
0
                    "return_column_is_nothing {}",
2171
0
                    cid, loc, column_in_block_is_nothing, column_is_normal,
2172
0
                    return_column_is_nothing);
2173
2174
27.5k
            if (column_in_block_is_nothing || column_is_normal) {
2175
27.5k
                block->replace_by_position(loc, std::move(_current_return_columns[cid]));
2176
27.5k
                VLOG_DEBUG << fmt::format(
2177
0
                        "Output non-predicate column, cid: {}, loc: {}, col_name: {}, rows {}", cid,
2178
0
                        loc, _schema->column(cid)->name(),
2179
0
                        block->get_by_position(loc).column->size());
2180
27.5k
            }
2181
            // Means virtual column in block has been materialized(maybe by common expr).
2182
            // so do nothing here.
2183
27.5k
        }
2184
27.5k
    }
2185
17.5k
    return Status::OK();
2186
17.5k
}
2187
2188
/**
2189
 * Reads columns by their index, handling both continuous and discontinuous rowid scenarios.
2190
 *
2191
 * This function is designed to read a specified number of rows (up to nrows_read_limit)
2192
 * from the segment iterator, dealing with both continuous and discontinuous rowid arrays.
2193
 * It operates as follows:
2194
 *
2195
 * 1. Reads a batch of rowids (up to the specified limit), and checks if they are continuous.
2196
 *    Continuous here means that the rowids form an unbroken sequence (e.g., 1, 2, 3, 4...).
2197
 *
2198
 * 2. For each column that needs to be read (identified by _predicate_column_ids):
2199
 *    - If the rowids are continuous, the function uses seek_to_ordinal and next_batch
2200
 *      for efficient reading.
2201
 *    - If the rowids are not continuous, the function processes them in smaller batches
2202
 *      (each of size up to 256). Each batch is checked for internal continuity:
2203
 *        a. If a batch is continuous, uses seek_to_ordinal and next_batch for that batch.
2204
 *        b. If a batch is not continuous, uses read_by_rowids for individual rowids in the batch.
2205
 *
2206
 * This approach optimizes reading performance by leveraging batch processing for continuous
2207
 * rowid sequences and handling discontinuities gracefully in smaller chunks.
2208
 */
2209
23.1k
Status SegmentIterator::_read_columns_by_index(uint32_t nrows_read_limit, uint16_t& nrows_read) {
2210
23.1k
    SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_ns);
2211
2212
23.1k
    nrows_read = (uint16_t)_range_iter->read_batch_rowids(_block_rowids.data(), nrows_read_limit);
2213
23.1k
    bool is_continuous = (nrows_read > 1) &&
2214
23.1k
                         (_block_rowids[nrows_read - 1] - _block_rowids[0] == nrows_read - 1);
2215
23.1k
    VLOG_DEBUG << fmt::format(
2216
0
            "nrows_read from range iterator: {}, is_continus {}, _cols_read_by_column_predicate "
2217
0
            "[{}]",
2218
0
            nrows_read, is_continuous, fmt::join(_predicate_column_ids, ","));
2219
2220
23.1k
    LOG_IF(INFO, config::enable_segment_prefetch_verbose_log) << fmt::format(
2221
0
            "[verbose] SegmentIterator::_read_columns_by_index read {} rowids, continuous: {}, "
2222
0
            "rowids: [{}...{}]",
2223
0
            nrows_read, is_continuous, nrows_read > 0 ? _block_rowids[0] : 0,
2224
0
            nrows_read > 0 ? _block_rowids[nrows_read - 1] : 0);
2225
39.6k
    for (auto cid : _predicate_column_ids) {
2226
39.6k
        auto& column = _current_return_columns[cid];
2227
39.6k
        VLOG_DEBUG << fmt::format("Reading column {}, col_name {}", cid,
2228
0
                                  _schema->column(cid)->name());
2229
39.6k
        if (!_virtual_column_exprs.contains(cid)) {
2230
39.6k
            if (_no_need_read_key_data(cid, column, nrows_read)) {
2231
0
                VLOG_DEBUG << fmt::format("Column {} no need to read.", cid);
2232
0
                continue;
2233
0
            }
2234
39.6k
            if (_prune_column(cid, column, true, nrows_read)) {
2235
0
                VLOG_DEBUG << fmt::format("Column {} is pruned. No need to read data.", cid);
2236
0
                continue;
2237
0
            }
2238
39.6k
            DBUG_EXECUTE_IF("segment_iterator._read_columns_by_index", {
2239
39.6k
                auto col_name = _opts.tablet_schema->column(cid).name();
2240
39.6k
                auto debug_col_name =
2241
39.6k
                        DebugPoints::instance()->get_debug_param_or_default<std::string>(
2242
39.6k
                                "segment_iterator._read_columns_by_index", "column_name", "");
2243
39.6k
                if (debug_col_name.empty() && col_name != "__DORIS_DELETE_SIGN__") {
2244
39.6k
                    return Status::Error<ErrorCode::INTERNAL_ERROR>(
2245
39.6k
                            "does not need to read data, {}", col_name);
2246
39.6k
                }
2247
39.6k
                if (debug_col_name.find(col_name) != std::string::npos) {
2248
39.6k
                    return Status::Error<ErrorCode::INTERNAL_ERROR>(
2249
39.6k
                            "does not need to read data, {}", col_name);
2250
39.6k
                }
2251
39.6k
            })
2252
39.6k
        }
2253
2254
39.6k
        if (is_continuous) {
2255
27.5k
            size_t rows_read = nrows_read;
2256
27.5k
            _opts.stats->predicate_column_read_seek_num += 1;
2257
27.5k
            if (_opts.runtime_state && _opts.runtime_state->enable_profile()) {
2258
0
                SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_seek_ns);
2259
0
                RETURN_IF_ERROR(_column_iterators[cid]->seek_to_ordinal(_block_rowids[0]));
2260
27.5k
            } else {
2261
27.5k
                RETURN_IF_ERROR(_column_iterators[cid]->seek_to_ordinal(_block_rowids[0]));
2262
27.5k
            }
2263
27.5k
            RETURN_IF_ERROR(_column_iterators[cid]->next_batch(&rows_read, column));
2264
27.5k
            if (rows_read != nrows_read) {
2265
0
                return Status::Error<ErrorCode::INTERNAL_ERROR>("nrows({}) != rows_read({})",
2266
0
                                                                nrows_read, rows_read);
2267
0
            }
2268
27.5k
        } else {
2269
12.1k
            const uint32_t batch_size = _range_iter->get_batch_size();
2270
12.1k
            uint32_t processed = 0;
2271
13.3k
            while (processed < nrows_read) {
2272
1.19k
                uint32_t current_batch_size = std::min(batch_size, nrows_read - processed);
2273
1.19k
                bool batch_continuous = (current_batch_size > 1) &&
2274
1.19k
                                        (_block_rowids[processed + current_batch_size - 1] -
2275
1.17k
                                                 _block_rowids[processed] ==
2276
1.17k
                                         current_batch_size - 1);
2277
2278
1.19k
                if (batch_continuous) {
2279
0
                    size_t rows_read = current_batch_size;
2280
0
                    _opts.stats->predicate_column_read_seek_num += 1;
2281
0
                    if (_opts.runtime_state && _opts.runtime_state->enable_profile()) {
2282
0
                        SCOPED_RAW_TIMER(&_opts.stats->predicate_column_read_seek_ns);
2283
0
                        RETURN_IF_ERROR(
2284
0
                                _column_iterators[cid]->seek_to_ordinal(_block_rowids[processed]));
2285
0
                    } else {
2286
0
                        RETURN_IF_ERROR(
2287
0
                                _column_iterators[cid]->seek_to_ordinal(_block_rowids[processed]));
2288
0
                    }
2289
0
                    RETURN_IF_ERROR(_column_iterators[cid]->next_batch(&rows_read, column));
2290
0
                    if (rows_read != current_batch_size) {
2291
0
                        return Status::Error<ErrorCode::INTERNAL_ERROR>(
2292
0
                                "batch nrows({}) != rows_read({})", current_batch_size, rows_read);
2293
0
                    }
2294
1.19k
                } else {
2295
1.19k
                    RETURN_IF_ERROR(_column_iterators[cid]->read_by_rowids(
2296
1.19k
                            &_block_rowids[processed], current_batch_size, column));
2297
1.19k
                }
2298
1.19k
                processed += current_batch_size;
2299
1.19k
            }
2300
12.1k
        }
2301
39.6k
    }
2302
2303
23.1k
    return Status::OK();
2304
23.1k
}
2305
void SegmentIterator::_replace_version_col_if_needed(const std::vector<ColumnId>& column_ids,
2306
26.1k
                                                     size_t num_rows) {
2307
    // Only the rowset with single version need to replace the version column.
2308
    // Doris can't determine the version before publish_version finished, so
2309
    // we can't write data to __DORIS_VERSION_COL__ in segment writer, the value
2310
    // is 0 by default.
2311
    // So we need to replace the value to real version while reading.
2312
26.1k
    if (_opts.version.first != _opts.version.second) {
2313
9.41k
        return;
2314
9.41k
    }
2315
16.7k
    int32_t version_idx = _schema->version_col_idx();
2316
16.7k
    if (std::ranges::find(column_ids, version_idx) == column_ids.end()) {
2317
16.7k
        return;
2318
16.7k
    }
2319
2320
0
    const auto* column_desc = _schema->column(version_idx);
2321
0
    auto column = Schema::get_data_type_ptr(*column_desc)->create_column();
2322
0
    DCHECK(_schema->column(version_idx)->type() == FieldType::OLAP_FIELD_TYPE_BIGINT);
2323
0
    auto* col_ptr = assert_cast<ColumnInt64*>(column.get());
2324
0
    for (size_t j = 0; j < num_rows; j++) {
2325
0
        col_ptr->insert_value(_opts.version.second);
2326
0
    }
2327
0
    _current_return_columns[version_idx] = std::move(column);
2328
0
    VLOG_DEBUG << "replaced version column in segment iterator, version_col_idx:" << version_idx;
2329
0
}
2330
2331
uint16_t SegmentIterator::_evaluate_vectorization_predicate(uint16_t* sel_rowid_idx,
2332
4.19k
                                                            uint16_t selected_size) {
2333
4.19k
    SCOPED_RAW_TIMER(&_opts.stats->vec_cond_ns);
2334
4.19k
    bool all_pred_always_true = true;
2335
4.19k
    for (const auto& pred : _pre_eval_block_predicate) {
2336
0
        if (!pred->always_true()) {
2337
0
            all_pred_always_true = false;
2338
0
        } else {
2339
0
            pred->update_filter_info(0, 0, selected_size);
2340
0
        }
2341
0
    }
2342
2343
4.19k
    const uint16_t original_size = selected_size;
2344
    //If all predicates are always_true, then return directly.
2345
4.19k
    if (all_pred_always_true || !_is_need_vec_eval) {
2346
3.91M
        for (uint16_t i = 0; i < original_size; ++i) {
2347
3.90M
            sel_rowid_idx[i] = i;
2348
3.90M
        }
2349
        // All preds are always_true, so return immediately and update the profile statistics here.
2350
4.19k
        _opts.stats->vec_cond_input_rows += original_size;
2351
4.19k
        return original_size;
2352
4.19k
    }
2353
2354
0
    _ret_flags.resize(original_size);
2355
0
    DCHECK(!_pre_eval_block_predicate.empty());
2356
0
    bool is_first = true;
2357
0
    for (auto& pred : _pre_eval_block_predicate) {
2358
0
        if (pred->always_true()) {
2359
0
            continue;
2360
0
        }
2361
0
        auto column_id = pred->column_id();
2362
0
        auto& column = _current_return_columns[column_id];
2363
0
        if (is_first) {
2364
0
            pred->evaluate_vec(*column, original_size, (bool*)_ret_flags.data());
2365
0
            is_first = false;
2366
0
        } else {
2367
0
            pred->evaluate_and_vec(*column, original_size, (bool*)_ret_flags.data());
2368
0
        }
2369
0
    }
2370
2371
0
    uint16_t new_size = 0;
2372
2373
0
    uint16_t sel_pos = 0;
2374
0
    const uint16_t sel_end = sel_pos + selected_size;
2375
0
    static constexpr size_t SIMD_BYTES = simd::bits_mask_length();
2376
0
    const uint16_t sel_end_simd = sel_pos + selected_size / SIMD_BYTES * SIMD_BYTES;
2377
2378
0
    while (sel_pos < sel_end_simd) {
2379
0
        auto mask = simd::bytes_mask_to_bits_mask(_ret_flags.data() + sel_pos);
2380
0
        if (0 == mask) {
2381
            //pass
2382
0
        } else if (simd::bits_mask_all() == mask) {
2383
0
            for (uint16_t i = 0; i < SIMD_BYTES; i++) {
2384
0
                sel_rowid_idx[new_size++] = sel_pos + i;
2385
0
            }
2386
0
        } else {
2387
0
            simd::iterate_through_bits_mask(
2388
0
                    [&](const int bit_pos) {
2389
0
                        sel_rowid_idx[new_size++] = sel_pos + (uint16_t)bit_pos;
2390
0
                    },
2391
0
                    mask);
2392
0
        }
2393
0
        sel_pos += SIMD_BYTES;
2394
0
    }
2395
2396
0
    for (; sel_pos < sel_end; sel_pos++) {
2397
0
        if (_ret_flags[sel_pos]) {
2398
0
            sel_rowid_idx[new_size++] = sel_pos;
2399
0
        }
2400
0
    }
2401
2402
0
    _opts.stats->vec_cond_input_rows += original_size;
2403
0
    _opts.stats->rows_vec_cond_filtered += original_size - new_size;
2404
0
    return new_size;
2405
4.19k
}
2406
2407
uint16_t SegmentIterator::_evaluate_short_circuit_predicate(uint16_t* vec_sel_rowid_idx,
2408
4.19k
                                                            uint16_t selected_size) {
2409
4.19k
    SCOPED_RAW_TIMER(&_opts.stats->short_cond_ns);
2410
4.19k
    if (!_is_need_short_eval) {
2411
0
        return selected_size;
2412
0
    }
2413
2414
4.19k
    uint16_t original_size = selected_size;
2415
4.19k
    for (auto predicate : _short_cir_eval_predicate) {
2416
0
        auto column_id = predicate->column_id();
2417
0
        auto& short_cir_column = _current_return_columns[column_id];
2418
0
        selected_size = predicate->evaluate(*short_cir_column, vec_sel_rowid_idx, selected_size);
2419
0
    }
2420
2421
4.19k
    _opts.stats->short_circuit_cond_input_rows += original_size;
2422
4.19k
    _opts.stats->rows_short_circuit_cond_filtered += original_size - selected_size;
2423
2424
    // evaluate delete condition
2425
4.19k
    original_size = selected_size;
2426
4.19k
    selected_size = _opts.delete_condition_predicates->evaluate(_current_return_columns,
2427
4.19k
                                                                vec_sel_rowid_idx, selected_size);
2428
4.19k
    _opts.stats->rows_vec_del_cond_filtered += original_size - selected_size;
2429
4.19k
    return selected_size;
2430
4.19k
}
2431
2432
Status SegmentIterator::_read_columns_by_rowids(std::vector<ColumnId>& read_column_ids,
2433
                                                std::vector<rowid_t>& rowid_vector,
2434
                                                uint16_t* sel_rowid_idx, size_t select_size,
2435
                                                MutableColumns* mutable_columns,
2436
3.05k
                                                bool init_condition_cache) {
2437
3.05k
    SCOPED_RAW_TIMER(&_opts.stats->lazy_read_ns);
2438
3.05k
    std::vector<rowid_t> rowids(select_size);
2439
2440
3.05k
    if (init_condition_cache) {
2441
0
        DCHECK(_condition_cache);
2442
0
        auto& condition_cache = *_condition_cache;
2443
0
        for (size_t i = 0; i < select_size; ++i) {
2444
0
            rowids[i] = rowid_vector[sel_rowid_idx[i]];
2445
0
            condition_cache[rowids[i] / SegmentIterator::CONDITION_CACHE_OFFSET] = true;
2446
0
        }
2447
3.05k
    } else {
2448
2.74M
        for (size_t i = 0; i < select_size; ++i) {
2449
2.74M
            rowids[i] = rowid_vector[sel_rowid_idx[i]];
2450
2.74M
        }
2451
3.05k
    }
2452
2453
3.77k
    for (auto cid : read_column_ids) {
2454
3.77k
        auto& colunm = (*mutable_columns)[cid];
2455
3.77k
        if (_no_need_read_key_data(cid, colunm, select_size)) {
2456
0
            continue;
2457
0
        }
2458
3.77k
        if (_prune_column(cid, colunm, true, select_size)) {
2459
0
            continue;
2460
0
        }
2461
2462
3.77k
        DBUG_EXECUTE_IF("segment_iterator._read_columns_by_index", {
2463
3.77k
            auto debug_col_name = DebugPoints::instance()->get_debug_param_or_default<std::string>(
2464
3.77k
                    "segment_iterator._read_columns_by_index", "column_name", "");
2465
3.77k
            if (debug_col_name.empty()) {
2466
3.77k
                return Status::Error<ErrorCode::INTERNAL_ERROR>("does not need to read data");
2467
3.77k
            }
2468
3.77k
            auto col_name = _opts.tablet_schema->column(cid).name();
2469
3.77k
            if (debug_col_name.find(col_name) != std::string::npos) {
2470
3.77k
                return Status::Error<ErrorCode::INTERNAL_ERROR>("does not need to read data, {}",
2471
3.77k
                                                                debug_col_name);
2472
3.77k
            }
2473
3.77k
        })
2474
2475
3.77k
        if (_current_return_columns[cid].get() == nullptr) {
2476
0
            return Status::InternalError(
2477
0
                    "SegmentIterator meet invalid column, return columns size {}, cid {}",
2478
0
                    _current_return_columns.size(), cid);
2479
0
        }
2480
3.77k
        RETURN_IF_ERROR(_column_iterators[cid]->read_by_rowids(rowids.data(), select_size,
2481
3.77k
                                                               _current_return_columns[cid]));
2482
3.77k
    }
2483
2484
3.05k
    return Status::OK();
2485
3.05k
}
2486
2487
23.1k
Status SegmentIterator::next_batch(Block* block) {
2488
    // Replace virtual columns with ColumnNothing at the begining of each next_batch call.
2489
23.1k
    _init_virtual_columns(block);
2490
23.1k
    auto status = [&]() {
2491
23.1k
        RETURN_IF_CATCH_EXCEPTION({
2492
23.1k
            auto res = _next_batch_internal(block);
2493
2494
23.1k
            if (res.is<END_OF_FILE>()) {
2495
                // Since we have a type check at the caller.
2496
                // So a replacement of nothing column with real column is needed.
2497
23.1k
                const auto& idx_to_datatype = _opts.vir_col_idx_to_type;
2498
23.1k
                for (const auto& pair : _vir_cid_to_idx_in_block) {
2499
23.1k
                    size_t idx = pair.second;
2500
23.1k
                    auto type = idx_to_datatype.find(idx)->second;
2501
23.1k
                    block->replace_by_position(idx, type->create_column());
2502
23.1k
                }
2503
2504
23.1k
                if (_opts.condition_cache_digest && !_find_condition_cache) {
2505
23.1k
                    auto* condition_cache = ConditionCache::instance();
2506
23.1k
                    ConditionCache::CacheKey cache_key(_opts.rowset_id, _segment->id(),
2507
23.1k
                                                       _opts.condition_cache_digest);
2508
23.1k
                    VLOG_DEBUG << "Condition cache insert, query id: "
2509
23.1k
                               << print_id(_opts.runtime_state->query_id())
2510
23.1k
                               << ", rowset id: " << _opts.rowset_id.to_string()
2511
23.1k
                               << ", segment id: " << _segment->id()
2512
23.1k
                               << ", cache digest: " << _opts.condition_cache_digest;
2513
23.1k
                    condition_cache->insert(cache_key, std::move(_condition_cache));
2514
23.1k
                }
2515
23.1k
                return res;
2516
23.1k
            }
2517
2518
23.1k
            RETURN_IF_ERROR(res);
2519
            // reverse block row order if read_orderby_key_reverse is true for key topn
2520
            // it should be processed for all success _next_batch_internal
2521
23.1k
            if (_opts.read_orderby_key_reverse) {
2522
23.1k
                size_t num_rows = block->rows();
2523
23.1k
                if (num_rows == 0) {
2524
23.1k
                    return Status::OK();
2525
23.1k
                }
2526
23.1k
                size_t num_columns = block->columns();
2527
23.1k
                IColumn::Permutation permutation;
2528
23.1k
                for (size_t i = 0; i < num_rows; ++i) permutation.emplace_back(num_rows - 1 - i);
2529
2530
23.1k
                for (size_t i = 0; i < num_columns; ++i)
2531
23.1k
                    block->get_by_position(i).column =
2532
23.1k
                            block->get_by_position(i).column->permute(permutation, num_rows);
2533
23.1k
            }
2534
2535
23.1k
            RETURN_IF_ERROR(block->check_type_and_column());
2536
2537
23.1k
            return Status::OK();
2538
23.1k
        });
2539
23.1k
    }();
2540
2541
    // if rows read by batch is 0, will return end of file, we should not remove segment cache in this situation.
2542
23.1k
    if (!status.ok() && !status.is<END_OF_FILE>()) {
2543
0
        _segment->update_healthy_status(status);
2544
0
    }
2545
23.1k
    return status;
2546
23.1k
}
2547
2548
23.1k
Status SegmentIterator::_convert_to_expected_type(const std::vector<ColumnId>& col_ids) {
2549
40.2k
    for (ColumnId i : col_ids) {
2550
40.2k
        if (!_current_return_columns[i] || _converted_column_ids[i] || _is_pred_column[i]) {
2551
467
            continue;
2552
467
        }
2553
39.7k
        const StorageField* field_type = _schema->column(i);
2554
39.7k
        DataTypePtr expected_type = Schema::get_data_type_ptr(*field_type);
2555
39.7k
        DataTypePtr file_column_type = _storage_name_and_type[i].second;
2556
39.7k
        if (!file_column_type->equals(*expected_type)) {
2557
0
            ColumnPtr expected;
2558
0
            ColumnPtr original = _current_return_columns[i]->assume_mutable()->get_ptr();
2559
0
            RETURN_IF_ERROR(variant_util::cast_column({original, file_column_type, ""},
2560
0
                                                      expected_type, &expected));
2561
0
            _current_return_columns[i] = expected->assume_mutable();
2562
0
            _converted_column_ids[i] = true;
2563
0
            VLOG_DEBUG << fmt::format(
2564
0
                    "Convert {} fom file column type {} to {}, num_rows {}",
2565
0
                    field_type->path() == nullptr ? "" : field_type->path()->get_path(),
2566
0
                    file_column_type->get_name(), expected_type->get_name(),
2567
0
                    _current_return_columns[i]->size());
2568
0
        }
2569
39.7k
    }
2570
23.1k
    return Status::OK();
2571
23.1k
}
2572
2573
Status SegmentIterator::copy_column_data_by_selector(IColumn* input_col_ptr,
2574
                                                     MutableColumnPtr& output_col,
2575
                                                     uint16_t* sel_rowid_idx, uint16_t select_size,
2576
2.83k
                                                     size_t batch_size) {
2577
2.83k
    if (output_col->is_nullable() != input_col_ptr->is_nullable()) {
2578
0
        LOG(WARNING) << "nullable mismatch for output_column: " << output_col->dump_structure()
2579
0
                     << " input_column: " << input_col_ptr->dump_structure()
2580
0
                     << " select_size: " << select_size;
2581
0
        return Status::RuntimeError("copy_column_data_by_selector nullable mismatch");
2582
0
    }
2583
2.83k
    output_col->reserve(select_size);
2584
2.83k
    return input_col_ptr->filter_by_selector(sel_rowid_idx, select_size, output_col.get());
2585
2.83k
}
2586
2587
23.1k
Status SegmentIterator::_next_batch_internal(Block* block) {
2588
23.1k
    SCOPED_CONCURRENCY_COUNT(ConcurrencyStatsManager::instance().segment_iterator_next_batch);
2589
2590
23.1k
    bool is_mem_reuse = block->mem_reuse();
2591
23.1k
    DCHECK(is_mem_reuse);
2592
2593
23.1k
    RETURN_IF_ERROR(_lazy_init(block));
2594
2595
23.1k
    SCOPED_RAW_TIMER(&_opts.stats->block_load_ns);
2596
2597
    // If the row bitmap size is smaller than nrows_read_limit, there's no need to reserve that many column rows.
2598
23.1k
    uint32_t nrows_read_limit =
2599
23.1k
            std::min(cast_set<uint32_t>(_row_bitmap.cardinality()), _opts.block_row_max);
2600
23.1k
    if (_can_opt_topn_reads()) {
2601
0
        nrows_read_limit = std::min(static_cast<uint32_t>(_opts.topn_limit), nrows_read_limit);
2602
0
    }
2603
23.1k
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_1", {
2604
23.1k
        if (nrows_read_limit != 1) {
2605
23.1k
            return Status::Error<ErrorCode::INTERNAL_ERROR>(
2606
23.1k
                    "topn opt 1 execute failed: nrows_read_limit={}, _opts.topn_limit={}",
2607
23.1k
                    nrows_read_limit, _opts.topn_limit);
2608
23.1k
        }
2609
23.1k
    })
2610
2611
23.1k
    RETURN_IF_ERROR(_init_current_block(block, _current_return_columns, nrows_read_limit));
2612
23.1k
    _converted_column_ids.assign(_schema->columns().size(), false);
2613
2614
23.1k
    _selected_size = 0;
2615
23.1k
    RETURN_IF_ERROR(_read_columns_by_index(nrows_read_limit, _selected_size));
2616
23.1k
    _replace_version_col_if_needed(_predicate_column_ids, _selected_size);
2617
2618
23.1k
    _opts.stats->blocks_load += 1;
2619
23.1k
    _opts.stats->raw_rows_read += _selected_size;
2620
2621
23.1k
    if (_selected_size == 0) {
2622
5.62k
        return _process_eof(block);
2623
5.62k
    }
2624
2625
17.5k
    if (_is_need_vec_eval || _is_need_short_eval || _is_need_expr_eval) {
2626
4.19k
        _sel_rowid_idx.resize(_selected_size);
2627
2628
4.19k
        if (_is_need_vec_eval || _is_need_short_eval) {
2629
4.19k
            _convert_dict_code_for_predicate_if_necessary();
2630
2631
            // step 1: evaluate vectorization predicate
2632
4.19k
            _selected_size =
2633
4.19k
                    _evaluate_vectorization_predicate(_sel_rowid_idx.data(), _selected_size);
2634
2635
            // step 2: evaluate short circuit predicate
2636
            // todo(wb) research whether need to read short predicate after vectorization evaluation
2637
            //          to reduce cost of read short circuit columns.
2638
            //          In SSB test, it make no difference; So need more scenarios to test
2639
4.19k
            _selected_size =
2640
4.19k
                    _evaluate_short_circuit_predicate(_sel_rowid_idx.data(), _selected_size);
2641
4.19k
            VLOG_DEBUG << fmt::format("After evaluate predicates, selected size: {} ",
2642
0
                                      _selected_size);
2643
4.19k
            if (_selected_size > 0) {
2644
                // step 3.1: output short circuit and predicate column
2645
                // when lazy materialization enables, _predicate_column_ids = distinct(_short_cir_pred_column_ids + _vec_pred_column_ids)
2646
                // see _vec_init_lazy_materialization
2647
                // todo(wb) need to tell input columnids from output columnids
2648
4.04k
                RETURN_IF_ERROR(_output_column_by_sel_idx(block, _predicate_column_ids,
2649
4.04k
                                                          _sel_rowid_idx.data(), _selected_size));
2650
2651
                // step 3.2: read remaining expr column and evaluate it.
2652
4.04k
                if (_is_need_expr_eval) {
2653
                    // The predicate column contains the remaining expr column, no need second read.
2654
0
                    if (_common_expr_column_ids.size() > 0) {
2655
0
                        SCOPED_RAW_TIMER(&_opts.stats->non_predicate_read_ns);
2656
0
                        RETURN_IF_ERROR(_read_columns_by_rowids(
2657
0
                                _common_expr_column_ids, _block_rowids, _sel_rowid_idx.data(),
2658
0
                                _selected_size, &_current_return_columns));
2659
0
                        _replace_version_col_if_needed(_common_expr_column_ids, _selected_size);
2660
0
                        RETURN_IF_ERROR(_process_columns(_common_expr_column_ids, block));
2661
0
                    }
2662
2663
0
                    DCHECK(block->columns() > _schema_block_id_map[*_common_expr_columns.begin()]);
2664
0
                    RETURN_IF_ERROR(
2665
0
                            _process_common_expr(_sel_rowid_idx.data(), _selected_size, block));
2666
0
                }
2667
4.04k
            } else {
2668
150
                _fill_column_nothing();
2669
150
                if (_is_need_expr_eval) {
2670
0
                    RETURN_IF_ERROR(_process_columns(_common_expr_column_ids, block));
2671
0
                }
2672
150
            }
2673
4.19k
        } else if (_is_need_expr_eval) {
2674
0
            DCHECK(!_predicate_column_ids.empty());
2675
0
            RETURN_IF_ERROR(_process_columns(_predicate_column_ids, block));
2676
            // first read all rows are insert block, initialize sel_rowid_idx to all rows.
2677
0
            for (uint16_t i = 0; i < _selected_size; ++i) {
2678
0
                _sel_rowid_idx[i] = i;
2679
0
            }
2680
0
            RETURN_IF_ERROR(_process_common_expr(_sel_rowid_idx.data(), _selected_size, block));
2681
0
        }
2682
2683
        // step4: read non_predicate column
2684
4.19k
        if (_selected_size > 0) {
2685
4.04k
            if (!_non_predicate_columns.empty()) {
2686
3.05k
                RETURN_IF_ERROR(_read_columns_by_rowids(
2687
3.05k
                        _non_predicate_columns, _block_rowids, _sel_rowid_idx.data(),
2688
3.05k
                        _selected_size, &_current_return_columns,
2689
3.05k
                        _opts.condition_cache_digest && !_find_condition_cache));
2690
3.05k
                _replace_version_col_if_needed(_non_predicate_columns, _selected_size);
2691
3.05k
            } else {
2692
995
                if (_opts.condition_cache_digest && !_find_condition_cache) {
2693
0
                    auto& condition_cache = *_condition_cache;
2694
0
                    for (size_t i = 0; i < _selected_size; ++i) {
2695
0
                        auto rowid = _block_rowids[_sel_rowid_idx[i]];
2696
0
                        condition_cache[rowid / SegmentIterator::CONDITION_CACHE_OFFSET] = true;
2697
0
                    }
2698
0
                }
2699
995
            }
2700
4.04k
        }
2701
4.19k
    }
2702
2703
    // step5: output columns
2704
17.5k
    RETURN_IF_ERROR(_output_non_pred_columns(block));
2705
    // Convert inverted index bitmaps to result columns for virtual column exprs
2706
    // (e.g., MATCH projections). This must run before _materialization_of_virtual_column
2707
    // so that fast_execute() can find the pre-computed result columns.
2708
17.5k
    if (!_virtual_column_exprs.empty()) {
2709
0
        bool use_sel = _is_need_vec_eval || _is_need_short_eval || _is_need_expr_eval;
2710
0
        uint16_t* sel_rowid_idx = use_sel ? _sel_rowid_idx.data() : nullptr;
2711
0
        std::vector<VExprContext*> vir_ctxs;
2712
0
        vir_ctxs.reserve(_virtual_column_exprs.size());
2713
0
        for (auto& [cid, ctx] : _virtual_column_exprs) {
2714
0
            vir_ctxs.push_back(ctx.get());
2715
0
        }
2716
0
        _output_index_result_column(vir_ctxs, sel_rowid_idx, _selected_size, block);
2717
0
    }
2718
17.5k
    RETURN_IF_ERROR(_materialization_of_virtual_column(block));
2719
    // shrink char_type suffix zero data
2720
17.5k
    block->shrink_char_type_column_suffix_zero(_char_type_idx);
2721
17.5k
    return _check_output_block(block);
2722
17.5k
}
2723
2724
0
Status SegmentIterator::_process_columns(const std::vector<ColumnId>& column_ids, Block* block) {
2725
0
    RETURN_IF_ERROR(_convert_to_expected_type(column_ids));
2726
0
    for (auto cid : column_ids) {
2727
0
        auto loc = _schema_block_id_map[cid];
2728
0
        block->replace_by_position(loc, std::move(_current_return_columns[cid]));
2729
0
    }
2730
0
    return Status::OK();
2731
0
}
2732
2733
150
void SegmentIterator::_fill_column_nothing() {
2734
    // If column_predicate filters out all rows, the corresponding column in _current_return_columns[cid] must be a ColumnNothing.
2735
    // Because:
2736
    // 1. Before each batch, _init_return_columns is called to initialize _current_return_columns, and virtual columns in _current_return_columns are initialized as ColumnNothing.
2737
    // 2. When select_size == 0, the read method of VirtualColumnIterator will definitely not be called, so the corresponding Column remains a ColumnNothing
2738
150
    for (const auto pair : _vir_cid_to_idx_in_block) {
2739
0
        auto cid = pair.first;
2740
0
        auto pos = pair.second;
2741
0
        const auto* nothing_col =
2742
0
                check_and_get_column<ColumnNothing>(_current_return_columns[cid].get());
2743
0
        DCHECK(nothing_col != nullptr)
2744
0
                << fmt::format("ColumnNothing expected, but got {}, cid: {}, pos: {}",
2745
0
                               _current_return_columns[cid]->get_name(), cid, pos);
2746
0
        _current_return_columns[cid] = _opts.vir_col_idx_to_type[pos]->create_column();
2747
0
    }
2748
150
}
2749
2750
17.5k
Status SegmentIterator::_check_output_block(Block* block) {
2751
17.5k
#ifndef NDEBUG
2752
17.5k
    size_t rows = block->rows();
2753
17.5k
    size_t idx = 0;
2754
30.5k
    for (const auto& entry : *block) {
2755
30.5k
        if (!entry.column) {
2756
0
            return Status::InternalError(
2757
0
                    "Column in idx {} is null, block columns {}, normal_columns {}, "
2758
0
                    "virtual_columns {}",
2759
0
                    idx, block->columns(), _schema->num_column_ids(), _virtual_column_exprs.size());
2760
30.5k
        } else if (check_and_get_column<ColumnNothing>(entry.column.get())) {
2761
0
            if (rows > 0) {
2762
0
                std::vector<std::string> vcid_to_idx;
2763
0
                for (const auto& pair : _vir_cid_to_idx_in_block) {
2764
0
                    vcid_to_idx.push_back(fmt::format("{}-{}", pair.first, pair.second));
2765
0
                }
2766
0
                std::string vir_cid_to_idx_in_block_msg =
2767
0
                        fmt::format("_vir_cid_to_idx_in_block:[{}]", fmt::join(vcid_to_idx, ","));
2768
0
                return Status::InternalError(
2769
0
                        "Column in idx {} is nothing, block columns {}, normal_columns {}, "
2770
0
                        "vir_cid_to_idx_in_block_msg {}",
2771
0
                        idx, block->columns(), _schema->num_column_ids(),
2772
0
                        vir_cid_to_idx_in_block_msg);
2773
0
            }
2774
30.5k
        } else if (entry.column->size() != rows) {
2775
0
            return Status::InternalError(
2776
0
                    "Unmatched size {}, expected {}, column: {}, type: {}, idx_in_block: {}, "
2777
0
                    "block: {}",
2778
0
                    entry.column->size(), rows, entry.column->get_name(), entry.type->get_name(),
2779
0
                    idx, block->dump_structure());
2780
0
        }
2781
30.5k
        idx++;
2782
30.5k
    }
2783
17.5k
#endif
2784
17.5k
    return Status::OK();
2785
17.5k
}
2786
2787
0
Status SegmentIterator::_process_column_predicate() {
2788
0
    return Status::OK();
2789
0
}
2790
2791
5.62k
Status SegmentIterator::_process_eof(Block* block) {
2792
    // Convert all columns in _current_return_columns to schema column
2793
5.62k
    RETURN_IF_ERROR(_convert_to_expected_type(_schema->column_ids()));
2794
18.0k
    for (int i = 0; i < block->columns(); i++) {
2795
12.4k
        auto cid = _schema->column_id(i);
2796
12.4k
        if (!_is_pred_column[cid]) {
2797
12.1k
            block->replace_by_position(i, std::move(_current_return_columns[cid]));
2798
12.1k
        }
2799
12.4k
    }
2800
5.62k
    block->clear_column_data();
2801
    // clear and release iterators memory footprint in advance
2802
5.62k
    _column_iterators.clear();
2803
5.62k
    _index_iterators.clear();
2804
5.62k
    return Status::EndOfFile("no more data in segment");
2805
5.62k
}
2806
2807
Status SegmentIterator::_process_common_expr(uint16_t* sel_rowid_idx, uint16_t& selected_size,
2808
0
                                             Block* block) {
2809
    // Here we just use col0 as row_number indicator. when reach here, we will calculate the predicates first.
2810
    //  then use the result to reduce our data read(that is, expr push down). there's now row in block means the first
2811
    //  column is not in common expr. so it's safe to replace it temporarily to provide correct `selected_size`.
2812
0
    VLOG_DEBUG << fmt::format("Execute common expr. block rows {}, selected size {}", block->rows(),
2813
0
                              _selected_size);
2814
2815
0
    bool need_mock_col = block->rows() != selected_size;
2816
0
    MutableColumnPtr col0;
2817
0
    if (need_mock_col) {
2818
0
        col0 = std::move(*block->get_by_position(0).column).mutate();
2819
0
        block->replace_by_position(
2820
0
                0, block->get_by_position(0).type->create_column_const_with_default_value(
2821
0
                           _selected_size));
2822
0
    }
2823
2824
0
    std::vector<VExprContext*> common_ctxs;
2825
0
    common_ctxs.reserve(_common_expr_ctxs_push_down.size());
2826
0
    for (auto& ctx : _common_expr_ctxs_push_down) {
2827
0
        common_ctxs.push_back(ctx.get());
2828
0
    }
2829
0
    _output_index_result_column(common_ctxs, _sel_rowid_idx.data(), _selected_size, block);
2830
0
    block->shrink_char_type_column_suffix_zero(_char_type_idx);
2831
0
    RETURN_IF_ERROR(_execute_common_expr(_sel_rowid_idx.data(), _selected_size, block));
2832
2833
0
    if (need_mock_col) {
2834
0
        block->replace_by_position(0, std::move(col0));
2835
0
    }
2836
2837
0
    VLOG_DEBUG << fmt::format("Execute common expr end. block rows {}, selected size {}",
2838
0
                              block->rows(), _selected_size);
2839
0
    return Status::OK();
2840
0
}
2841
2842
Status SegmentIterator::_execute_common_expr(uint16_t* sel_rowid_idx, uint16_t& selected_size,
2843
0
                                             Block* block) {
2844
0
    SCOPED_RAW_TIMER(&_opts.stats->expr_filter_ns);
2845
0
    DCHECK(!_remaining_conjunct_roots.empty());
2846
0
    DCHECK(block->rows() != 0);
2847
0
    int prev_columns = block->columns();
2848
0
    uint16_t original_size = selected_size;
2849
0
    _opts.stats->expr_cond_input_rows += original_size;
2850
2851
0
    IColumn::Filter filter;
2852
0
    RETURN_IF_ERROR(VExprContext::execute_conjuncts_and_filter_block(
2853
0
            _common_expr_ctxs_push_down, block, _columns_to_filter, prev_columns, filter));
2854
2855
0
    selected_size = _evaluate_common_expr_filter(sel_rowid_idx, selected_size, filter);
2856
0
    _opts.stats->rows_expr_cond_filtered += original_size - selected_size;
2857
0
    return Status::OK();
2858
0
}
2859
2860
uint16_t SegmentIterator::_evaluate_common_expr_filter(uint16_t* sel_rowid_idx,
2861
                                                       uint16_t selected_size,
2862
0
                                                       const IColumn::Filter& filter) {
2863
0
    size_t count = filter.size() - simd::count_zero_num((int8_t*)filter.data(), filter.size());
2864
0
    if (count == 0) {
2865
0
        return 0;
2866
0
    } else {
2867
0
        const UInt8* filt_pos = filter.data();
2868
2869
0
        uint16_t new_size = 0;
2870
0
        uint32_t sel_pos = 0;
2871
0
        const uint32_t sel_end = selected_size;
2872
0
        static constexpr size_t SIMD_BYTES = simd::bits_mask_length();
2873
0
        const uint32_t sel_end_simd = sel_pos + selected_size / SIMD_BYTES * SIMD_BYTES;
2874
2875
0
        while (sel_pos < sel_end_simd) {
2876
0
            auto mask = simd::bytes_mask_to_bits_mask(filt_pos + sel_pos);
2877
0
            if (0 == mask) {
2878
                //pass
2879
0
            } else if (simd::bits_mask_all() == mask) {
2880
0
                for (uint32_t i = 0; i < SIMD_BYTES; i++) {
2881
0
                    sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos + i];
2882
0
                }
2883
0
            } else {
2884
0
                simd::iterate_through_bits_mask(
2885
0
                        [&](const size_t bit_pos) {
2886
0
                            sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos + bit_pos];
2887
0
                        },
2888
0
                        mask);
2889
0
            }
2890
0
            sel_pos += SIMD_BYTES;
2891
0
        }
2892
2893
0
        for (; sel_pos < sel_end; sel_pos++) {
2894
0
            if (filt_pos[sel_pos]) {
2895
0
                sel_rowid_idx[new_size++] = sel_rowid_idx[sel_pos];
2896
0
            }
2897
0
        }
2898
0
        return new_size;
2899
0
    }
2900
0
}
2901
2902
void SegmentIterator::_output_index_result_column(const std::vector<VExprContext*>& expr_ctxs,
2903
                                                  uint16_t* sel_rowid_idx, uint16_t select_size,
2904
0
                                                  Block* block) {
2905
0
    SCOPED_RAW_TIMER(&_opts.stats->output_index_result_column_timer);
2906
0
    if (block->rows() == 0) {
2907
0
        return;
2908
0
    }
2909
0
    for (auto* expr_ctx_ptr : expr_ctxs) {
2910
0
        auto index_ctx = expr_ctx_ptr->get_index_context();
2911
0
        if (index_ctx == nullptr) {
2912
0
            continue;
2913
0
        }
2914
0
        for (auto& inverted_index_result_bitmap_for_expr : index_ctx->get_index_result_bitmap()) {
2915
0
            const auto* expr = inverted_index_result_bitmap_for_expr.first;
2916
0
            const auto& result_bitmap = inverted_index_result_bitmap_for_expr.second;
2917
0
            const auto& index_result_bitmap = result_bitmap.get_data_bitmap();
2918
0
            auto index_result_column = ColumnUInt8::create();
2919
0
            ColumnUInt8::Container& vec_match_pred = index_result_column->get_data();
2920
0
            vec_match_pred.resize(block->rows());
2921
0
            std::fill(vec_match_pred.begin(), vec_match_pred.end(), 0);
2922
2923
0
            const auto& null_bitmap = result_bitmap.get_null_bitmap();
2924
0
            bool has_null_bitmap = null_bitmap != nullptr && !null_bitmap->isEmpty();
2925
0
            bool expr_returns_nullable = expr->data_type()->is_nullable();
2926
2927
0
            ColumnUInt8::MutablePtr null_map_column = nullptr;
2928
0
            ColumnUInt8::Container* null_map_data = nullptr;
2929
0
            if (has_null_bitmap && expr_returns_nullable) {
2930
0
                null_map_column = ColumnUInt8::create();
2931
0
                auto& null_map_vec = null_map_column->get_data();
2932
0
                null_map_vec.resize(block->rows());
2933
0
                std::fill(null_map_vec.begin(), null_map_vec.end(), 0);
2934
0
                null_map_data = &null_map_column->get_data();
2935
0
            }
2936
2937
0
            roaring::BulkContext bulk_context;
2938
0
            for (uint32_t i = 0; i < select_size; i++) {
2939
0
                auto rowid = sel_rowid_idx ? _block_rowids[sel_rowid_idx[i]] : _block_rowids[i];
2940
0
                if (index_result_bitmap) {
2941
0
                    vec_match_pred[i] = index_result_bitmap->containsBulk(bulk_context, rowid);
2942
0
                }
2943
0
                if (null_map_data != nullptr && null_bitmap->contains(rowid)) {
2944
0
                    (*null_map_data)[i] = 1;
2945
0
                    vec_match_pred[i] = 0;
2946
0
                }
2947
0
            }
2948
2949
0
            DCHECK(block->rows() == vec_match_pred.size());
2950
2951
0
            if (null_map_column) {
2952
0
                index_ctx->set_index_result_column_for_expr(
2953
0
                        expr, ColumnNullable::create(std::move(index_result_column),
2954
0
                                                     std::move(null_map_column)));
2955
0
            } else {
2956
0
                index_ctx->set_index_result_column_for_expr(expr, std::move(index_result_column));
2957
0
            }
2958
0
        }
2959
0
    }
2960
0
}
2961
2962
4.19k
void SegmentIterator::_convert_dict_code_for_predicate_if_necessary() {
2963
4.19k
    for (auto predicate : _short_cir_eval_predicate) {
2964
0
        _convert_dict_code_for_predicate_if_necessary_impl(predicate);
2965
0
    }
2966
2967
4.19k
    for (auto predicate : _pre_eval_block_predicate) {
2968
0
        _convert_dict_code_for_predicate_if_necessary_impl(predicate);
2969
0
    }
2970
2971
4.19k
    for (auto column_id : _delete_range_column_ids) {
2972
4.05k
        _current_return_columns[column_id].get()->convert_dict_codes_if_necessary();
2973
4.05k
    }
2974
2975
4.19k
    for (auto column_id : _delete_bloom_filter_column_ids) {
2976
0
        _current_return_columns[column_id].get()->initialize_hash_values_for_runtime_filter();
2977
0
    }
2978
4.19k
}
2979
2980
void SegmentIterator::_convert_dict_code_for_predicate_if_necessary_impl(
2981
0
        std::shared_ptr<ColumnPredicate> predicate) {
2982
0
    auto& column = _current_return_columns[predicate->column_id()];
2983
0
    auto* col_ptr = column.get();
2984
2985
0
    if (PredicateTypeTraits::is_range(predicate->type())) {
2986
0
        col_ptr->convert_dict_codes_if_necessary();
2987
0
    } else if (PredicateTypeTraits::is_bloom_filter(predicate->type())) {
2988
0
        col_ptr->initialize_hash_values_for_runtime_filter();
2989
0
    }
2990
0
}
2991
2992
7.19k
Status SegmentIterator::current_block_row_locations(std::vector<RowLocation>* block_row_locations) {
2993
7.19k
    DCHECK(_opts.record_rowids);
2994
7.19k
    DCHECK_GE(_block_rowids.size(), _selected_size);
2995
7.19k
    block_row_locations->resize(_selected_size);
2996
7.19k
    uint32_t sid = segment_id();
2997
7.19k
    if (!_is_need_vec_eval && !_is_need_short_eval && !_is_need_expr_eval) {
2998
4.24M
        for (auto i = 0; i < _selected_size; i++) {
2999
4.23M
            (*block_row_locations)[i] = RowLocation(sid, _block_rowids[i]);
3000
4.23M
        }
3001
4.46k
    } else {
3002
2.46M
        for (auto i = 0; i < _selected_size; i++) {
3003
2.46M
            (*block_row_locations)[i] = RowLocation(sid, _block_rowids[_sel_rowid_idx[i]]);
3004
2.46M
        }
3005
2.73k
    }
3006
7.19k
    return Status::OK();
3007
7.19k
}
3008
3009
5.63k
Status SegmentIterator::_construct_compound_expr_context() {
3010
5.63k
    ColumnIteratorOptions iter_opts {
3011
5.63k
            .use_page_cache = _opts.use_page_cache,
3012
5.63k
            .file_reader = _file_reader.get(),
3013
5.63k
            .stats = _opts.stats,
3014
5.63k
            .io_ctx = _opts.io_ctx,
3015
5.63k
    };
3016
5.63k
    auto inverted_index_context = std::make_shared<IndexExecContext>(
3017
5.63k
            _schema->column_ids(), _index_iterators, _storage_name_and_type,
3018
5.63k
            _common_expr_index_exec_status, _score_runtime, _segment.get(), iter_opts);
3019
5.63k
    inverted_index_context->set_index_query_context(_index_query_context);
3020
5.63k
    for (const auto& expr_ctx : _opts.common_expr_ctxs_push_down) {
3021
0
        VExprContextSPtr context;
3022
        // _ann_range_search_runtime will do deep copy.
3023
0
        RETURN_IF_ERROR(expr_ctx->clone(_opts.runtime_state, context));
3024
0
        context->set_index_context(inverted_index_context);
3025
0
        _common_expr_ctxs_push_down.emplace_back(context);
3026
0
    }
3027
    // Clone virtual column exprs before setting IndexExecContext, because
3028
    // IndexExecContext holds segment-specific index iterator references.
3029
    // Without cloning, shared VExprContext would be overwritten per-segment
3030
    // and could point to the wrong segment's context.
3031
5.63k
    for (auto& [cid, expr_ctx] : _virtual_column_exprs) {
3032
0
        VExprContextSPtr context;
3033
0
        RETURN_IF_ERROR(expr_ctx->clone(_opts.runtime_state, context));
3034
0
        context->set_index_context(inverted_index_context);
3035
0
        expr_ctx = context;
3036
0
    }
3037
5.63k
    return Status::OK();
3038
5.63k
}
3039
3040
5.63k
void SegmentIterator::_calculate_expr_in_remaining_conjunct_root() {
3041
5.63k
    for (const auto& root_expr_ctx : _common_expr_ctxs_push_down) {
3042
0
        const auto& root_expr = root_expr_ctx->root();
3043
0
        if (root_expr == nullptr) {
3044
0
            continue;
3045
0
        }
3046
0
        _common_expr_to_slotref_map[root_expr_ctx.get()] = std::unordered_map<ColumnId, VExpr*>();
3047
3048
0
        std::stack<VExprSPtr> stack;
3049
0
        stack.emplace(root_expr);
3050
3051
0
        while (!stack.empty()) {
3052
0
            const auto& expr = stack.top();
3053
0
            stack.pop();
3054
3055
0
            for (const auto& child : expr->children()) {
3056
0
                if (child->is_virtual_slot_ref()) {
3057
                    // Expand virtual slot ref to its underlying expression tree and
3058
                    // collect real slot refs used inside. We still associate those
3059
                    // slot refs with the current parent expr node for inverted index
3060
                    // tracking, just like normal slot refs.
3061
0
                    auto* vir_slot_ref = assert_cast<VirtualSlotRef*>(child.get());
3062
0
                    auto vir_expr = vir_slot_ref->get_virtual_column_expr();
3063
0
                    if (vir_expr) {
3064
0
                        std::stack<VExprSPtr> vir_stack;
3065
0
                        vir_stack.emplace(vir_expr);
3066
3067
0
                        while (!vir_stack.empty()) {
3068
0
                            const auto& vir_node = vir_stack.top();
3069
0
                            vir_stack.pop();
3070
3071
0
                            for (const auto& vir_child : vir_node->children()) {
3072
0
                                if (vir_child->is_slot_ref()) {
3073
0
                                    auto* inner_slot_ref = assert_cast<VSlotRef*>(vir_child.get());
3074
0
                                    _common_expr_index_exec_status[_schema->column_id(
3075
0
                                            inner_slot_ref->column_id())][expr.get()] = false;
3076
0
                                    _common_expr_to_slotref_map[root_expr_ctx.get()]
3077
0
                                                               [inner_slot_ref->column_id()] =
3078
0
                                                                       expr.get();
3079
0
                                }
3080
3081
0
                                if (!vir_child->children().empty()) {
3082
0
                                    vir_stack.emplace(vir_child);
3083
0
                                }
3084
0
                            }
3085
0
                        }
3086
0
                    }
3087
0
                }
3088
                // Example: CAST(v['a'] AS VARCHAR) MATCH 'hello', do not add CAST expr to index tracking.
3089
0
                auto expr_without_cast = VExpr::expr_without_cast(child);
3090
0
                if (expr_without_cast->is_slot_ref() && expr->op() != TExprOpcode::CAST) {
3091
0
                    auto* column_slot_ref = assert_cast<VSlotRef*>(expr_without_cast.get());
3092
0
                    _common_expr_index_exec_status[_schema->column_id(column_slot_ref->column_id())]
3093
0
                                                  [expr.get()] = false;
3094
0
                    _common_expr_to_slotref_map[root_expr_ctx.get()][column_slot_ref->column_id()] =
3095
0
                            expr.get();
3096
0
                }
3097
0
            }
3098
3099
0
            const auto& children = expr->children();
3100
0
            for (int i = cast_set<int>(children.size()) - 1; i >= 0; --i) {
3101
0
                if (!children[i]->children().empty()) {
3102
0
                    stack.emplace(children[i]);
3103
0
                }
3104
0
            }
3105
0
        }
3106
0
    }
3107
5.63k
}
3108
3109
bool SegmentIterator::_no_need_read_key_data(ColumnId cid, MutableColumnPtr& column,
3110
43.4k
                                             size_t nrows_read) {
3111
43.4k
    if (_opts.runtime_state && !_opts.runtime_state->query_options().enable_no_need_read_data_opt) {
3112
0
        return false;
3113
0
    }
3114
3115
43.4k
    if (!((_opts.tablet_schema->keys_type() == KeysType::DUP_KEYS ||
3116
43.4k
           (_opts.tablet_schema->keys_type() == KeysType::UNIQUE_KEYS &&
3117
16.3k
            _opts.enable_unique_key_merge_on_write)))) {
3118
12.0k
        return false;
3119
12.0k
    }
3120
3121
31.3k
    if (_opts.push_down_agg_type_opt != TPushAggOp::COUNT_ON_INDEX) {
3122
31.3k
        return false;
3123
31.3k
    }
3124
3125
0
    if (!_opts.tablet_schema->column(cid).is_key()) {
3126
0
        return false;
3127
0
    }
3128
3129
0
    if (_has_delete_predicate(cid)) {
3130
0
        return false;
3131
0
    }
3132
3133
0
    if (!_check_all_conditions_passed_inverted_index_for_column(cid)) {
3134
0
        return false;
3135
0
    }
3136
3137
0
    if (column->is_nullable()) {
3138
0
        auto* nullable_col_ptr = reinterpret_cast<ColumnNullable*>(column.get());
3139
0
        nullable_col_ptr->get_null_map_column().insert_many_defaults(nrows_read);
3140
0
        nullable_col_ptr->get_nested_column_ptr()->insert_many_defaults(nrows_read);
3141
0
    } else {
3142
0
        column->insert_many_defaults(nrows_read);
3143
0
    }
3144
3145
0
    return true;
3146
0
}
3147
3148
31.3k
bool SegmentIterator::_has_delete_predicate(ColumnId cid) {
3149
31.3k
    std::set<uint32_t> delete_columns_set;
3150
31.3k
    _opts.delete_condition_predicates->get_all_column_ids(delete_columns_set);
3151
31.3k
    return delete_columns_set.contains(cid);
3152
31.3k
}
3153
3154
23.1k
bool SegmentIterator::_can_opt_topn_reads() {
3155
23.1k
    if (_opts.topn_limit <= 0) {
3156
23.1k
        return false;
3157
23.1k
    }
3158
3159
0
    if (_opts.delete_condition_predicates->num_of_column_predicate() > 0) {
3160
0
        return false;
3161
0
    }
3162
3163
0
    bool all_true = std::ranges::all_of(_schema->column_ids(), [this](auto cid) {
3164
0
        if (cid == _opts.tablet_schema->delete_sign_idx()) {
3165
0
            return true;
3166
0
        }
3167
0
        if (_check_all_conditions_passed_inverted_index_for_column(cid, true)) {
3168
0
            return true;
3169
0
        }
3170
0
        return false;
3171
0
    });
3172
3173
0
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_1", {
3174
0
        LOG(INFO) << "col_predicates: " << _col_predicates.size() << ", all_true: " << all_true;
3175
0
    })
3176
3177
0
    DBUG_EXECUTE_IF("segment_iterator.topn_opt_2", {
3178
0
        if (all_true) {
3179
0
            return Status::Error<ErrorCode::INTERNAL_ERROR>("topn opt 2 execute failed");
3180
0
        }
3181
0
    })
3182
3183
0
    return all_true;
3184
0
}
3185
3186
// Before get next batch. make sure all virtual columns in block has type ColumnNothing.
3187
23.1k
void SegmentIterator::_init_virtual_columns(Block* block) {
3188
23.1k
    for (const auto& pair : _vir_cid_to_idx_in_block) {
3189
0
        auto& col_with_type_and_name = block->get_by_position(pair.second);
3190
0
        col_with_type_and_name.column = ColumnNothing::create(0);
3191
0
        col_with_type_and_name.type = _opts.vir_col_idx_to_type[pair.second];
3192
0
    }
3193
23.1k
}
3194
3195
17.5k
Status SegmentIterator::_materialization_of_virtual_column(Block* block) {
3196
17.5k
    size_t prev_block_columns = block->columns();
3197
    // Some expr can not process empty block, such as function `element_at`.
3198
    // So materialize virtual column in advance to avoid errors.
3199
17.5k
    if (block->rows() == 0) {
3200
150
        for (const auto& pair : _vir_cid_to_idx_in_block) {
3201
0
            auto& col_with_type_and_name = block->get_by_position(pair.second);
3202
0
            col_with_type_and_name.column = _opts.vir_col_idx_to_type[pair.second]->create_column();
3203
0
            col_with_type_and_name.type = _opts.vir_col_idx_to_type[pair.second];
3204
0
        }
3205
150
        return Status::OK();
3206
150
    }
3207
3208
17.3k
    for (const auto& cid_and_expr : _virtual_column_exprs) {
3209
0
        auto cid = cid_and_expr.first;
3210
0
        auto column_expr = cid_and_expr.second;
3211
0
        size_t idx_in_block = _vir_cid_to_idx_in_block[cid];
3212
0
        if (block->columns() <= idx_in_block) {
3213
0
            return Status::InternalError(
3214
0
                    "Virtual column index {} is out of range, block columns {}, "
3215
0
                    "virtual columns size {}, virtual column expr {}",
3216
0
                    idx_in_block, block->columns(), _vir_cid_to_idx_in_block.size(),
3217
0
                    column_expr->root()->debug_string());
3218
0
        } else if (block->get_by_position(idx_in_block).column.get() == nullptr) {
3219
0
            return Status::InternalError(
3220
0
                    "Virtual column index {} is null, block columns {}, virtual columns size {}, "
3221
0
                    "virtual column expr {}",
3222
0
                    idx_in_block, block->columns(), _vir_cid_to_idx_in_block.size(),
3223
0
                    column_expr->root()->debug_string());
3224
0
        }
3225
0
        block->shrink_char_type_column_suffix_zero(_char_type_idx);
3226
0
        if (check_and_get_column<const ColumnNothing>(
3227
0
                    block->get_by_position(idx_in_block).column.get())) {
3228
0
            VLOG_DEBUG << fmt::format("Virtual column is doing materialization, cid {}, col idx {}",
3229
0
                                      cid, idx_in_block);
3230
0
            int result_cid = -1;
3231
0
            RETURN_IF_ERROR(column_expr->execute(block, &result_cid));
3232
3233
0
            block->replace_by_position(idx_in_block,
3234
0
                                       std::move(block->get_by_position(result_cid).column));
3235
0
            if (block->get_by_position(idx_in_block).column->size() == 0) {
3236
0
                LOG_WARNING(
3237
0
                        "Result of expr column {} is empty. cid {}, idx_in_block {}, result_cid",
3238
0
                        column_expr->root()->debug_string(), cid, idx_in_block, result_cid);
3239
0
            }
3240
0
        }
3241
0
    }
3242
    // During execution of expr, some columns may be added to the end of the block.
3243
    // Remove them to keep consistent with current block.
3244
17.3k
    block->erase_tail(prev_block_columns);
3245
17.3k
    return Status::OK();
3246
17.3k
}
3247
3248
5.63k
void SegmentIterator::_prepare_score_column_materialization() {
3249
5.63k
    if (_score_runtime == nullptr) {
3250
5.63k
        return;
3251
5.63k
    }
3252
3253
0
    ScoreRangeFilterPtr filter;
3254
0
    if (_score_runtime->has_score_range_filter()) {
3255
0
        const auto& range_info = _score_runtime->get_score_range_info();
3256
0
        filter = std::make_shared<ScoreRangeFilter>(range_info->op, range_info->threshold);
3257
0
    }
3258
3259
0
    IColumn::MutablePtr result_column;
3260
0
    auto result_row_ids = std::make_unique<std::vector<uint64_t>>();
3261
0
    if (_score_runtime->get_limit() > 0 && _col_predicates.empty() &&
3262
0
        _common_expr_ctxs_push_down.empty()) {
3263
0
        OrderType order_type = _score_runtime->is_asc() ? OrderType::ASC : OrderType::DESC;
3264
0
        _index_query_context->collection_similarity->get_topn_bm25_scores(
3265
0
                &_row_bitmap, result_column, result_row_ids, order_type,
3266
0
                _score_runtime->get_limit(), filter);
3267
0
    } else {
3268
0
        _index_query_context->collection_similarity->get_bm25_scores(&_row_bitmap, result_column,
3269
0
                                                                     result_row_ids, filter);
3270
0
    }
3271
0
    const size_t dst_col_idx = _score_runtime->get_dest_column_idx();
3272
0
    auto* column_iter = _column_iterators[_schema->column_id(dst_col_idx)].get();
3273
0
    auto* virtual_column_iter = dynamic_cast<VirtualColumnIterator*>(column_iter);
3274
0
    virtual_column_iter->prepare_materialization(std::move(result_column),
3275
0
                                                 std::move(result_row_ids));
3276
0
}
3277
3278
} // namespace segment_v2
3279
} // namespace doris