Coverage Report

Created: 2026-05-13 14:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/format/parquet/vparquet_reader.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 "format/parquet/vparquet_reader.h"
19
20
#include <gen_cpp/Metrics_types.h>
21
#include <gen_cpp/PlanNodes_types.h>
22
#include <gen_cpp/parquet_types.h>
23
#include <glog/logging.h>
24
25
#include <algorithm>
26
#include <functional>
27
#include <sstream>
28
#include <utility>
29
30
#include "common/config.h"
31
#include "common/status.h"
32
#include "core/block/block.h"
33
#include "core/block/column_with_type_and_name.h"
34
#include "core/column/column.h"
35
#include "core/data_type/define_primitive_type.h"
36
#include "core/typeid_cast.h"
37
#include "core/types.h"
38
#include "exec/scan/file_scanner.h"
39
#include "exprs/vbloom_predicate.h"
40
#include "exprs/vdirect_in_predicate.h"
41
#include "exprs/vexpr.h"
42
#include "exprs/vexpr_context.h"
43
#include "exprs/vin_predicate.h"
44
#include "exprs/vruntimefilter_wrapper.h"
45
#include "exprs/vslot_ref.h"
46
#include "exprs/vtopn_pred.h"
47
#include "format/column_type_convert.h"
48
#include "format/parquet/parquet_block_split_bloom_filter.h"
49
#include "format/parquet/parquet_common.h"
50
#include "format/parquet/parquet_predicate.h"
51
#include "format/parquet/parquet_thrift_util.h"
52
#include "format/parquet/schema_desc.h"
53
#include "format/parquet/vparquet_file_metadata.h"
54
#include "format/parquet/vparquet_group_reader.h"
55
#include "format/parquet/vparquet_page_index.h"
56
#include "format/table/hive/hive_parquet_nested_column_utils.h"
57
#include "format/table/nested_column_access_helper.h"
58
#include "information_schema/schema_scanner.h"
59
#include "io/file_factory.h"
60
#include "io/fs/buffered_reader.h"
61
#include "io/fs/file_reader.h"
62
#include "io/fs/file_reader_writer_fwd.h"
63
#include "io/fs/tracing_file_reader.h"
64
#include "runtime/descriptors.h"
65
#include "util/slice.h"
66
#include "util/string_util.h"
67
#include "util/timezone_utils.h"
68
69
namespace cctz {
70
class time_zone;
71
} // namespace cctz
72
namespace doris {
73
class RowDescriptor;
74
class RuntimeState;
75
class SlotDescriptor;
76
class TupleDescriptor;
77
namespace io {
78
struct IOContext;
79
enum class FileCachePolicy : uint8_t;
80
} // namespace io
81
class Block;
82
} // namespace doris
83
84
namespace doris {
85
86
ParquetReader::ParquetReader(RuntimeProfile* profile, const TFileScanRangeParams& params,
87
                             const TFileRangeDesc& range, size_t batch_size,
88
                             const cctz::time_zone* ctz, io::IOContext* io_ctx, RuntimeState* state,
89
                             FileMetaCache* meta_cache, bool enable_lazy_mat)
90
98
        : _profile(profile),
91
98
          _scan_params(params),
92
98
          _scan_range(range),
93
98
          _batch_size(std::max(batch_size, 1UL)),
94
98
          _range_start_offset(range.start_offset),
95
98
          _range_size(range.size),
96
98
          _ctz(ctz),
97
98
          _io_ctx(io_ctx),
98
98
          _state(state),
99
98
          _enable_lazy_mat(enable_lazy_mat),
100
          _enable_filter_by_min_max(
101
98
                  state == nullptr ? true
102
98
                                   : state->query_options().enable_parquet_filter_by_min_max),
103
          _enable_filter_by_bloom_filter(
104
98
                  state == nullptr ? true
105
98
                                   : state->query_options().enable_parquet_filter_by_bloom_filter) {
106
98
    _meta_cache = meta_cache;
107
98
    _init_profile();
108
98
    _init_system_properties();
109
98
    _init_file_description();
110
98
}
111
112
0
void ParquetReader::set_batch_size(size_t batch_size) {
113
0
    if (_batch_size == batch_size) {
114
0
        return;
115
0
    }
116
0
    _batch_size = batch_size;
117
0
}
118
119
ParquetReader::ParquetReader(RuntimeProfile* profile, const TFileScanRangeParams& params,
120
                             const TFileRangeDesc& range, size_t batch_size,
121
                             const cctz::time_zone* ctz,
122
                             std::shared_ptr<io::IOContext> io_ctx_holder, RuntimeState* state,
123
                             FileMetaCache* meta_cache, bool enable_lazy_mat)
124
0
        : _profile(profile),
125
0
          _scan_params(params),
126
0
          _scan_range(range),
127
0
          _batch_size(std::max(batch_size, 1UL)),
128
0
          _range_start_offset(range.start_offset),
129
0
          _range_size(range.size),
130
0
          _ctz(ctz),
131
0
          _io_ctx(io_ctx_holder ? io_ctx_holder.get() : nullptr),
132
0
          _io_ctx_holder(std::move(io_ctx_holder)),
133
0
          _state(state),
134
0
          _enable_lazy_mat(enable_lazy_mat),
135
          _enable_filter_by_min_max(
136
0
                  state == nullptr ? true
137
0
                                   : state->query_options().enable_parquet_filter_by_min_max),
138
          _enable_filter_by_bloom_filter(
139
0
                  state == nullptr ? true
140
0
                                   : state->query_options().enable_parquet_filter_by_bloom_filter) {
141
0
    _meta_cache = meta_cache;
142
0
    _init_profile();
143
0
    _init_system_properties();
144
0
    _init_file_description();
145
0
}
146
147
ParquetReader::ParquetReader(const TFileScanRangeParams& params, const TFileRangeDesc& range,
148
                             io::IOContext* io_ctx, RuntimeState* state, FileMetaCache* meta_cache,
149
                             bool enable_lazy_mat)
150
5
        : _profile(nullptr),
151
5
          _scan_params(params),
152
5
          _scan_range(range),
153
5
          _io_ctx(io_ctx),
154
5
          _state(state),
155
5
          _enable_lazy_mat(enable_lazy_mat),
156
          _enable_filter_by_min_max(
157
5
                  state == nullptr ? true
158
5
                                   : state->query_options().enable_parquet_filter_by_min_max),
159
          _enable_filter_by_bloom_filter(
160
5
                  state == nullptr ? true
161
5
                                   : state->query_options().enable_parquet_filter_by_bloom_filter) {
162
5
    _meta_cache = meta_cache;
163
5
    _init_system_properties();
164
5
    _init_file_description();
165
5
}
166
167
ParquetReader::ParquetReader(const TFileScanRangeParams& params, const TFileRangeDesc& range,
168
                             std::shared_ptr<io::IOContext> io_ctx_holder, RuntimeState* state,
169
                             FileMetaCache* meta_cache, bool enable_lazy_mat)
170
0
        : _profile(nullptr),
171
0
          _scan_params(params),
172
0
          _scan_range(range),
173
0
          _io_ctx(io_ctx_holder ? io_ctx_holder.get() : nullptr),
174
0
          _io_ctx_holder(std::move(io_ctx_holder)),
175
0
          _state(state),
176
0
          _enable_lazy_mat(enable_lazy_mat),
177
          _enable_filter_by_min_max(
178
0
                  state == nullptr ? true
179
0
                                   : state->query_options().enable_parquet_filter_by_min_max),
180
          _enable_filter_by_bloom_filter(
181
0
                  state == nullptr ? true
182
0
                                   : state->query_options().enable_parquet_filter_by_bloom_filter) {
183
0
    _meta_cache = meta_cache;
184
0
    _init_system_properties();
185
0
    _init_file_description();
186
0
}
187
188
103
ParquetReader::~ParquetReader() {
189
103
    _close_internal();
190
103
}
191
192
#ifdef BE_TEST
193
// for unit test
194
69
void ParquetReader::set_file_reader(io::FileReaderSPtr file_reader) {
195
69
    _file_reader = file_reader;
196
69
    _tracing_file_reader = file_reader;
197
69
}
198
#endif
199
200
98
void ParquetReader::_init_profile() {
201
98
    if (_profile != nullptr) {
202
50
        static const char* parquet_profile = "ParquetReader";
203
50
        ADD_TIMER_WITH_LEVEL(_profile, parquet_profile, 1);
204
205
50
        _parquet_profile.filtered_row_groups = ADD_CHILD_COUNTER_WITH_LEVEL(
206
50
                _profile, "RowGroupsFiltered", TUnit::UNIT, parquet_profile, 1);
207
50
        _parquet_profile.filtered_row_groups_by_min_max = ADD_CHILD_COUNTER_WITH_LEVEL(
208
50
                _profile, "RowGroupsFilteredByMinMax", TUnit::UNIT, parquet_profile, 1);
209
50
        _parquet_profile.filtered_row_groups_by_bloom_filter = ADD_CHILD_COUNTER_WITH_LEVEL(
210
50
                _profile, "RowGroupsFilteredByBloomFilter", TUnit::UNIT, parquet_profile, 1);
211
50
        _parquet_profile.to_read_row_groups = ADD_CHILD_COUNTER_WITH_LEVEL(
212
50
                _profile, "RowGroupsReadNum", TUnit::UNIT, parquet_profile, 1);
213
50
        _parquet_profile.total_row_groups = ADD_CHILD_COUNTER_WITH_LEVEL(
214
50
                _profile, "RowGroupsTotalNum", TUnit::UNIT, parquet_profile, 1);
215
50
        _parquet_profile.filtered_group_rows = ADD_CHILD_COUNTER_WITH_LEVEL(
216
50
                _profile, "FilteredRowsByGroup", TUnit::UNIT, parquet_profile, 1);
217
50
        _parquet_profile.filtered_page_rows = ADD_CHILD_COUNTER_WITH_LEVEL(
218
50
                _profile, "FilteredRowsByPage", TUnit::UNIT, parquet_profile, 1);
219
50
        _parquet_profile.lazy_read_filtered_rows = ADD_CHILD_COUNTER_WITH_LEVEL(
220
50
                _profile, "FilteredRowsByLazyRead", TUnit::UNIT, parquet_profile, 1);
221
50
        _parquet_profile.filtered_bytes = ADD_CHILD_COUNTER_WITH_LEVEL(
222
50
                _profile, "FilteredBytes", TUnit::BYTES, parquet_profile, 1);
223
50
        _parquet_profile.raw_rows_read = ADD_CHILD_COUNTER_WITH_LEVEL(
224
50
                _profile, "RawRowsRead", TUnit::UNIT, parquet_profile, 1);
225
50
        _parquet_profile.column_read_time =
226
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "ColumnReadTime", parquet_profile, 1);
227
50
        _parquet_profile.parse_meta_time =
228
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "ParseMetaTime", parquet_profile, 1);
229
50
        _parquet_profile.parse_footer_time =
230
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "ParseFooterTime", parquet_profile, 1);
231
50
        _parquet_profile.file_reader_create_time =
232
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "FileReaderCreateTime", parquet_profile, 1);
233
50
        _parquet_profile.open_file_num =
234
50
                ADD_CHILD_COUNTER_WITH_LEVEL(_profile, "FileNum", TUnit::UNIT, parquet_profile, 1);
235
50
        _parquet_profile.page_index_read_calls =
236
50
                ADD_COUNTER_WITH_LEVEL(_profile, "PageIndexReadCalls", TUnit::UNIT, 1);
237
50
        _parquet_profile.page_index_filter_time =
238
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "PageIndexFilterTime", parquet_profile, 1);
239
50
        _parquet_profile.read_page_index_time =
240
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "PageIndexReadTime", parquet_profile, 1);
241
50
        _parquet_profile.parse_page_index_time =
242
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "PageIndexParseTime", parquet_profile, 1);
243
50
        _parquet_profile.row_group_filter_time =
244
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "RowGroupFilterTime", parquet_profile, 1);
245
50
        _parquet_profile.file_footer_read_calls =
246
50
                ADD_COUNTER_WITH_LEVEL(_profile, "FileFooterReadCalls", TUnit::UNIT, 1);
247
50
        _parquet_profile.file_footer_hit_cache =
248
50
                ADD_COUNTER_WITH_LEVEL(_profile, "FileFooterHitCache", TUnit::UNIT, 1);
249
50
        _parquet_profile.decompress_time =
250
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "DecompressTime", parquet_profile, 1);
251
50
        _parquet_profile.decompress_cnt = ADD_CHILD_COUNTER_WITH_LEVEL(
252
50
                _profile, "DecompressCount", TUnit::UNIT, parquet_profile, 1);
253
50
        _parquet_profile.page_read_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
254
50
                _profile, "PageReadCount", TUnit::UNIT, parquet_profile, 1);
255
50
        _parquet_profile.page_cache_write_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
256
50
                _profile, "PageCacheWriteCount", TUnit::UNIT, parquet_profile, 1);
257
50
        _parquet_profile.page_cache_compressed_write_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
258
50
                _profile, "PageCacheCompressedWriteCount", TUnit::UNIT, parquet_profile, 1);
259
50
        _parquet_profile.page_cache_decompressed_write_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
260
50
                _profile, "PageCacheDecompressedWriteCount", TUnit::UNIT, parquet_profile, 1);
261
50
        _parquet_profile.page_cache_hit_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
262
50
                _profile, "PageCacheHitCount", TUnit::UNIT, parquet_profile, 1);
263
50
        _parquet_profile.page_cache_missing_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
264
50
                _profile, "PageCacheMissingCount", TUnit::UNIT, parquet_profile, 1);
265
50
        _parquet_profile.page_cache_compressed_hit_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
266
50
                _profile, "PageCacheCompressedHitCount", TUnit::UNIT, parquet_profile, 1);
267
50
        _parquet_profile.page_cache_decompressed_hit_counter = ADD_CHILD_COUNTER_WITH_LEVEL(
268
50
                _profile, "PageCacheDecompressedHitCount", TUnit::UNIT, parquet_profile, 1);
269
50
        _parquet_profile.decode_header_time =
270
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "PageHeaderDecodeTime", parquet_profile, 1);
271
50
        _parquet_profile.read_page_header_time =
272
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "PageHeaderReadTime", parquet_profile, 1);
273
50
        _parquet_profile.decode_value_time =
274
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "DecodeValueTime", parquet_profile, 1);
275
50
        _parquet_profile.decode_dict_time =
276
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "DecodeDictTime", parquet_profile, 1);
277
50
        _parquet_profile.decode_level_time =
278
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "DecodeLevelTime", parquet_profile, 1);
279
50
        _parquet_profile.decode_null_map_time =
280
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "DecodeNullMapTime", parquet_profile, 1);
281
50
        _parquet_profile.skip_page_header_num = ADD_CHILD_COUNTER_WITH_LEVEL(
282
50
                _profile, "SkipPageHeaderNum", TUnit::UNIT, parquet_profile, 1);
283
50
        _parquet_profile.parse_page_header_num = ADD_CHILD_COUNTER_WITH_LEVEL(
284
50
                _profile, "ParsePageHeaderNum", TUnit::UNIT, parquet_profile, 1);
285
50
        _parquet_profile.predicate_filter_time =
286
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "PredicateFilterTime", parquet_profile, 1);
287
50
        _parquet_profile.dict_filter_rewrite_time =
288
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "DictFilterRewriteTime", parquet_profile, 1);
289
50
        _parquet_profile.convert_time =
290
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "ConvertTime", parquet_profile, 1);
291
50
        _parquet_profile.bloom_filter_read_time =
292
50
                ADD_CHILD_TIMER_WITH_LEVEL(_profile, "BloomFilterReadTime", parquet_profile, 1);
293
50
    }
294
98
}
295
296
14
Status ParquetReader::close() {
297
14
    _close_internal();
298
14
    return Status::OK();
299
14
}
300
301
117
void ParquetReader::_close_internal() {
302
117
    if (!_closed) {
303
103
        _closed = true;
304
103
    }
305
117
}
306
307
106
Status ParquetReader::_open_file() {
308
106
    if (UNLIKELY(_io_ctx && _io_ctx->should_stop)) {
309
0
        return Status::EndOfFile("stop");
310
0
    }
311
106
    if (_file_reader == nullptr) {
312
15
        SCOPED_RAW_TIMER(&_reader_statistics.file_reader_create_time);
313
15
        ++_reader_statistics.open_file_num;
314
15
        _file_description.mtime =
315
15
                _scan_range.__isset.modification_time ? _scan_range.modification_time : 0;
316
15
        io::FileReaderOptions reader_options =
317
15
                FileFactory::get_reader_options(_state, _file_description);
318
15
        _file_reader = DORIS_TRY(io::DelegateReader::create_file_reader(
319
15
                _profile, _system_properties, _file_description, reader_options,
320
15
                io::DelegateReader::AccessMode::RANDOM, _io_ctx));
321
15
        _tracing_file_reader = _io_ctx ? std::make_shared<io::TracingFileReader>(
322
15
                                                 _file_reader, _io_ctx->file_reader_stats)
323
15
                                       : _file_reader;
324
15
    }
325
326
106
    if (_file_metadata == nullptr) {
327
84
        SCOPED_RAW_TIMER(&_reader_statistics.parse_footer_time);
328
84
        if (_tracing_file_reader->size() <= sizeof(PARQUET_VERSION_NUMBER)) {
329
            // Some system may generate parquet file with only 4 bytes: PAR1
330
            // Should consider it as empty file.
331
0
            return Status::EndOfFile("open file failed, empty parquet file {} with size: {}",
332
0
                                     _scan_range.path, _tracing_file_reader->size());
333
0
        }
334
84
        size_t meta_size = 0;
335
84
        bool enable_mapping_varbinary = _scan_params.__isset.enable_mapping_varbinary
336
84
                                                ? _scan_params.enable_mapping_varbinary
337
84
                                                : false;
338
84
        bool enable_mapping_timestamp_tz = _scan_params.__isset.enable_mapping_timestamp_tz
339
84
                                                   ? _scan_params.enable_mapping_timestamp_tz
340
84
                                                   : false;
341
84
        if (_meta_cache == nullptr) {
342
            // wrap _file_metadata with unique ptr, so that it can be released finally.
343
48
            RETURN_IF_ERROR(parse_thrift_footer(_tracing_file_reader, &_file_metadata_ptr,
344
48
                                                &meta_size, _io_ctx, enable_mapping_varbinary,
345
48
                                                enable_mapping_timestamp_tz));
346
48
            _file_metadata = _file_metadata_ptr.get();
347
            // parse magic number & parse meta data
348
48
            _reader_statistics.file_footer_read_calls += 1;
349
48
        } else {
350
36
            const auto& file_meta_cache_key =
351
36
                    FileMetaCache::get_key(_tracing_file_reader, _file_description);
352
36
            if (!_meta_cache->lookup(file_meta_cache_key, &_meta_cache_handle)) {
353
24
                RETURN_IF_ERROR(parse_thrift_footer(_tracing_file_reader, &_file_metadata_ptr,
354
24
                                                    &meta_size, _io_ctx, enable_mapping_varbinary,
355
24
                                                    enable_mapping_timestamp_tz));
356
                // _file_metadata_ptr.release() : move control of _file_metadata to _meta_cache_handle
357
24
                _meta_cache->insert(file_meta_cache_key, _file_metadata_ptr.release(),
358
24
                                    &_meta_cache_handle);
359
24
                _file_metadata = _meta_cache_handle.data<FileMetaData>();
360
24
                _reader_statistics.file_footer_read_calls += 1;
361
24
            } else {
362
12
                _reader_statistics.file_footer_hit_cache++;
363
12
            }
364
36
            _file_metadata = _meta_cache_handle.data<FileMetaData>();
365
36
        }
366
367
84
        if (_file_metadata == nullptr) {
368
0
            return Status::InternalError("failed to get file meta data: {}",
369
0
                                         _file_description.path);
370
0
        }
371
84
    }
372
106
    return Status::OK();
373
106
}
374
375
40
Status ParquetReader::get_file_metadata_schema(const FieldDescriptor** ptr) {
376
40
    RETURN_IF_ERROR(_open_file());
377
40
    DCHECK(_file_metadata != nullptr);
378
40
    *ptr = &_file_metadata->schema();
379
40
    return Status::OK();
380
40
}
381
382
103
void ParquetReader::_init_system_properties() {
383
103
    if (_scan_range.__isset.file_type) {
384
        // for compatibility
385
0
        _system_properties.system_type = _scan_range.file_type;
386
103
    } else {
387
103
        _system_properties.system_type = _scan_params.file_type;
388
103
    }
389
103
    _system_properties.properties = _scan_params.properties;
390
103
    _system_properties.hdfs_params = _scan_params.hdfs_params;
391
103
    if (_scan_params.__isset.broker_addresses) {
392
0
        _system_properties.broker_addresses.assign(_scan_params.broker_addresses.begin(),
393
0
                                                   _scan_params.broker_addresses.end());
394
0
    }
395
103
}
396
397
103
void ParquetReader::_init_file_description() {
398
103
    _file_description.path = _scan_range.path;
399
103
    _file_description.file_size = _scan_range.__isset.file_size ? _scan_range.file_size : -1;
400
103
    if (_scan_range.__isset.fs_name) {
401
0
        _file_description.fs_name = _scan_range.fs_name;
402
0
    }
403
103
    if (_scan_range.__isset.file_cache_admission) {
404
0
        _file_description.file_cache_admission = _scan_range.file_cache_admission;
405
0
    }
406
103
}
407
408
9
Status ParquetReader::on_before_init_reader(ReaderInitContext* ctx) {
409
9
    _column_descs = ctx->column_descs;
410
9
    _fill_col_name_to_block_idx = ctx->col_name_to_block_idx;
411
9
    RETURN_IF_ERROR(
412
9
            _extract_partition_values(*ctx->range, ctx->tuple_descriptor, _fill_partition_values));
413
21
    for (auto& desc : *ctx->column_descs) {
414
21
        if (desc.category == ColumnCategory::REGULAR ||
415
21
            desc.category == ColumnCategory::GENERATED) {
416
21
            ctx->column_names.push_back(desc.name);
417
21
        } else if (desc.category == ColumnCategory::SYNTHESIZED &&
418
0
                   desc.name.starts_with(BeConsts::GLOBAL_ROWID_COL)) {
419
0
            auto topn_row_id_column_iter = _create_topn_row_id_column_iterator();
420
0
            this->register_synthesized_column_handler(
421
0
                    desc.name,
422
0
                    [iter = std::move(topn_row_id_column_iter), this, &desc](
423
0
                            Block* block, size_t rows) -> Status {
424
0
                        return fill_topn_row_id(iter, desc.name, block, rows);
425
0
                    });
426
0
            continue;
427
0
        }
428
21
    }
429
430
    // Build table_info_node from Parquet file metadata with case-insensitive recursive matching.
431
    // File is already opened by init_reader before this hook, so metadata is available.
432
    // tuple_descriptor may be null in unit tests that only set column_descs.
433
9
    if (ctx->tuple_descriptor != nullptr) {
434
7
        const FieldDescriptor* field_desc = nullptr;
435
7
        RETURN_IF_ERROR(get_file_metadata_schema(&field_desc));
436
7
        RETURN_IF_ERROR(TableSchemaChangeHelper::BuildTableInfoUtil::by_parquet_name(
437
7
                ctx->tuple_descriptor, *field_desc, ctx->table_info_node));
438
7
        auto column_id_result = _create_column_ids_by_name(field_desc, ctx->tuple_descriptor);
439
7
        ctx->column_ids = std::move(column_id_result.column_ids);
440
7
        ctx->filter_column_ids = std::move(column_id_result.filter_column_ids);
441
7
    }
442
443
9
    return Status::OK();
444
9
}
445
446
ColumnIdResult ParquetReader::_create_column_ids_by_name(const FieldDescriptor* field_desc,
447
7
                                                         const TupleDescriptor* tuple_descriptor) {
448
7
    auto* mutable_field_desc = const_cast<FieldDescriptor*>(field_desc);
449
7
    mutable_field_desc->assign_ids();
450
451
7
    std::unordered_map<std::string, const FieldSchema*> table_col_name_to_field_schema_map;
452
21
    for (int i = 0; i < field_desc->size(); ++i) {
453
14
        auto field_schema = field_desc->get_column(i);
454
14
        if (!field_schema) {
455
0
            continue;
456
0
        }
457
14
        table_col_name_to_field_schema_map[field_schema->lower_case_name] = field_schema;
458
14
    }
459
460
7
    std::set<uint64_t> column_ids;
461
7
    std::set<uint64_t> filter_column_ids;
462
463
7
    auto process_access_paths = [](const FieldSchema* parquet_field,
464
7
                                   const std::vector<TColumnAccessPath>& access_paths,
465
7
                                   std::set<uint64_t>& out_ids) {
466
0
        process_nested_access_paths(
467
0
                parquet_field, access_paths, out_ids,
468
0
                [](const FieldSchema* field) { return field->get_column_id(); },
469
0
                [](const FieldSchema* field) { return field->get_max_column_id(); },
470
0
                HiveParquetNestedColumnUtils::extract_nested_column_ids);
471
0
    };
472
473
17
    for (const auto* slot : tuple_descriptor->slots()) {
474
17
        auto it = table_col_name_to_field_schema_map.find(slot->col_name_lower_case());
475
17
        if (it == table_col_name_to_field_schema_map.end()) {
476
5
            continue;
477
5
        }
478
12
        auto field_schema = it->second;
479
480
12
        if ((slot->col_type() != TYPE_STRUCT && slot->col_type() != TYPE_ARRAY &&
481
12
             slot->col_type() != TYPE_MAP && slot->col_type() != TYPE_VARIANT)) {
482
12
            column_ids.insert(field_schema->column_id);
483
12
            if (slot->is_predicate()) {
484
0
                filter_column_ids.insert(field_schema->column_id);
485
0
            }
486
12
            continue;
487
12
        }
488
489
0
        process_access_paths(field_schema, slot->all_access_paths(), column_ids);
490
0
        if (!slot->predicate_access_paths().empty()) {
491
0
            process_access_paths(field_schema, slot->predicate_access_paths(), filter_column_ids);
492
0
        }
493
0
    }
494
495
7
    return ColumnIdResult(std::move(column_ids), std::move(filter_column_ids));
496
7
}
497
498
18
std::string ParquetReader::_selected_leaf_column_paths() const {
499
18
    if (_file_metadata == nullptr) {
500
0
        return "";
501
0
    }
502
503
18
    std::vector<std::string> leaf_paths;
504
18
    auto schema_desc = _file_metadata->schema();
505
18
    std::function<void(const FieldSchema*, const std::string&)> collect =
506
87
            [&](const FieldSchema* field, const std::string& path) {
507
87
                if (!_column_ids.empty() && !_column_ids.contains(field->get_column_id())) {
508
4
                    return;
509
4
                }
510
511
83
                if (field->children.empty()) {
512
70
                    if (field->physical_column_index >= 0) {
513
70
                        leaf_paths.push_back(path);
514
70
                    }
515
70
                    return;
516
70
                }
517
518
28
                for (const auto& child : field->children) {
519
28
                    collect(&child, path + "." + child.name);
520
28
                }
521
13
            };
522
523
59
    for (const auto& read_col : _read_file_columns) {
524
59
        const FieldSchema* field = schema_desc.get_column(read_col);
525
59
        if (field != nullptr) {
526
59
            collect(field, field->name);
527
59
        }
528
59
    }
529
530
18
    std::sort(leaf_paths.begin(), leaf_paths.end());
531
18
    leaf_paths.erase(std::unique(leaf_paths.begin(), leaf_paths.end()), leaf_paths.end());
532
533
18
    std::stringstream result;
534
88
    for (size_t i = 0; i < leaf_paths.size(); ++i) {
535
70
        if (i != 0) {
536
52
            result << ", ";
537
52
        }
538
70
        result << leaf_paths[i];
539
70
    }
540
18
    return result.str();
541
18
}
542
543
66
Status ParquetReader::_open_file_reader(ReaderInitContext* /*ctx*/) {
544
66
    return _open_file();
545
66
}
546
547
66
Status ParquetReader::_do_init_reader(ReaderInitContext* base_ctx) {
548
66
    auto* ctx = checked_context_cast<ParquetInitContext>(base_ctx);
549
66
    _col_name_to_block_idx = base_ctx->col_name_to_block_idx;
550
66
    _tuple_descriptor = ctx->tuple_descriptor;
551
66
    _row_descriptor = ctx->row_descriptor;
552
66
    _colname_to_slot_id = ctx->colname_to_slot_id;
553
66
    _not_single_slot_filter_conjuncts = ctx->not_single_slot_filter_conjuncts;
554
66
    _slot_id_to_filter_conjuncts = ctx->slot_id_to_filter_conjuncts;
555
66
    _filter_groups = ctx->filter_groups;
556
66
    _table_info_node_ptr = base_ctx->table_info_node;
557
66
    _column_ids = base_ctx->column_ids;
558
66
    _filter_column_ids = base_ctx->filter_column_ids;
559
560
    // _open_file_reader (called by init_reader NVI before hooks) must have opened the file.
561
66
    DCHECK(_file_metadata != nullptr)
562
0
            << "ParquetReader::_do_init_reader called without _open_file_reader";
563
66
    _t_metadata = &(_file_metadata->to_thrift());
564
565
66
    SCOPED_RAW_TIMER(&_reader_statistics.parse_meta_time);
566
66
    _total_groups = _t_metadata->row_groups.size();
567
66
    if (_total_groups == 0) {
568
0
        return Status::EndOfFile("init reader failed, empty parquet file: " + _scan_range.path);
569
0
    }
570
66
    _current_row_group_index = RowGroupReader::RowGroupIndex {-1, 0, 0};
571
572
    // Compute missing columns and file↔table column mapping.
573
    // This runs in _do_init_reader (not on_before_init_reader) because table-format readers
574
    // (Iceberg, Paimon, Hive, Hudi) override on_before_init_reader completely.
575
66
    if (has_column_descs()) {
576
24
        _fill_missing_cols.clear();
577
24
        _fill_missing_defaults.clear();
578
74
        for (const auto& col_name : base_ctx->column_names) {
579
74
            if (!_table_info_node_ptr->children_column_exists(col_name)) {
580
5
                _fill_missing_cols.insert(col_name);
581
5
            }
582
74
        }
583
24
        if (_column_descs && !_fill_missing_cols.empty()) {
584
13
            for (const auto& desc : *_column_descs) {
585
13
                if (_fill_missing_cols.contains(desc.name) &&
586
13
                    !_fill_partition_values.contains(desc.name)) {
587
0
                    _fill_missing_defaults[desc.name] = desc.default_expr;
588
0
                }
589
13
            }
590
5
        }
591
24
    }
592
    // Resolve file-column ↔ table-column mapping in file-schema order.
593
    // _init_read_columns handles both normal path (missing cols populated above)
594
    // and standalone path (_fill_missing_cols empty, _table_info_node_ptr may be null).
595
66
    _init_read_columns(base_ctx->column_names);
596
66
    if (_profile != nullptr) {
597
18
        _profile->add_info_string("ParquetReadColumnPaths", _selected_leaf_column_paths());
598
18
    }
599
600
    // build column predicates for column lazy read
601
66
    if (ctx->conjuncts != nullptr) {
602
66
        _lazy_read_ctx.conjuncts = *ctx->conjuncts;
603
66
    }
604
66
    if (ctx->slot_id_to_predicates != nullptr) {
605
66
        _lazy_read_ctx.slot_id_to_predicates = *ctx->slot_id_to_predicates;
606
66
    }
607
608
    // ---- Inlined set_fill_columns logic (partition/missing/synthesized classification) ----
609
610
    // 1. Collect predicate columns from conjuncts for lazy materialization
611
66
    std::unordered_map<std::string, std::pair<uint32_t, int>> predicate_columns;
612
66
    _collect_predicate_columns_from_conjuncts(predicate_columns);
613
614
    // 2. Classify read/partition/missing/synthesized columns into lazy vs predicate groups
615
66
    _classify_columns_for_lazy_read(predicate_columns, _fill_partition_values,
616
66
                                    _fill_missing_defaults);
617
618
    // 3. Populate col_names vectors for ColumnProcessor path
619
66
    for (auto& kv : _lazy_read_ctx.predicate_partition_columns) {
620
5
        _lazy_read_ctx.predicate_partition_col_names.emplace_back(kv.first);
621
5
    }
622
66
    for (auto& kv : _lazy_read_ctx.predicate_missing_columns) {
623
0
        _lazy_read_ctx.predicate_missing_col_names.emplace_back(kv.first);
624
0
    }
625
66
    for (auto& kv : _lazy_read_ctx.partition_columns) {
626
3
        _lazy_read_ctx.partition_col_names.emplace_back(kv.first);
627
3
    }
628
66
    for (auto& kv : _lazy_read_ctx.missing_columns) {
629
0
        _lazy_read_ctx.missing_col_names.emplace_back(kv.first);
630
0
    }
631
632
66
    if (_filter_groups && (_total_groups == 0 || _t_metadata->num_rows == 0 || _range_size < 0)) {
633
0
        return Status::EndOfFile("No row group to read");
634
0
    }
635
636
66
    return Status::OK();
637
66
}
638
639
66
void ParquetReader::_init_read_columns(const std::vector<std::string>& column_names) {
640
    // Build file_col_name → table_col_name map, skipping missing columns.
641
    // Must iterate file schema in physical order so that _generate_random_access_ranges
642
    // sees monotonically increasing chunk offsets.
643
66
    auto schema_desc = _file_metadata->schema();
644
66
    std::map<std::string, std::string> required_file_columns;
645
422
    for (const auto& col_name : column_names) {
646
422
        if (_fill_missing_cols.contains(col_name)) {
647
5
            continue;
648
5
        }
649
417
        std::string file_col = col_name;
650
417
        if (_table_info_node_ptr && _table_info_node_ptr->children_column_exists(col_name)) {
651
417
            file_col = _table_info_node_ptr->children_file_column_name(col_name);
652
417
        }
653
417
        required_file_columns[file_col] = col_name;
654
417
    }
655
725
    for (int i = 0; i < schema_desc.size(); ++i) {
656
659
        const auto& name = schema_desc.get_column(i)->name;
657
659
        if (required_file_columns.contains(name)) {
658
417
            _read_file_columns.emplace_back(name);
659
417
            _read_table_columns.emplace_back(required_file_columns[name]);
660
417
            _read_table_columns_set.insert(required_file_columns[name]);
661
417
        }
662
659
    }
663
66
}
664
665
0
bool ParquetReader::_exists_in_file(const std::string& expr_name) const {
666
    // `_read_table_columns_set` is used to ensure that only columns actually read are subject to min-max filtering.
667
    // This primarily handles cases where partition columns also exist in a file. The reason it's not modified
668
    // in `_table_info_node_ptr` is that Iceberg、Hudi has inconsistent requirements for this node;
669
    // Iceberg partition evolution need read partition columns from a file.
670
    // hudi set `hoodie.datasource.write.drop.partition.columns=false` not need read partition columns from a file.
671
0
    return _table_info_node_ptr->children_column_exists(expr_name) &&
672
0
           _read_table_columns_set.contains(expr_name);
673
0
}
674
675
0
bool ParquetReader::_type_matches(const int cid) const {
676
0
    auto* slot = _tuple_descriptor->slots()[cid];
677
0
    auto table_col_type = remove_nullable(slot->type());
678
679
0
    const auto& file_col_name = _table_info_node_ptr->children_file_column_name(slot->col_name());
680
0
    const auto& file_col_type =
681
0
            remove_nullable(_file_metadata->schema().get_column(file_col_name)->data_type);
682
683
0
    return (table_col_type->get_primitive_type() == file_col_type->get_primitive_type()) &&
684
0
           !is_complex_type(table_col_type->get_primitive_type());
685
0
}
686
687
void ParquetReader::_collect_predicate_columns_from_conjuncts(
688
66
        std::unordered_map<std::string, std::pair<uint32_t, int>>& predicate_columns) {
689
66
    std::function<void(VExpr * expr)> visit_slot = [&](VExpr* expr) {
690
39
        if (expr->is_slot_ref()) {
691
13
            VSlotRef* slot_ref = static_cast<VSlotRef*>(expr);
692
13
            auto expr_name = slot_ref->expr_name();
693
13
            predicate_columns.emplace(expr_name,
694
13
                                      std::make_pair(slot_ref->column_id(), slot_ref->slot_id()));
695
13
            if (slot_ref->column_id() == 0) {
696
3
                _lazy_read_ctx.resize_first_column = false;
697
3
            }
698
13
            return;
699
13
        }
700
26
        for (auto& child : expr->children()) {
701
26
            visit_slot(child.get());
702
26
        }
703
26
    };
704
705
66
    for (const auto& conjunct : _lazy_read_ctx.conjuncts) {
706
13
        auto expr = conjunct->root();
707
13
        if (expr->is_rf_wrapper()) {
708
0
            VRuntimeFilterWrapper* runtime_filter = assert_cast<VRuntimeFilterWrapper*>(expr.get());
709
0
            auto filter_impl = runtime_filter->get_impl();
710
0
            visit_slot(filter_impl.get());
711
13
        } else {
712
13
            visit_slot(expr.get());
713
13
        }
714
13
    }
715
716
66
    if (!_lazy_read_ctx.slot_id_to_predicates.empty()) {
717
0
        auto and_pred = AndBlockColumnPredicate::create_unique();
718
0
        for (const auto& entry : _lazy_read_ctx.slot_id_to_predicates) {
719
0
            for (const auto& pred : entry.second) {
720
                // Parquet shares _push_down_predicates for row-group/page min-max pruning and
721
                // bloom-filter evaluation, so this flag currently gates both predicate paths.
722
0
                if (!has_column_optimization(pred->col_name(), ColumnOptimizationTypes::MIN_MAX)) {
723
0
                    continue;
724
0
                }
725
0
                if (!_exists_in_file(pred->col_name()) || !_type_matches(pred->column_id())) {
726
0
                    continue;
727
0
                }
728
0
                and_pred->add_column_predicate(
729
0
                        SingleColumnBlockPredicate::create_unique(pred->clone(pred->column_id())));
730
0
            }
731
0
        }
732
0
        if (and_pred->num_of_column_predicate() > 0) {
733
0
            _push_down_predicates.push_back(std::move(and_pred));
734
0
        }
735
0
    }
736
66
}
737
738
void ParquetReader::_classify_columns_for_lazy_read(
739
        const std::unordered_map<std::string, std::pair<uint32_t, int>>&
740
                predicate_conjuncts_columns,
741
        const std::unordered_map<std::string, std::tuple<std::string, const SlotDescriptor*>>&
742
                partition_columns,
743
66
        const std::unordered_map<std::string, VExprContextSPtr>& missing_columns) {
744
66
    const FieldDescriptor& schema = _file_metadata->schema();
745
66
    auto predicate_columns = predicate_conjuncts_columns;
746
#ifndef BE_TEST
747
    for (const auto& [col_name, _] : _generated_col_handlers) {
748
        int slot_id = -1;
749
        for (auto slot : _tuple_descriptor->slots()) {
750
            if (slot->col_name() == col_name) {
751
                slot_id = slot->id();
752
                break;
753
            }
754
        }
755
        DCHECK(slot_id != -1) << "slot id should not be -1 for generated column: " << col_name;
756
        auto column_index = _row_descriptor->get_column_id(slot_id);
757
        if (column_index == 0) {
758
            _lazy_read_ctx.resize_first_column = false;
759
        }
760
        // assume generated columns are only used for predicate push down.
761
        predicate_columns.emplace(col_name, std::make_pair(column_index, slot_id));
762
    }
763
764
    for (const auto& [col_name, _] : _synthesized_col_handlers) {
765
        int slot_id = -1;
766
        for (auto slot : _tuple_descriptor->slots()) {
767
            if (slot->col_name() == col_name) {
768
                slot_id = slot->id();
769
                break;
770
            }
771
        }
772
        DCHECK(slot_id != -1) << "slot id should not be -1 for synthesized column: " << col_name;
773
        auto column_index = _row_descriptor->get_column_id(slot_id);
774
        if (column_index == 0) {
775
            _lazy_read_ctx.resize_first_column = false;
776
        }
777
        // synthesized columns always fill data on first phase.
778
        _lazy_read_ctx.all_predicate_col_ids.emplace_back(column_index);
779
    }
780
#endif
781
417
    for (auto& read_table_col : _read_table_columns) {
782
417
        _lazy_read_ctx.all_read_columns.emplace_back(read_table_col);
783
784
417
        auto file_column_name = _table_info_node_ptr->children_file_column_name(read_table_col);
785
417
        PrimitiveType column_type =
786
417
                schema.get_column(file_column_name)->data_type->get_primitive_type();
787
417
        if (is_complex_type(column_type)) {
788
2
            _lazy_read_ctx.has_complex_type = true;
789
2
        }
790
417
        if (predicate_columns.size() > 0) {
791
12
            auto iter = predicate_columns.find(read_table_col);
792
12
            if (iter == predicate_columns.end()) {
793
4
                _lazy_read_ctx.lazy_read_columns.emplace_back(read_table_col);
794
8
            } else {
795
8
                _lazy_read_ctx.predicate_columns.first.emplace_back(iter->first);
796
8
                _lazy_read_ctx.predicate_columns.second.emplace_back(iter->second.second);
797
8
                _lazy_read_ctx.all_predicate_col_ids.emplace_back(iter->second.first);
798
8
            }
799
12
        }
800
417
    }
801
802
66
    for (auto& kv : partition_columns) {
803
5
        auto iter = predicate_columns.find(kv.first);
804
5
        if (iter == predicate_columns.end()) {
805
0
            _lazy_read_ctx.partition_columns.emplace(kv.first, kv.second);
806
5
        } else {
807
5
            _lazy_read_ctx.predicate_partition_columns.emplace(kv.first, kv.second);
808
5
            _lazy_read_ctx.all_predicate_col_ids.emplace_back(iter->second.first);
809
5
        }
810
5
    }
811
812
66
    for (auto& kv : missing_columns) {
813
0
        auto iter = predicate_columns.find(kv.first);
814
0
        if (iter != predicate_columns.end()) {
815
            //For check missing column :   missing column == xx, missing column is null,missing column is not null.
816
0
            if (_slot_id_to_filter_conjuncts->find(iter->second.second) !=
817
0
                _slot_id_to_filter_conjuncts->end()) {
818
0
                for (auto& ctx : _slot_id_to_filter_conjuncts->find(iter->second.second)->second) {
819
0
                    _lazy_read_ctx.missing_columns_conjuncts.emplace_back(ctx);
820
0
                }
821
0
            }
822
0
            _lazy_read_ctx.predicate_missing_columns.emplace(kv.first, kv.second);
823
0
            _lazy_read_ctx.all_predicate_col_ids.emplace_back(iter->second.first);
824
0
        } else {
825
0
            _lazy_read_ctx.missing_columns.emplace(kv.first, kv.second);
826
0
        }
827
0
    }
828
829
66
    if (_enable_lazy_mat && _lazy_read_ctx.predicate_columns.first.size() > 0 &&
830
66
        _lazy_read_ctx.lazy_read_columns.size() > 0) {
831
2
        _lazy_read_ctx.can_lazy_read = true;
832
2
    }
833
834
66
    if (!_lazy_read_ctx.can_lazy_read) {
835
64
        for (auto& kv : _lazy_read_ctx.predicate_partition_columns) {
836
3
            _lazy_read_ctx.partition_columns.emplace(kv.first, kv.second);
837
3
        }
838
64
        for (auto& kv : _lazy_read_ctx.predicate_missing_columns) {
839
0
            _lazy_read_ctx.missing_columns.emplace(kv.first, kv.second);
840
0
        }
841
64
    }
842
66
}
843
844
// init file reader and file metadata for parsing schema
845
0
Status ParquetReader::init_schema_reader() {
846
0
    RETURN_IF_ERROR(_open_file());
847
0
    _t_metadata = &(_file_metadata->to_thrift());
848
0
    return Status::OK();
849
0
}
850
851
Status ParquetReader::get_parsed_schema(std::vector<std::string>* col_names,
852
0
                                        std::vector<DataTypePtr>* col_types) {
853
0
    _total_groups = _t_metadata->row_groups.size();
854
0
    auto schema_desc = _file_metadata->schema();
855
0
    for (int i = 0; i < schema_desc.size(); ++i) {
856
        // Get the Column Reader for the boolean column
857
0
        col_names->emplace_back(schema_desc.get_column(i)->name);
858
0
        col_types->emplace_back(make_nullable(schema_desc.get_column(i)->data_type));
859
0
    }
860
0
    return Status::OK();
861
0
}
862
863
Status ParquetReader::_get_columns_impl(
864
14
        std::unordered_map<std::string, DataTypePtr>* name_to_type) {
865
14
    const auto& schema_desc = _file_metadata->schema();
866
14
    std::unordered_set<std::string> column_names;
867
14
    schema_desc.get_column_names(&column_names);
868
210
    for (auto& name : column_names) {
869
210
        auto field = schema_desc.get_column(name);
870
210
        name_to_type->emplace(name, field->data_type);
871
210
    }
872
14
    return Status::OK();
873
14
}
874
875
98
Status ParquetReader::_do_get_next_block(Block* block, size_t* read_rows, bool* eof) {
876
98
    if (_current_group_reader == nullptr || _row_group_eof) {
877
38
        Status st = _next_row_group_reader();
878
38
        if (!st.ok() && !st.is<ErrorCode::END_OF_FILE>()) {
879
0
            return st;
880
0
        }
881
38
        if (_current_group_reader == nullptr || _row_group_eof || st.is<ErrorCode::END_OF_FILE>()) {
882
0
            _current_group_reader.reset(nullptr);
883
0
            _row_group_eof = true;
884
0
            *read_rows = 0;
885
0
            *eof = true;
886
0
            return Status::OK();
887
0
        }
888
38
    }
889
890
    // Limit memory per batch for load paths.
891
    // _load_bytes_per_row is updated after each batch so the *next* call pre-shrinks _batch_size
892
    // before reading, ensuring the current batch is already within the limit (from call 2 onward).
893
98
    const int64_t max_block_bytes =
894
98
            (_state != nullptr && _state->query_type() == TQueryType::LOAD &&
895
98
             config::load_reader_max_block_bytes > 0)
896
98
                    ? config::load_reader_max_block_bytes
897
98
                    : 0;
898
98
    if (max_block_bytes > 0 && _load_bytes_per_row > 0) {
899
0
        _batch_size = std::max((size_t)1,
900
0
                               (size_t)((int64_t)max_block_bytes / (int64_t)_load_bytes_per_row));
901
0
    }
902
903
98
    SCOPED_RAW_TIMER(&_reader_statistics.column_read_time);
904
98
    Status batch_st =
905
98
            _current_group_reader->next_batch(block, _batch_size, read_rows, &_row_group_eof);
906
98
    if (batch_st.is<ErrorCode::END_OF_FILE>()) {
907
0
        block->clear_column_data();
908
0
        _current_group_reader.reset(nullptr);
909
0
        *read_rows = 0;
910
0
        *eof = true;
911
0
        return Status::OK();
912
0
    }
913
914
98
    if (!batch_st.ok()) {
915
0
        return Status::InternalError("Read parquet file {} failed, reason = {}", _scan_range.path,
916
0
                                     batch_st.to_string());
917
0
    }
918
919
98
    if (max_block_bytes > 0 && *read_rows > 0) {
920
0
        _load_bytes_per_row = block->bytes() / *read_rows;
921
0
    }
922
923
98
    if (_row_group_eof) {
924
38
        auto column_st = _current_group_reader->merged_column_statistics();
925
38
        _column_statistics.merge(column_st);
926
38
        _reader_statistics.lazy_read_filtered_rows +=
927
38
                _current_group_reader->lazy_read_filtered_rows();
928
38
        _reader_statistics.predicate_filter_time += _current_group_reader->predicate_filter_time();
929
38
        _reader_statistics.dict_filter_rewrite_time +=
930
38
                _current_group_reader->dict_filter_rewrite_time();
931
38
        if (_io_ctx) {
932
15
            _io_ctx->condition_cache_filtered_rows +=
933
15
                    _current_group_reader->condition_cache_filtered_rows();
934
15
        }
935
936
38
        if (_current_row_group_index.row_group_id + 1 == _total_groups) {
937
37
            *eof = true;
938
37
        } else {
939
1
            *eof = false;
940
1
        }
941
38
    }
942
98
    return Status::OK();
943
98
}
944
945
RowGroupReader::PositionDeleteContext ParquetReader::_get_position_delete_ctx(
946
38
        const tparquet::RowGroup& row_group, const RowGroupReader::RowGroupIndex& row_group_index) {
947
38
    if (_delete_rows == nullptr) {
948
38
        return RowGroupReader::PositionDeleteContext(row_group.num_rows, row_group_index.first_row);
949
38
    }
950
0
    const int64_t* delete_rows = &(*_delete_rows)[0];
951
0
    const int64_t* delete_rows_end = delete_rows + _delete_rows->size();
952
0
    const int64_t* start_pos = std::lower_bound(delete_rows + _delete_rows_index, delete_rows_end,
953
0
                                                row_group_index.first_row);
954
0
    int64_t start_index = start_pos - delete_rows;
955
0
    const int64_t* end_pos = std::lower_bound(start_pos, delete_rows_end, row_group_index.last_row);
956
0
    int64_t end_index = end_pos - delete_rows;
957
0
    _delete_rows_index = end_index;
958
0
    return RowGroupReader::PositionDeleteContext(*_delete_rows, row_group.num_rows,
959
0
                                                 row_group_index.first_row, start_index, end_index);
960
38
}
961
962
38
Status ParquetReader::_next_row_group_reader() {
963
38
    if (_current_group_reader != nullptr) {
964
1
        _current_group_reader->collect_profile_before_close();
965
1
    }
966
967
38
    RowRanges candidate_row_ranges;
968
38
    while (++_current_row_group_index.row_group_id < _total_groups) {
969
38
        const auto& row_group = _t_metadata->row_groups[_current_row_group_index.row_group_id];
970
38
        _current_row_group_index.first_row = _current_row_group_index.last_row;
971
38
        _current_row_group_index.last_row = _current_row_group_index.last_row + row_group.num_rows;
972
973
38
        if (_filter_groups && _is_misaligned_range_group(row_group)) {
974
0
            continue;
975
0
        }
976
977
38
        candidate_row_ranges.clear();
978
        // The range of lines to be read is determined by the push down predicate.
979
38
        RETURN_IF_ERROR(_process_min_max_bloom_filter(
980
38
                _current_row_group_index, row_group, _push_down_predicates, &candidate_row_ranges));
981
982
38
        std::function<int64_t(const FieldSchema*)> column_compressed_size =
983
138
                [&row_group, &column_compressed_size](const FieldSchema* field) -> int64_t {
984
138
            if (field->physical_column_index >= 0) {
985
124
                int parquet_col_id = field->physical_column_index;
986
124
                if (row_group.columns[parquet_col_id].__isset.meta_data) {
987
124
                    return row_group.columns[parquet_col_id].meta_data.total_compressed_size;
988
124
                }
989
0
                return 0;
990
124
            }
991
14
            int64_t size = 0;
992
30
            for (const FieldSchema& child : field->children) {
993
30
                size += column_compressed_size(&child);
994
30
            }
995
14
            return size;
996
138
        };
997
38
        int64_t group_size = 0; // only calculate the needed columns
998
108
        for (auto& read_col : _read_file_columns) {
999
108
            const FieldSchema* field = _file_metadata->schema().get_column(read_col);
1000
108
            group_size += column_compressed_size(field);
1001
108
        }
1002
1003
38
        _reader_statistics.read_rows += candidate_row_ranges.count();
1004
38
        if (_io_ctx) {
1005
15
            _io_ctx->file_reader_stats->read_rows += candidate_row_ranges.count();
1006
15
        }
1007
1008
38
        if (candidate_row_ranges.count() != 0) {
1009
            // need read this row group.
1010
38
            _reader_statistics.read_row_groups++;
1011
38
            _reader_statistics.filtered_page_rows +=
1012
38
                    row_group.num_rows - candidate_row_ranges.count();
1013
38
            break;
1014
38
        } else {
1015
            // this row group be filtered.
1016
0
            _reader_statistics.filtered_row_groups++;
1017
0
            _reader_statistics.filtered_bytes += group_size;
1018
0
            _reader_statistics.filtered_group_rows += row_group.num_rows;
1019
0
        }
1020
38
    }
1021
1022
38
    if (_current_row_group_index.row_group_id == _total_groups) {
1023
0
        _row_group_eof = true;
1024
0
        _current_group_reader.reset(nullptr);
1025
0
        return Status::EndOfFile("No next RowGroupReader");
1026
0
    }
1027
1028
    // process page index and generate the ranges to read
1029
38
    auto& row_group = _t_metadata->row_groups[_current_row_group_index.row_group_id];
1030
1031
38
    RowGroupReader::PositionDeleteContext position_delete_ctx =
1032
38
            _get_position_delete_ctx(row_group, _current_row_group_index);
1033
38
    io::FileReaderSPtr group_file_reader;
1034
38
    if (typeid_cast<io::InMemoryFileReader*>(_file_reader.get())) {
1035
        // InMemoryFileReader has the ability to merge small IO
1036
0
        group_file_reader = _file_reader;
1037
38
    } else {
1038
38
        size_t avg_io_size = 0;
1039
38
        const std::vector<io::PrefetchRange> io_ranges =
1040
38
                _generate_random_access_ranges(_current_row_group_index, &avg_io_size);
1041
38
        int64_t merged_read_slice_size = -1;
1042
38
        if (_state != nullptr && _state->query_options().__isset.merge_read_slice_size) {
1043
26
            merged_read_slice_size = _state->query_options().merge_read_slice_size;
1044
26
        }
1045
        // The underlying page reader will prefetch data in column.
1046
        // Using both MergeRangeFileReader and BufferedStreamReader simultaneously would waste a lot of memory.
1047
38
        group_file_reader =
1048
38
                avg_io_size < io::MergeRangeFileReader::SMALL_IO
1049
38
                        ? std::make_shared<io::MergeRangeFileReader>(
1050
38
                                  _profile, _file_reader, io_ranges, merged_read_slice_size)
1051
38
                        : _file_reader;
1052
38
    }
1053
38
    _current_group_reader.reset(new RowGroupReader(
1054
38
            _io_ctx ? std::make_shared<io::TracingFileReader>(group_file_reader,
1055
15
                                                              _io_ctx->file_reader_stats)
1056
38
                    : group_file_reader,
1057
38
            _read_table_columns, _current_row_group_index.row_group_id, row_group, _ctz, _io_ctx,
1058
38
            position_delete_ctx, _lazy_read_ctx, _state, _column_ids, _filter_column_ids));
1059
38
    _row_group_eof = false;
1060
1061
38
    _current_group_reader->set_current_row_group_idx(_current_row_group_index);
1062
38
    _current_group_reader->set_col_name_to_block_idx(_col_name_to_block_idx);
1063
38
    if (_condition_cache_ctx) {
1064
0
        _current_group_reader->set_condition_cache_context(_condition_cache_ctx);
1065
0
    }
1066
38
    _current_group_reader->set_table_format_reader(this);
1067
1068
38
    _current_group_reader->_table_info_node_ptr = _table_info_node_ptr;
1069
38
    return _current_group_reader->init(_file_metadata->schema(), candidate_row_ranges, _col_offsets,
1070
38
                                       _tuple_descriptor, _row_descriptor, _colname_to_slot_id,
1071
38
                                       _not_single_slot_filter_conjuncts,
1072
38
                                       _slot_id_to_filter_conjuncts);
1073
38
}
1074
1075
std::vector<io::PrefetchRange> ParquetReader::_generate_random_access_ranges(
1076
38
        const RowGroupReader::RowGroupIndex& group, size_t* avg_io_size) {
1077
38
    std::vector<io::PrefetchRange> result;
1078
38
    int64_t last_chunk_end = -1;
1079
38
    size_t total_io_size = 0;
1080
38
    std::function<void(const FieldSchema*, const tparquet::RowGroup&)> scalar_range =
1081
136
            [&](const FieldSchema* field, const tparquet::RowGroup& row_group) {
1082
136
                if (_column_ids.empty() ||
1083
136
                    _column_ids.find(field->get_column_id()) != _column_ids.end()) {
1084
132
                    if (field->data_type->get_primitive_type() == TYPE_ARRAY) {
1085
2
                        scalar_range(&field->children[0], row_group);
1086
130
                    } else if (field->data_type->get_primitive_type() == TYPE_MAP) {
1087
0
                        scalar_range(&field->children[0], row_group);
1088
0
                        scalar_range(&field->children[1], row_group);
1089
130
                    } else if (field->data_type->get_primitive_type() == TYPE_STRUCT ||
1090
130
                               field->data_type->get_primitive_type() == TYPE_VARIANT) {
1091
37
                        for (int i = 0; i < field->children.size(); ++i) {
1092
26
                            scalar_range(&field->children[i], row_group);
1093
26
                        }
1094
119
                    } else {
1095
119
                        const tparquet::ColumnChunk& chunk =
1096
119
                                row_group.columns[field->physical_column_index];
1097
119
                        auto& chunk_meta = chunk.meta_data;
1098
119
                        int64_t chunk_start = has_dict_page(chunk_meta)
1099
119
                                                      ? chunk_meta.dictionary_page_offset
1100
119
                                                      : chunk_meta.data_page_offset;
1101
119
                        int64_t chunk_end = chunk_start + chunk_meta.total_compressed_size;
1102
119
                        DCHECK_GE(chunk_start, last_chunk_end);
1103
119
                        result.emplace_back(chunk_start, chunk_end);
1104
119
                        total_io_size += chunk_meta.total_compressed_size;
1105
119
                        last_chunk_end = chunk_end;
1106
119
                    }
1107
132
                }
1108
136
            };
1109
38
    const tparquet::RowGroup& row_group = _t_metadata->row_groups[group.row_group_id];
1110
108
    for (const auto& read_col : _read_file_columns) {
1111
108
        const FieldSchema* field = _file_metadata->schema().get_column(read_col);
1112
108
        scalar_range(field, row_group);
1113
108
    }
1114
38
    if (!result.empty()) {
1115
37
        *avg_io_size = total_io_size / result.size();
1116
37
    }
1117
38
    return result;
1118
38
}
1119
1120
37
bool ParquetReader::_is_misaligned_range_group(const tparquet::RowGroup& row_group) const {
1121
37
    int64_t start_offset = _get_column_start_offset(row_group.columns[0].meta_data);
1122
1123
37
    auto& last_column = row_group.columns[row_group.columns.size() - 1].meta_data;
1124
37
    int64_t end_offset = _get_column_start_offset(last_column) + last_column.total_compressed_size;
1125
1126
37
    int64_t row_group_mid = start_offset + (end_offset - start_offset) / 2;
1127
37
    if (!(row_group_mid >= _range_start_offset &&
1128
37
          row_group_mid < _range_start_offset + _range_size)) {
1129
0
        return true;
1130
0
    }
1131
37
    return false;
1132
37
}
1133
1134
0
int64_t ParquetReader::get_total_rows() const {
1135
0
    if (!_t_metadata) return 0;
1136
0
    if (!_filter_groups) return _t_metadata->num_rows;
1137
0
    int64_t total = 0;
1138
0
    for (const auto& rg : _t_metadata->row_groups) {
1139
0
        if (!_is_misaligned_range_group(rg)) {
1140
0
            total += rg.num_rows;
1141
0
        }
1142
0
    }
1143
0
    return total;
1144
0
}
1145
1146
0
void ParquetReader::set_condition_cache_context(std::shared_ptr<ConditionCacheContext> ctx) {
1147
0
    _condition_cache_ctx = std::move(ctx);
1148
0
    if (!_condition_cache_ctx || !_t_metadata || !_filter_groups) {
1149
0
        return;
1150
0
    }
1151
    // Find the first assigned row group to compute base_granule.
1152
0
    int64_t first_row = 0;
1153
0
    for (const auto& rg : _t_metadata->row_groups) {
1154
0
        if (!_is_misaligned_range_group(rg)) {
1155
0
            _condition_cache_ctx->base_granule = first_row / ConditionCacheContext::GRANULE_SIZE;
1156
0
            return;
1157
0
        }
1158
0
        first_row += rg.num_rows;
1159
0
    }
1160
0
}
1161
1162
Status ParquetReader::_process_page_index_filter(
1163
        const tparquet::RowGroup& row_group, const RowGroupReader::RowGroupIndex& row_group_index,
1164
        const std::vector<std::unique_ptr<MutilColumnBlockPredicate>>& push_down_pred,
1165
18
        RowRanges* candidate_row_ranges) {
1166
18
    if (UNLIKELY(_io_ctx && _io_ctx->should_stop)) {
1167
0
        return Status::EndOfFile("stop");
1168
0
    }
1169
1170
18
    std::function<void()> read_whole_row_group = [&]() {
1171
18
        candidate_row_ranges->add(RowRange {0, row_group.num_rows});
1172
18
    };
1173
1174
    // Check if the page index is available and if it exists.
1175
18
    PageIndex page_index;
1176
18
    if (!config::enable_parquet_page_index || _colname_to_slot_id == nullptr ||
1177
18
        !page_index.check_and_get_page_index_ranges(row_group.columns)) {
1178
18
        read_whole_row_group();
1179
18
        return Status::OK();
1180
18
    }
1181
1182
0
    std::vector<int> parquet_col_ids;
1183
0
    for (size_t idx = 0; idx < _read_table_columns.size(); idx++) {
1184
0
        const auto& read_table_col = _read_table_columns[idx];
1185
0
        const auto& read_file_col = _read_file_columns[idx];
1186
0
        if (!_colname_to_slot_id->contains(read_table_col)) {
1187
0
            continue;
1188
0
        }
1189
0
        auto* field = _file_metadata->schema().get_column(read_file_col);
1190
1191
0
        std::function<void(FieldSchema * field)> f = [&](FieldSchema* field) {
1192
0
            if (!_column_ids.empty() &&
1193
0
                _column_ids.find(field->get_column_id()) == _column_ids.end()) {
1194
0
                return;
1195
0
            }
1196
1197
0
            if (field->data_type->get_primitive_type() == TYPE_ARRAY) {
1198
0
                f(&field->children[0]);
1199
0
            } else if (field->data_type->get_primitive_type() == TYPE_MAP) {
1200
0
                f(&field->children[0]);
1201
0
                f(&field->children[1]);
1202
0
            } else if (field->data_type->get_primitive_type() == TYPE_STRUCT ||
1203
0
                       field->data_type->get_primitive_type() == TYPE_VARIANT) {
1204
0
                for (int i = 0; i < field->children.size(); ++i) {
1205
0
                    f(&field->children[i]);
1206
0
                }
1207
0
            } else {
1208
0
                int parquet_col_id = field->physical_column_index;
1209
0
                if (parquet_col_id >= 0) {
1210
0
                    parquet_col_ids.push_back(parquet_col_id);
1211
0
                }
1212
0
            }
1213
0
        };
1214
1215
0
        f(field);
1216
0
    }
1217
1218
0
    auto parse_offset_index = [&]() -> Status {
1219
0
        std::vector<uint8_t> off_index_buff(page_index._offset_index_size);
1220
0
        Slice res(off_index_buff.data(), page_index._offset_index_size);
1221
0
        size_t bytes_read = 0;
1222
0
        {
1223
0
            SCOPED_RAW_TIMER(&_reader_statistics.read_page_index_time);
1224
0
            RETURN_IF_ERROR(_tracing_file_reader->read_at(page_index._offset_index_start, res,
1225
0
                                                          &bytes_read, _io_ctx));
1226
0
        }
1227
0
        _column_statistics.page_index_read_calls++;
1228
0
        _col_offsets.clear();
1229
1230
0
        for (auto parquet_col_id : parquet_col_ids) {
1231
0
            auto& chunk = row_group.columns[parquet_col_id];
1232
0
            if (chunk.offset_index_length == 0) [[unlikely]] {
1233
0
                continue;
1234
0
            }
1235
0
            tparquet::OffsetIndex offset_index;
1236
0
            SCOPED_RAW_TIMER(&_reader_statistics.parse_page_index_time);
1237
0
            RETURN_IF_ERROR(
1238
0
                    page_index.parse_offset_index(chunk, off_index_buff.data(), &offset_index));
1239
0
            _col_offsets[parquet_col_id] = offset_index;
1240
0
        }
1241
0
        return Status::OK();
1242
0
    };
1243
1244
    // from https://github.com/apache/doris/pull/55795
1245
0
    RETURN_IF_ERROR(parse_offset_index());
1246
1247
    // Check if page index is needed for min-max filter.
1248
0
    if (!_enable_filter_by_min_max || push_down_pred.empty()) {
1249
0
        read_whole_row_group();
1250
0
        return Status::OK();
1251
0
    }
1252
1253
    // read column index.
1254
0
    std::vector<uint8_t> col_index_buff(page_index._column_index_size);
1255
0
    size_t bytes_read = 0;
1256
0
    Slice result(col_index_buff.data(), page_index._column_index_size);
1257
0
    {
1258
0
        SCOPED_RAW_TIMER(&_reader_statistics.read_page_index_time);
1259
0
        RETURN_IF_ERROR(_tracing_file_reader->read_at(page_index._column_index_start, result,
1260
0
                                                      &bytes_read, _io_ctx));
1261
0
    }
1262
0
    _column_statistics.page_index_read_calls++;
1263
1264
0
    SCOPED_RAW_TIMER(&_reader_statistics.page_index_filter_time);
1265
1266
    // Construct a cacheable page index structure to avoid repeatedly reading the page index of the same column.
1267
0
    ParquetPredicate::CachedPageIndexStat cached_page_index;
1268
0
    cached_page_index.ctz = _ctz;
1269
0
    std::function<bool(ParquetPredicate::PageIndexStat**, int)> get_stat_func =
1270
0
            [&](ParquetPredicate::PageIndexStat** ans, const int cid) -> bool {
1271
0
        if (cached_page_index.stats.contains(cid)) {
1272
0
            *ans = &cached_page_index.stats[cid];
1273
0
            return (*ans)->available;
1274
0
        }
1275
0
        cached_page_index.stats.emplace(cid, ParquetPredicate::PageIndexStat {});
1276
0
        auto& sig_stat = cached_page_index.stats[cid];
1277
1278
0
        auto* slot = _tuple_descriptor->slots()[cid];
1279
0
        if (!_table_info_node_ptr->children_column_exists(slot->col_name())) {
1280
            // table column not exist in file, may be schema change.
1281
0
            return false;
1282
0
        }
1283
1284
0
        const auto& file_col_name =
1285
0
                _table_info_node_ptr->children_file_column_name(slot->col_name());
1286
0
        const FieldSchema* col_schema = _file_metadata->schema().get_column(file_col_name);
1287
0
        int parquet_col_id = col_schema->physical_column_index;
1288
1289
0
        if (parquet_col_id < 0) {
1290
            // complex type, not support page index yet.
1291
0
            return false;
1292
0
        }
1293
0
        if (!_col_offsets.contains(parquet_col_id)) {
1294
            // If the file contains partition columns and the query applies filters on those
1295
            // partition columns, then reading the page index is unnecessary.
1296
0
            return false;
1297
0
        }
1298
1299
0
        auto& column_chunk = row_group.columns[parquet_col_id];
1300
0
        if (column_chunk.column_index_length == 0 || column_chunk.offset_index_length == 0) {
1301
            // column no page index.
1302
0
            return false;
1303
0
        }
1304
1305
0
        tparquet::ColumnIndex column_index;
1306
0
        {
1307
0
            SCOPED_RAW_TIMER(&_reader_statistics.parse_page_index_time);
1308
0
            RETURN_IF_ERROR(page_index.parse_column_index(column_chunk, col_index_buff.data(),
1309
0
                                                          &column_index));
1310
0
        }
1311
0
        const int64_t num_of_pages = column_index.null_pages.size();
1312
0
        if (num_of_pages <= 0) [[unlikely]] {
1313
            // no page. (maybe this row group no data.)
1314
0
            return false;
1315
0
        }
1316
0
        DCHECK_EQ(column_index.min_values.size(), column_index.max_values.size());
1317
0
        if (!column_index.__isset.null_counts) {
1318
            // not set null or null counts;
1319
0
            return false;
1320
0
        }
1321
1322
0
        auto& offset_index = _col_offsets[parquet_col_id];
1323
0
        const auto& page_locations = offset_index.page_locations;
1324
1325
0
        sig_stat.col_schema = col_schema;
1326
0
        sig_stat.num_of_pages = num_of_pages;
1327
0
        sig_stat.encoded_min_value = column_index.min_values;
1328
0
        sig_stat.encoded_max_value = column_index.max_values;
1329
0
        sig_stat.is_all_null.resize(num_of_pages);
1330
0
        sig_stat.has_null.resize(num_of_pages);
1331
0
        sig_stat.ranges.resize(num_of_pages);
1332
1333
0
        for (int page_id = 0; page_id < num_of_pages; page_id++) {
1334
0
            sig_stat.is_all_null[page_id] = column_index.null_pages[page_id];
1335
0
            sig_stat.has_null[page_id] = column_index.null_counts[page_id] > 0;
1336
1337
0
            int64_t from = page_locations[page_id].first_row_index;
1338
0
            int64_t to = 0;
1339
0
            if (page_id == page_locations.size() - 1) {
1340
0
                to = row_group_index.last_row;
1341
0
            } else {
1342
0
                to = page_locations[page_id + 1].first_row_index;
1343
0
            }
1344
0
            sig_stat.ranges[page_id] = RowRange {from, to};
1345
0
        }
1346
1347
0
        sig_stat.available = true;
1348
0
        *ans = &sig_stat;
1349
0
        return true;
1350
0
    };
1351
0
    cached_page_index.row_group_range = {0, row_group.num_rows};
1352
0
    cached_page_index.get_stat_func = get_stat_func;
1353
1354
0
    candidate_row_ranges->add({0, row_group.num_rows});
1355
0
    for (const auto& predicate : push_down_pred) {
1356
0
        RowRanges tmp_row_range;
1357
0
        if (!predicate->evaluate_and(&cached_page_index, &tmp_row_range)) {
1358
            // no need read this row group.
1359
0
            candidate_row_ranges->clear();
1360
0
            return Status::OK();
1361
0
        }
1362
0
        RowRanges::ranges_intersection(*candidate_row_ranges, tmp_row_range, candidate_row_ranges);
1363
0
    }
1364
0
    return Status::OK();
1365
0
}
1366
1367
Status ParquetReader::_process_min_max_bloom_filter(
1368
        const RowGroupReader::RowGroupIndex& row_group_index, const tparquet::RowGroup& row_group,
1369
        const std::vector<std::unique_ptr<MutilColumnBlockPredicate>>& push_down_pred,
1370
38
        RowRanges* row_ranges) {
1371
38
    SCOPED_RAW_TIMER(&_reader_statistics.row_group_filter_time);
1372
38
    if (!_filter_groups) {
1373
        // No row group filtering is needed;
1374
        // for example, Iceberg reads position delete files.
1375
1
        row_ranges->add({0, row_group.num_rows});
1376
1
        return Status::OK();
1377
1
    }
1378
1379
37
    if (_read_by_rows) {
1380
19
        auto group_start = row_group_index.first_row;
1381
19
        auto group_end = row_group_index.last_row;
1382
1383
47
        while (!_row_ids.empty()) {
1384
28
            auto v = _row_ids.front();
1385
28
            if (v < group_start) {
1386
0
                continue;
1387
28
            } else if (v < group_end) {
1388
28
                row_ranges->add(RowRange {v - group_start, v - group_start + 1});
1389
28
                _row_ids.pop_front();
1390
28
            } else {
1391
0
                break;
1392
0
            }
1393
28
        }
1394
19
    } else {
1395
18
        bool filter_this_row_group = false;
1396
18
        bool filtered_by_min_max = false;
1397
18
        bool filtered_by_bloom_filter = false;
1398
18
        RETURN_IF_ERROR(_process_column_stat_filter(row_group, push_down_pred,
1399
18
                                                    &filter_this_row_group, &filtered_by_min_max,
1400
18
                                                    &filtered_by_bloom_filter));
1401
        // Update statistics based on filter type
1402
18
        if (filter_this_row_group) {
1403
0
            if (filtered_by_min_max) {
1404
0
                _reader_statistics.filtered_row_groups_by_min_max++;
1405
0
            }
1406
0
            if (filtered_by_bloom_filter) {
1407
0
                _reader_statistics.filtered_row_groups_by_bloom_filter++;
1408
0
            }
1409
0
        }
1410
1411
18
        if (!filter_this_row_group) {
1412
18
            RETURN_IF_ERROR(_process_page_index_filter(row_group, row_group_index, push_down_pred,
1413
18
                                                       row_ranges));
1414
18
        }
1415
18
    }
1416
1417
37
    return Status::OK();
1418
37
}
1419
1420
Status ParquetReader::_process_column_stat_filter(
1421
        const tparquet::RowGroup& row_group,
1422
        const std::vector<std::unique_ptr<MutilColumnBlockPredicate>>& push_down_pred,
1423
20
        bool* filter_group, bool* filtered_by_min_max, bool* filtered_by_bloom_filter) {
1424
    // If both filters are disabled, skip filtering
1425
20
    if (!_enable_filter_by_min_max && !_enable_filter_by_bloom_filter) {
1426
0
        return Status::OK();
1427
0
    }
1428
1429
    // Cache bloom filters for each column to avoid reading the same bloom filter multiple times
1430
    // when there are multiple predicates on the same column
1431
20
    std::unordered_map<int, std::unique_ptr<ParquetBlockSplitBloomFilter>> bloom_filter_cache;
1432
1433
    // Initialize output parameters
1434
20
    *filtered_by_min_max = false;
1435
20
    *filtered_by_bloom_filter = false;
1436
1437
20
    for (const auto& predicate : _push_down_predicates) {
1438
2
        std::function<bool(ParquetPredicate::ColumnStat*, int)> get_stat_func =
1439
4
                [&](ParquetPredicate::ColumnStat* stat, const int cid) {
1440
                    // Check if min-max filter is enabled
1441
4
                    if (!_enable_filter_by_min_max) {
1442
0
                        return false;
1443
0
                    }
1444
4
                    auto* slot = _tuple_descriptor->slots()[cid];
1445
4
                    if (!_table_info_node_ptr->children_column_exists(slot->col_name())) {
1446
0
                        return false;
1447
0
                    }
1448
4
                    const auto& file_col_name =
1449
4
                            _table_info_node_ptr->children_file_column_name(slot->col_name());
1450
4
                    const FieldSchema* col_schema =
1451
4
                            _file_metadata->schema().get_column(file_col_name);
1452
4
                    int parquet_col_id = col_schema->physical_column_index;
1453
4
                    auto meta_data = row_group.columns[parquet_col_id].meta_data;
1454
4
                    stat->col_schema = col_schema;
1455
4
                    return ParquetPredicate::read_column_stats(col_schema, meta_data,
1456
4
                                                               &_ignored_stats,
1457
4
                                                               _t_metadata->created_by, stat)
1458
4
                            .ok();
1459
4
                };
1460
2
        std::function<bool(ParquetPredicate::ColumnStat*, int)> get_bloom_filter_func =
1461
2
                [&](ParquetPredicate::ColumnStat* stat, const int cid) {
1462
0
                    auto* slot = _tuple_descriptor->slots()[cid];
1463
0
                    if (!_table_info_node_ptr->children_column_exists(slot->col_name())) {
1464
0
                        return false;
1465
0
                    }
1466
0
                    const auto& file_col_name =
1467
0
                            _table_info_node_ptr->children_file_column_name(slot->col_name());
1468
0
                    const FieldSchema* col_schema =
1469
0
                            _file_metadata->schema().get_column(file_col_name);
1470
0
                    int parquet_col_id = col_schema->physical_column_index;
1471
0
                    auto meta_data = row_group.columns[parquet_col_id].meta_data;
1472
0
                    if (!meta_data.__isset.bloom_filter_offset) {
1473
0
                        return false;
1474
0
                    }
1475
0
                    auto primitive_type =
1476
0
                            remove_nullable(col_schema->data_type)->get_primitive_type();
1477
0
                    if (!ParquetPredicate::bloom_filter_supported(primitive_type)) {
1478
0
                        return false;
1479
0
                    }
1480
1481
                    // Check if bloom filter is enabled
1482
0
                    if (!_enable_filter_by_bloom_filter) {
1483
0
                        return false;
1484
0
                    }
1485
1486
                    // Check cache first
1487
0
                    auto cache_iter = bloom_filter_cache.find(parquet_col_id);
1488
0
                    if (cache_iter != bloom_filter_cache.end()) {
1489
                        // Bloom filter already loaded for this column, reuse it
1490
0
                        stat->bloom_filter = std::move(cache_iter->second);
1491
0
                        bloom_filter_cache.erase(cache_iter);
1492
0
                        return stat->bloom_filter != nullptr;
1493
0
                    }
1494
1495
0
                    if (!stat->bloom_filter) {
1496
0
                        SCOPED_RAW_TIMER(&_reader_statistics.bloom_filter_read_time);
1497
0
                        auto st = ParquetPredicate::read_bloom_filter(
1498
0
                                meta_data, _tracing_file_reader, _io_ctx, stat);
1499
0
                        if (!st.ok()) {
1500
0
                            LOG(WARNING) << "Failed to read bloom filter for column "
1501
0
                                         << col_schema->name << " in file " << _scan_range.path
1502
0
                                         << ", status: " << st.to_string();
1503
0
                            stat->bloom_filter.reset();
1504
0
                            return false;
1505
0
                        }
1506
0
                    }
1507
0
                    return stat->bloom_filter != nullptr;
1508
0
                };
1509
2
        ParquetPredicate::ColumnStat stat;
1510
2
        stat.ctz = _ctz;
1511
2
        stat.get_stat_func = &get_stat_func;
1512
2
        stat.get_bloom_filter_func = &get_bloom_filter_func;
1513
1514
2
        if (!predicate->evaluate_and(&stat)) {
1515
1
            *filter_group = true;
1516
1517
            // Track which filter was used for filtering
1518
            // If bloom filter was loaded, it means bloom filter was used
1519
1
            if (stat.bloom_filter) {
1520
0
                *filtered_by_bloom_filter = true;
1521
0
            }
1522
            // If col_schema was set but no bloom filter, it means min-max stats were used
1523
1
            if (stat.col_schema && !stat.bloom_filter) {
1524
1
                *filtered_by_min_max = true;
1525
1
            }
1526
1527
1
            return Status::OK();
1528
1
        }
1529
1530
        // After evaluating, if the bloom filter was used, cache it for subsequent predicates
1531
1
        if (stat.bloom_filter) {
1532
            // Find the column id for caching
1533
0
            for (auto* slot : _tuple_descriptor->slots()) {
1534
0
                if (_table_info_node_ptr->children_column_exists(slot->col_name())) {
1535
0
                    const auto& file_col_name =
1536
0
                            _table_info_node_ptr->children_file_column_name(slot->col_name());
1537
0
                    const FieldSchema* col_schema =
1538
0
                            _file_metadata->schema().get_column(file_col_name);
1539
0
                    int parquet_col_id = col_schema->physical_column_index;
1540
0
                    if (stat.col_schema == col_schema) {
1541
0
                        bloom_filter_cache[parquet_col_id] = std::move(stat.bloom_filter);
1542
0
                        break;
1543
0
                    }
1544
0
                }
1545
0
            }
1546
0
        }
1547
1
    }
1548
1549
    // Update filter statistics if this row group was not filtered
1550
    // The statistics will be updated in _init_row_groups when filter_group is true
1551
19
    return Status::OK();
1552
20
}
1553
1554
74
int64_t ParquetReader::_get_column_start_offset(const tparquet::ColumnMetaData& column) const {
1555
74
    return has_dict_page(column) ? column.dictionary_page_offset : column.data_page_offset;
1556
74
}
1557
1558
14
void ParquetReader::_collect_profile() {
1559
14
    if (_profile == nullptr) {
1560
0
        return;
1561
0
    }
1562
1563
14
    if (_current_group_reader != nullptr) {
1564
14
        _current_group_reader->collect_profile_before_close();
1565
14
    }
1566
14
    COUNTER_UPDATE(_parquet_profile.filtered_row_groups, _reader_statistics.filtered_row_groups);
1567
14
    COUNTER_UPDATE(_parquet_profile.filtered_row_groups_by_min_max,
1568
14
                   _reader_statistics.filtered_row_groups_by_min_max);
1569
14
    COUNTER_UPDATE(_parquet_profile.filtered_row_groups_by_bloom_filter,
1570
14
                   _reader_statistics.filtered_row_groups_by_bloom_filter);
1571
14
    COUNTER_UPDATE(_parquet_profile.to_read_row_groups, _reader_statistics.read_row_groups);
1572
14
    COUNTER_UPDATE(_parquet_profile.total_row_groups, _total_groups);
1573
14
    COUNTER_UPDATE(_parquet_profile.filtered_group_rows, _reader_statistics.filtered_group_rows);
1574
14
    COUNTER_UPDATE(_parquet_profile.filtered_page_rows, _reader_statistics.filtered_page_rows);
1575
14
    COUNTER_UPDATE(_parquet_profile.lazy_read_filtered_rows,
1576
14
                   _reader_statistics.lazy_read_filtered_rows);
1577
14
    COUNTER_UPDATE(_parquet_profile.filtered_bytes, _reader_statistics.filtered_bytes);
1578
14
    COUNTER_UPDATE(_parquet_profile.raw_rows_read, _reader_statistics.read_rows);
1579
14
    COUNTER_UPDATE(_parquet_profile.column_read_time, _reader_statistics.column_read_time);
1580
14
    COUNTER_UPDATE(_parquet_profile.parse_meta_time, _reader_statistics.parse_meta_time);
1581
14
    COUNTER_UPDATE(_parquet_profile.parse_footer_time, _reader_statistics.parse_footer_time);
1582
14
    COUNTER_UPDATE(_parquet_profile.file_reader_create_time,
1583
14
                   _reader_statistics.file_reader_create_time);
1584
14
    COUNTER_UPDATE(_parquet_profile.open_file_num, _reader_statistics.open_file_num);
1585
14
    COUNTER_UPDATE(_parquet_profile.page_index_filter_time,
1586
14
                   _reader_statistics.page_index_filter_time);
1587
14
    COUNTER_UPDATE(_parquet_profile.read_page_index_time, _reader_statistics.read_page_index_time);
1588
14
    COUNTER_UPDATE(_parquet_profile.parse_page_index_time,
1589
14
                   _reader_statistics.parse_page_index_time);
1590
14
    COUNTER_UPDATE(_parquet_profile.row_group_filter_time,
1591
14
                   _reader_statistics.row_group_filter_time);
1592
14
    COUNTER_UPDATE(_parquet_profile.file_footer_read_calls,
1593
14
                   _reader_statistics.file_footer_read_calls);
1594
14
    COUNTER_UPDATE(_parquet_profile.file_footer_hit_cache,
1595
14
                   _reader_statistics.file_footer_hit_cache);
1596
1597
14
    COUNTER_UPDATE(_parquet_profile.skip_page_header_num, _column_statistics.skip_page_header_num);
1598
14
    COUNTER_UPDATE(_parquet_profile.parse_page_header_num,
1599
14
                   _column_statistics.parse_page_header_num);
1600
14
    COUNTER_UPDATE(_parquet_profile.predicate_filter_time,
1601
14
                   _reader_statistics.predicate_filter_time);
1602
14
    COUNTER_UPDATE(_parquet_profile.dict_filter_rewrite_time,
1603
14
                   _reader_statistics.dict_filter_rewrite_time);
1604
14
    COUNTER_UPDATE(_parquet_profile.convert_time, _column_statistics.convert_time);
1605
14
    COUNTER_UPDATE(_parquet_profile.bloom_filter_read_time,
1606
14
                   _reader_statistics.bloom_filter_read_time);
1607
14
    COUNTER_UPDATE(_parquet_profile.page_index_read_calls,
1608
14
                   _column_statistics.page_index_read_calls);
1609
14
    COUNTER_UPDATE(_parquet_profile.decompress_time, _column_statistics.decompress_time);
1610
14
    COUNTER_UPDATE(_parquet_profile.decompress_cnt, _column_statistics.decompress_cnt);
1611
14
    COUNTER_UPDATE(_parquet_profile.page_read_counter, _column_statistics.page_read_counter);
1612
14
    COUNTER_UPDATE(_parquet_profile.page_cache_write_counter,
1613
14
                   _column_statistics.page_cache_write_counter);
1614
14
    COUNTER_UPDATE(_parquet_profile.page_cache_compressed_write_counter,
1615
14
                   _column_statistics.page_cache_compressed_write_counter);
1616
14
    COUNTER_UPDATE(_parquet_profile.page_cache_decompressed_write_counter,
1617
14
                   _column_statistics.page_cache_decompressed_write_counter);
1618
14
    COUNTER_UPDATE(_parquet_profile.page_cache_hit_counter,
1619
14
                   _column_statistics.page_cache_hit_counter);
1620
14
    COUNTER_UPDATE(_parquet_profile.page_cache_missing_counter,
1621
14
                   _column_statistics.page_cache_missing_counter);
1622
14
    COUNTER_UPDATE(_parquet_profile.page_cache_compressed_hit_counter,
1623
14
                   _column_statistics.page_cache_compressed_hit_counter);
1624
14
    COUNTER_UPDATE(_parquet_profile.page_cache_decompressed_hit_counter,
1625
14
                   _column_statistics.page_cache_decompressed_hit_counter);
1626
14
    COUNTER_UPDATE(_parquet_profile.decode_header_time, _column_statistics.decode_header_time);
1627
14
    COUNTER_UPDATE(_parquet_profile.read_page_header_time,
1628
14
                   _column_statistics.read_page_header_time);
1629
14
    COUNTER_UPDATE(_parquet_profile.decode_value_time, _column_statistics.decode_value_time);
1630
14
    COUNTER_UPDATE(_parquet_profile.decode_dict_time, _column_statistics.decode_dict_time);
1631
14
    COUNTER_UPDATE(_parquet_profile.decode_level_time, _column_statistics.decode_level_time);
1632
14
    COUNTER_UPDATE(_parquet_profile.decode_null_map_time, _column_statistics.decode_null_map_time);
1633
14
}
1634
1635
14
void ParquetReader::_collect_profile_before_close() {
1636
14
    _collect_profile();
1637
14
}
1638
1639
} // namespace doris