From e97d27d3275092cb73bdf5989f383983796ea62a Mon Sep 17 00:00:00 2001 From: lxy264173 Date: Wed, 25 Nov 2026 20:43:28 +0800 Subject: [PATCH 1/3] refactor(index)!: unify file and realtime index results --- docs/source/api/file_index.rst | 12 +- .../paimon/file_index/bitmap_index_result.h | 63 --------- include/paimon/file_index/file_index_reader.h | 1 - include/paimon/file_index/file_index_result.h | 78 ++--------- include/paimon/index/bitmap_result.h | 59 ++++++++ include/paimon/index/index_result.h | 89 ++++++++++++ .../scored_index_result.h} | 39 +++--- .../realtime/index/realtime_index_reader.h | 43 +++--- .../realtime/index/realtime_index_result.h | 39 +----- .../index/scored_realtime_index_result.h | 55 -------- src/paimon/CMakeLists.txt | 6 +- .../bitmap/apply_bitmap_index_batch_reader.h | 2 +- .../file_index/bitmap/bitmap_file_index.cpp | 2 +- .../bitmap/bitmap_file_index_test.cpp | 2 +- .../file_index/bitmap/bitmap_index_result.cpp | 103 -------------- .../bitmap/bitmap_index_result_test.cpp | 3 +- .../bsi/bit_slice_index_bitmap_file_index.cpp | 2 +- ...bit_slice_index_bitmap_file_index_test.cpp | 2 +- .../empty/empty_file_index_reader.h | 2 - .../empty/empty_file_index_reader_test.cpp | 2 +- .../file_index/file_index_format_test.cpp | 1 - .../common/file_index/file_index_reader.cpp | 26 +--- .../common/file_index/file_index_result.cpp | 68 ---------- .../file_index/file_index_result_test.cpp | 2 - .../rangebitmap/range_bitmap_file_index.cpp | 2 +- .../range_bitmap_file_index_test.cpp | 2 +- .../rangebitmap/range_bitmap_io_test.cpp | 2 +- .../file_index/scored_file_index_result.cpp | 87 ------------ .../scored_file_index_result_test.cpp | 4 +- .../range_bitmap_global_index_test.cpp | 2 +- .../wrap/file_index_reader_wrapper.h | 2 +- .../wrap/file_index_reader_wrapper_test.cpp | 2 +- src/paimon/common/index/bitmap_result.cpp | 128 ++++++++++++++++++ src/paimon/common/index/index_reader_utils.h | 125 +++++++++++------ src/paimon/common/index/index_result.cpp | 93 +++++++++++++ .../common/index/scored_index_result.cpp | 99 ++++++++++++++ src/paimon/core/io/file_index_evaluator.cpp | 15 +- src/paimon/core/io/file_index_evaluator.h | 2 +- .../core/io/file_index_evaluator_test.cpp | 3 +- .../core/operation/abstract_split_read.cpp | 1 - .../operation/data_evolution_split_read.cpp | 1 - .../operation/precise_file_index_read.cpp | 4 +- .../core/operation/precise_file_index_read.h | 4 +- .../precise_file_index_read_test.cpp | 4 +- .../core/operation/precise_index_evaluator.h | 73 +++------- .../core/realtime/arrow_realtime_store.cpp | 11 +- .../index/hash/hash_realtime_index.cpp | 13 +- .../realtime/index/hash/hash_realtime_index.h | 4 +- .../index/realtime_index_evaluator.cpp | 55 ++++---- .../realtime/index/realtime_index_evaluator.h | 8 +- .../realtime/index/realtime_index_reader.cpp | 87 ++++++------ .../realtime/index/realtime_index_test.cpp | 44 ++++-- .../realtime/precise_realtime_index_read.cpp | 2 +- .../precise_realtime_index_read_test.cpp | 11 +- .../realtime_offset_file_index_lookup.cpp | 2 +- .../indexer/lumina/lumina_file_index.cpp | 2 +- .../lumina/lumina_realtime_index_test.cpp | 8 +- .../testing/mock/mock_search_file_index.cpp | 3 +- .../mock/mock_search_realtime_index_reader.h | 3 +- 59 files changed, 811 insertions(+), 798 deletions(-) delete mode 100644 include/paimon/file_index/bitmap_index_result.h create mode 100644 include/paimon/index/bitmap_result.h create mode 100644 include/paimon/index/index_result.h rename include/paimon/{file_index/scored_file_index_result.h => index/scored_index_result.h} (58%) delete mode 100644 include/paimon/realtime/index/scored_realtime_index_result.h delete mode 100644 src/paimon/common/file_index/bitmap/bitmap_index_result.cpp delete mode 100644 src/paimon/common/file_index/file_index_result.cpp delete mode 100644 src/paimon/common/file_index/scored_file_index_result.cpp create mode 100644 src/paimon/common/index/bitmap_result.cpp create mode 100644 src/paimon/common/index/index_result.cpp create mode 100644 src/paimon/common/index/scored_index_result.cpp diff --git a/docs/source/api/file_index.rst b/docs/source/api/file_index.rst index c9fedf377..a89ac1ad1 100644 --- a/docs/source/api/file_index.rst +++ b/docs/source/api/file_index.rst @@ -47,10 +47,18 @@ Interface :members: :undoc-members: -.. doxygenclass:: paimon::FileIndexResult +.. doxygentypedef:: paimon::FileIndexResult + +.. doxygenclass:: paimon::IndexResult + :members: + :undoc-members: + +.. doxygentypedef:: paimon::BitmapIndexResult + +.. doxygenclass:: paimon::BitmapResult :members: :undoc-members: -.. doxygenclass:: paimon::BitmapIndexResult +.. doxygenclass:: paimon::ScoredIndexResult :members: :undoc-members: diff --git a/include/paimon/file_index/bitmap_index_result.h b/include/paimon/file_index/bitmap_index_result.h deleted file mode 100644 index 1a38aac8e..000000000 --- a/include/paimon/file_index/bitmap_index_result.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include - -#include "paimon/file_index/file_index_result.h" -#include "paimon/result.h" -#include "paimon/utils/roaring_bitmap32.h" -#include "paimon/visibility.h" - -namespace paimon { -/// The implementation of bitmap file index result, represents row granularity. -/// @note The inner bitmap in BitmapIndexResult is lazily initialized only when -/// the result is about to be used. -class PAIMON_EXPORT BitmapIndexResult : public FileIndexResult { - public: - using BitmapSupplier = std::function()>; - - explicit BitmapIndexResult(BitmapSupplier bitmap_supplier, bool is_exact = false); - ~BitmapIndexResult() override; - - /// @return Whether the file is remained. - Result IsRemain() const override; - - /// Compute the intersection of the current result with the provided result. - Result> And( - const std::shared_ptr& other) override; - - /// Compute the union of the current result with the provided result. - Result> Or( - const std::shared_ptr& other) override; - - /// @return Inner `RoaringBitmap32`. - Result GetBitmap() const; - - std::string ToString() const override; - - private: - mutable bool initialized_ = false; - BitmapSupplier bitmap_supplier_; - mutable RoaringBitmap32 bitmap_; -}; - -} // namespace paimon diff --git a/include/paimon/file_index/file_index_reader.h b/include/paimon/file_index/file_index_reader.h index 7ca61fb53..d1ffc8750 100644 --- a/include/paimon/file_index/file_index_reader.h +++ b/include/paimon/file_index/file_index_reader.h @@ -23,7 +23,6 @@ #include #include "paimon/file_index/file_index_result.h" -#include "paimon/file_index/scored_file_index_result.h" #include "paimon/index/index_reader_capabilities.h" #include "paimon/predicate/full_text_search.h" #include "paimon/predicate/function_visitor.h" diff --git a/include/paimon/file_index/file_index_result.h b/include/paimon/file_index/file_index_result.h index f7855171b..cd8805f93 100644 --- a/include/paimon/file_index/file_index_result.h +++ b/include/paimon/file_index/file_index_result.h @@ -18,77 +18,17 @@ #pragma once -#include -#include -#include - -#include "paimon/defs.h" -#include "paimon/result.h" -#include "paimon/visibility.h" +#include "paimon/index/bitmap_result.h" +#include "paimon/index/index_result.h" +#include "paimon/index/scored_index_result.h" +#include "paimon/utils/roaring_bitmap32.h" namespace paimon { -/// File index result to decide whether filter a file. -class PAIMON_EXPORT FileIndexResult : public std::enable_shared_from_this { - public: - virtual ~FileIndexResult() = default; - - /// @return A shared instance representing "retain the file". - /// @note This is a singleton-like utility; all calls return equivalent objects. - static std::shared_ptr Remain(); - - /// @return A shared instance representing "skip the file". - /// @note This is a singleton-like utility; all calls return equivalent objects. - static std::shared_ptr Skip(); - - /// @return Whether the file is remained. - virtual Result IsRemain() const = 0; - - /// Whether these rows exactly match the evaluated predicate within its candidate scope. - bool IsExact() const { - return is_exact_; - } - - /// Compute the intersection for two predicates, conservatively propagating precision. - virtual Result> And( - const std::shared_ptr& other) = 0; - - /// Compute the union for two predicates, conservatively propagating precision. - virtual Result> Or( - const std::shared_ptr& other) = 0; - - virtual std::string ToString() const = 0; - - protected: - explicit FileIndexResult(bool is_exact) : is_exact_(is_exact) {} - - private: - bool is_exact_; -}; - -/// Concrete implementation of FileIndexResult that always retains the file. -class PAIMON_EXPORT Remain : public FileIndexResult { - public: - Remain() : FileIndexResult(false) {} - - Result IsRemain() const override; - Result> And( - const std::shared_ptr& other) override; - Result> Or( - const std::shared_ptr& other) override; - std::string ToString() const override; -}; - -/// Concrete implementation of FileIndexResult that always skips the file. -class PAIMON_EXPORT Skip : public FileIndexResult { - public: - Skip() : FileIndexResult(true) {} - Result IsRemain() const override; - Result> And( - const std::shared_ptr& other) override; - Result> Or( - const std::shared_ptr& other) override; - std::string ToString() const override; -}; +using FileIndexResult = IndexResult; +using BitmapIndexResult = BitmapResult; +using ScoredFileIndexResult = ScoredIndexResult; +using Remain = RemainIndexResult; +using Skip = SkipIndexResult; } // namespace paimon diff --git a/include/paimon/index/bitmap_result.h b/include/paimon/index/bitmap_result.h new file mode 100644 index 000000000..2b0ed7358 --- /dev/null +++ b/include/paimon/index/bitmap_result.h @@ -0,0 +1,59 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include +#include + +#include "paimon/index/index_result.h" + +namespace paimon { + +/// Lazily loaded row positions, shared by file and real-time index results. +template +class PAIMON_EXPORT BitmapResult : public IndexResult { + public: + using BitmapSupplier = std::function()>; + + /// Construct a materialized result, rejecting negative row positions. + static Result>> Create(Bitmap rows, bool is_exact); + + explicit BitmapResult(BitmapSupplier bitmap_supplier, bool is_exact = false); + + Result IsRemain() const override; + + /// Load the bitmap if needed. The result owns the returned bitmap. + Result GetBitmap() const; + + Result>> And( + const std::shared_ptr>& other) override; + Result>> Or( + const std::shared_ptr>& other) override; + std::string ToString() const override; + + private: + BitmapResult(Bitmap rows, bool is_exact); + + mutable bool initialized_ = false; + BitmapSupplier bitmap_supplier_; + mutable Bitmap bitmap_; +}; + +} // namespace paimon diff --git a/include/paimon/index/index_result.h b/include/paimon/index/index_result.h new file mode 100644 index 000000000..9d2094cde --- /dev/null +++ b/include/paimon/index/index_result.h @@ -0,0 +1,89 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "paimon/result.h" +#include "paimon/visibility.h" + +namespace paimon { + +/// An index result within one source, read view and candidate scope. +/// Implementations are provided for RoaringBitmap32 and RoaringBitmap64. +/// Bitmap constrains And/Or to compatible result types; this base class stores no bitmap. +/// Exact results contain all and only matching rows. Inexact results may omit matches. +template +class PAIMON_EXPORT IndexResult : public std::enable_shared_from_this> { + public: + virtual ~IndexResult() = default; + + static std::shared_ptr> Remain(); + static std::shared_ptr> Skip(); + + bool IsExact() const { + return is_exact_; + } + + /// Whether the result retains candidates. This alone does not establish exactness. + virtual Result IsRemain() const = 0; + + /// Combine different predicates over the same source, view and candidate scope. + virtual Result>> And( + const std::shared_ptr>& other) = 0; + virtual Result>> Or( + const std::shared_ptr>& other) = 0; + + virtual std::string ToString() const = 0; + + protected: + explicit IndexResult(bool is_exact) : is_exact_(is_exact) {} + + private: + bool is_exact_; +}; + +template +class PAIMON_EXPORT RemainIndexResult : public IndexResult { + public: + RemainIndexResult() : IndexResult(false) {} + + Result IsRemain() const override; + Result>> And( + const std::shared_ptr>& other) override; + Result>> Or( + const std::shared_ptr>& other) override; + std::string ToString() const override; +}; + +template +class PAIMON_EXPORT SkipIndexResult : public IndexResult { + public: + SkipIndexResult() : IndexResult(true) {} + + Result IsRemain() const override; + Result>> And( + const std::shared_ptr>& other) override; + Result>> Or( + const std::shared_ptr>& other) override; + std::string ToString() const override; +}; + +} // namespace paimon diff --git a/include/paimon/file_index/scored_file_index_result.h b/include/paimon/index/scored_index_result.h similarity index 58% rename from include/paimon/file_index/scored_file_index_result.h rename to include/paimon/index/scored_index_result.h index e9c817d6f..ef7af0329 100644 --- a/include/paimon/file_index/scored_file_index_result.h +++ b/include/paimon/index/scored_index_result.h @@ -22,33 +22,29 @@ #include #include -#include "paimon/file_index/file_index_result.h" -#include "paimon/result.h" -#include "paimon/utils/roaring_bitmap32.h" -#include "paimon/visibility.h" +#include "paimon/index/index_result.h" namespace paimon { -/// File-local search result. Scores correspond to row positions in ascending order. -class PAIMON_EXPORT ScoredFileIndexResult : public FileIndexResult { +/// Scores follow ascending row positions, not ranking order. +/// IsExact() describes predicate matching within the candidate scope, +/// not search recall or global TopK completeness. +template +class PAIMON_EXPORT ScoredIndexResult : public IndexResult { public: - static Result> Create(RoaringBitmap32&& row_positions, - std::vector&& scores, - bool is_exact = false); + static Result>> Create(Bitmap rows, + std::vector scores, + bool is_exact = false); bool IsEmpty() const { return row_positions_.IsEmpty(); } - Result IsRemain() const override; - - Result> And( - const std::shared_ptr& other) override; - - Result> Or( - const std::shared_ptr& other) override; + Result IsRemain() const override { + return !IsEmpty(); + } - const RoaringBitmap32& GetRowPositions() const { + const Bitmap& GetRowPositions() const { return row_positions_; } @@ -56,13 +52,16 @@ class PAIMON_EXPORT ScoredFileIndexResult : public FileIndexResult { return scores_; } + Result>> And( + const std::shared_ptr>& other) override; + Result>> Or( + const std::shared_ptr>& other) override; std::string ToString() const override; private: - ScoredFileIndexResult(RoaringBitmap32&& row_positions, std::vector&& scores, - bool is_exact); + ScoredIndexResult(Bitmap rows, std::vector scores, bool is_exact); - RoaringBitmap32 row_positions_; + Bitmap row_positions_; std::vector scores_; }; diff --git a/include/paimon/realtime/index/realtime_index_reader.h b/include/paimon/realtime/index/realtime_index_reader.h index 35666898e..c306da170 100644 --- a/include/paimon/realtime/index/realtime_index_reader.h +++ b/include/paimon/realtime/index/realtime_index_reader.h @@ -26,7 +26,6 @@ #include "paimon/index/index_reader_capabilities.h" #include "paimon/predicate/function_visitor.h" #include "paimon/realtime/index/realtime_index_result.h" -#include "paimon/realtime/index/scored_realtime_index_result.h" #include "paimon/utils/roaring_bitmap64.h" #include "paimon/visibility.h" @@ -37,13 +36,19 @@ struct FullTextSearch; struct FullTextMatch; /// Visits predicates on one indexed field, returning realtime offsets. -/// nullopt means no pruning; an empty bitmap means no candidates. False negatives are not allowed. +/// Remain means no pruning; Skip means no candidates. Scalar visits must not omit matches. +/// IsExact() additionally guarantees that all returned candidates satisfy the predicate. /// Unsupported predicates default to no pruning. Plugins override only the supported visits. -class PAIMON_EXPORT RealtimeIndexReader : public IndexReaderCapabilities, - public FunctionVisitor> { +class PAIMON_EXPORT RealtimeIndexReader + : public IndexReaderCapabilities, + public FunctionVisitor> { public: ~RealtimeIndexReader() override = default; + /// Evaluate within eligible offsets, preserving result exactness. Null means the source range. + virtual Result> Evaluate( + const std::shared_ptr& predicate, const RoaringBitmap64* candidates); + /// Search pre-filters and result IDs use real-time offsets, not file-local row positions. /// Apply filters and pinned visibility before TopK; filtering a truncated result is /// insufficient. Search results must be stable for the pinned snapshot even while later writes @@ -60,21 +65,23 @@ class PAIMON_EXPORT RealtimeIndexReader : public IndexReaderCapabilities, virtual Result> VisitFullTextMatch( const std::shared_ptr& match, bool needs_scores); - Result> VisitIsNotNull() override; - Result> VisitIsNull() override; - Result> VisitEqual(const Literal& literal) override; - Result> VisitNotEqual(const Literal& literal) override; - Result> VisitLessThan(const Literal& literal) override; - Result> VisitLessOrEqual(const Literal& literal) override; - Result> VisitGreaterThan(const Literal& literal) override; - Result> VisitGreaterOrEqual(const Literal& literal) override; - Result> VisitIn(const std::vector& literals) override; - Result> VisitNotIn( + Result> VisitIsNotNull() override; + Result> VisitIsNull() override; + Result> VisitEqual(const Literal& literal) override; + Result> VisitNotEqual(const Literal& literal) override; + Result> VisitLessThan(const Literal& literal) override; + Result> VisitLessOrEqual(const Literal& literal) override; + Result> VisitGreaterThan(const Literal& literal) override; + Result> VisitGreaterOrEqual( + const Literal& literal) override; + Result> VisitIn( + const std::vector& literals) override; + Result> VisitNotIn( const std::vector& literals) override; - Result> VisitStartsWith(const Literal& literal) override; - Result> VisitEndsWith(const Literal& literal) override; - Result> VisitContains(const Literal& literal) override; - Result> VisitLike(const Literal& literal) override; + Result> VisitStartsWith(const Literal& literal) override; + Result> VisitEndsWith(const Literal& literal) override; + Result> VisitContains(const Literal& literal) override; + Result> VisitLike(const Literal& literal) override; }; } // namespace paimon diff --git a/include/paimon/realtime/index/realtime_index_result.h b/include/paimon/realtime/index/realtime_index_result.h index ae19075d9..c0be1a135 100644 --- a/include/paimon/realtime/index/realtime_index_result.h +++ b/include/paimon/realtime/index/realtime_index_result.h @@ -18,44 +18,13 @@ #pragma once -#include -#include - -#include "paimon/macros.h" -#include "paimon/result.h" +#include "paimon/index/index_result.h" +#include "paimon/index/scored_index_result.h" #include "paimon/utils/roaring_bitmap64.h" -#include "paimon/visibility.h" namespace paimon { -/// Matching real-time offsets. ScoredRealtimeIndexResult additionally carries scores. -class PAIMON_EXPORT RealtimeIndexResult { - public: - virtual ~RealtimeIndexResult() = default; - - static Result> Create(RoaringBitmap64 rows) { - PAIMON_RETURN_NOT_OK(ValidateRowPositions(rows)); - return std::shared_ptr(new RealtimeIndexResult(std::move(rows))); - } - - const RoaringBitmap64& GetRowPositions() const { - return rows_; - } - - protected: - explicit RealtimeIndexResult(RoaringBitmap64 rows) : rows_(std::move(rows)) {} - - static Status ValidateRowPositions(const RoaringBitmap64& rows) { - for (auto iter = rows.Begin(); iter != rows.End(); ++iter) { - if (*iter < 0) { - return Status::Invalid("Real-time search returned a negative offset"); - } - } - return Status::OK(); - } - - private: - RoaringBitmap64 rows_; -}; +using RealtimeIndexResult = IndexResult; +using ScoredRealtimeIndexResult = ScoredIndexResult; } // namespace paimon diff --git a/include/paimon/realtime/index/scored_realtime_index_result.h b/include/paimon/realtime/index/scored_realtime_index_result.h deleted file mode 100644 index 7d3a6fd9d..000000000 --- a/include/paimon/realtime/index/scored_realtime_index_result.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include - -#include "paimon/realtime/index/realtime_index_result.h" -#include "paimon/utils/roaring_bitmap64.h" -#include "paimon/visibility.h" - -namespace paimon { - -/// Search results keyed by real-time offset. Scores follow ascending offset order, not rank. -class PAIMON_EXPORT ScoredRealtimeIndexResult : public RealtimeIndexResult { - public: - static Result> Create(RoaringBitmap64 rows, - std::vector scores) { - if (rows.Cardinality() != static_cast(scores.size())) { - return Status::Invalid("Real-time search score count does not match offsets"); - } - PAIMON_RETURN_NOT_OK(ValidateRowPositions(rows)); - return std::shared_ptr( - new ScoredRealtimeIndexResult(std::move(rows), std::move(scores))); - } - - const std::vector& GetScores() const { - return scores_; - } - - private: - ScoredRealtimeIndexResult(RoaringBitmap64 rows, std::vector scores) - : RealtimeIndexResult(std::move(rows)), scores_(std::move(scores)) {} - - std::vector scores_; -}; - -} // namespace paimon diff --git a/src/paimon/CMakeLists.txt b/src/paimon/CMakeLists.txt index 60fc81ed4..866bfbe40 100644 --- a/src/paimon/CMakeLists.txt +++ b/src/paimon/CMakeLists.txt @@ -68,7 +68,7 @@ set(PAIMON_COMMON_SRCS common/factories/singleton.cpp common/factories/io_hook.cpp common/factories/factory_creator.cpp - common/file_index/bitmap/bitmap_index_result.cpp + common/index/bitmap_result.cpp common/file_index/file_indexer.cpp common/file_index/file_indexer_factory.cpp common/file_index/file_index_format.cpp @@ -77,8 +77,8 @@ set(PAIMON_COMMON_SRCS common/file_index/file_index_format_v2.cpp common/file_index/file_index_reader.cpp common/file_index/file_index_writer.cpp - common/file_index/file_index_result.cpp - common/file_index/scored_file_index_result.cpp + common/index/index_result.cpp + common/index/scored_index_result.cpp common/format/column_stats.cpp common/format/file_format_factory.cpp common/fs/file_system.cpp diff --git a/src/paimon/common/file_index/bitmap/apply_bitmap_index_batch_reader.h b/src/paimon/common/file_index/bitmap/apply_bitmap_index_batch_reader.h index 114e56b92..3022ed5f2 100644 --- a/src/paimon/common/file_index/bitmap/apply_bitmap_index_batch_reader.h +++ b/src/paimon/common/file_index/bitmap/apply_bitmap_index_batch_reader.h @@ -26,7 +26,7 @@ #include "arrow/c/bridge.h" #include "arrow/c/helpers.h" #include "paimon/common/reader/reader_utils.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/reader/file_batch_reader.h" #include "paimon/result.h" #include "paimon/status.h" diff --git a/src/paimon/common/file_index/bitmap/bitmap_file_index.cpp b/src/paimon/common/file_index/bitmap/bitmap_file_index.cpp index 7be69e036..ee1514078 100644 --- a/src/paimon/common/file_index/bitmap/bitmap_file_index.cpp +++ b/src/paimon/common/file_index/bitmap/bitmap_file_index.cpp @@ -35,7 +35,7 @@ #include "paimon/common/utils/options_utils.h" #include "paimon/data/timestamp.h" #include "paimon/defs.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/fs/file_system.h" #include "paimon/io/data_input_stream.h" #include "paimon/memory/bytes.h" diff --git a/src/paimon/common/file_index/bitmap/bitmap_file_index_test.cpp b/src/paimon/common/file_index/bitmap/bitmap_file_index_test.cpp index 6bf9f6d28..32c4d8f67 100644 --- a/src/paimon/common/file_index/bitmap/bitmap_file_index_test.cpp +++ b/src/paimon/common/file_index/bitmap/bitmap_file_index_test.cpp @@ -30,7 +30,7 @@ #include "paimon/common/utils/math.h" #include "paimon/data/timestamp.h" #include "paimon/defs.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/fs/file_system.h" #include "paimon/fs/local/local_file_system.h" #include "paimon/io/byte_array_input_stream.h" diff --git a/src/paimon/common/file_index/bitmap/bitmap_index_result.cpp b/src/paimon/common/file_index/bitmap/bitmap_index_result.cpp deleted file mode 100644 index 01120ca0a..000000000 --- a/src/paimon/common/file_index/bitmap/bitmap_index_result.cpp +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "paimon/file_index/bitmap_index_result.h" - -#include - -#include "paimon/common/utils/checked_cast.h" -#include "paimon/status.h" - -namespace paimon { -BitmapIndexResult::BitmapIndexResult(BitmapSupplier bitmap_supplier, bool is_exact) - : FileIndexResult(is_exact), bitmap_supplier_(std::move(bitmap_supplier)) {} - -BitmapIndexResult::~BitmapIndexResult() = default; - -Result BitmapIndexResult::GetBitmap() const { - if (!initialized_) { - PAIMON_ASSIGN_OR_RAISE(bitmap_, bitmap_supplier_()); - initialized_ = true; - } - return &bitmap_; -} - -Result BitmapIndexResult::IsRemain() const { - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* bitmap, GetBitmap()); - return !bitmap->IsEmpty(); -} - -Result> BitmapIndexResult::And( - const std::shared_ptr& other) { - if (auto typed_other = std::dynamic_pointer_cast(other)) { - return std::make_shared( - [result = std::dynamic_pointer_cast(shared_from_this()), - typed_other]() -> Result { - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* bitmap, result->GetBitmap()); - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* other_bitmap, - typed_other->GetBitmap()); - return RoaringBitmap32::And(*bitmap, *other_bitmap); - }, - IsExact() && other->IsExact()); - } else if (std::dynamic_pointer_cast(other)) { - if (!IsExact()) { - return shared_from_this(); - } - return std::make_shared( - [result = checked_pointer_cast( - shared_from_this())]() -> Result { - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* bitmap, result->GetBitmap()); - return *bitmap; - }, - /*is_exact=*/false); - } else if (std::dynamic_pointer_cast(other)) { - return FileIndexResult::Skip(); - } else { - return Status::Invalid("Cannot AND BitmapIndexResult with unsupported result type"); - } -} - -Result> BitmapIndexResult::Or( - const std::shared_ptr& other) { - if (auto typed_other = std::dynamic_pointer_cast(other)) { - return std::make_shared( - [result = std::dynamic_pointer_cast(shared_from_this()), - typed_other]() -> Result { - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* bitmap, result->GetBitmap()); - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* other_bitmap, - typed_other->GetBitmap()); - return RoaringBitmap32::Or(*bitmap, *other_bitmap); - }, - IsExact() && other->IsExact()); - } else if (std::dynamic_pointer_cast(other)) { - return FileIndexResult::Remain(); - } else if (std::dynamic_pointer_cast(other)) { - return shared_from_this(); - } else { - return Status::Invalid("Cannot OR BitmapIndexResult with unsupported result type"); - } -} - -std::string BitmapIndexResult::ToString() const { - auto bitmap = GetBitmap(); - if (!bitmap.ok()) { - return bitmap.status().ToString(); - } - return bitmap.value()->ToString(); -} -} // namespace paimon diff --git a/src/paimon/common/file_index/bitmap/bitmap_index_result_test.cpp b/src/paimon/common/file_index/bitmap/bitmap_index_result_test.cpp index 050f28b60..308982c9d 100644 --- a/src/paimon/common/file_index/bitmap/bitmap_index_result_test.cpp +++ b/src/paimon/common/file_index/bitmap/bitmap_index_result_test.cpp @@ -16,13 +16,12 @@ * limitations under the License. */ -#include "paimon/file_index/bitmap_index_result.h" - #include #include #include #include "gtest/gtest.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/status.h" #include "paimon/testing/utils/testharness.h" diff --git a/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index.cpp b/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index.cpp index b91a9da06..c99bda7eb 100644 --- a/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index.cpp +++ b/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index.cpp @@ -42,7 +42,7 @@ #include "paimon/data/decimal.h" #include "paimon/data/timestamp.h" #include "paimon/defs.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/fs/file_system.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/io/data_input_stream.h" diff --git a/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index_test.cpp b/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index_test.cpp index 1cfd292dc..0a803a5c5 100644 --- a/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index_test.cpp +++ b/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index_test.cpp @@ -30,7 +30,7 @@ #include "paimon/data/decimal.h" #include "paimon/data/timestamp.h" #include "paimon/defs.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/memory/memory_pool.h" #include "paimon/testing/utils/testharness.h" diff --git a/src/paimon/common/file_index/empty/empty_file_index_reader.h b/src/paimon/common/file_index/empty/empty_file_index_reader.h index 8231fd989..39dc835b2 100644 --- a/src/paimon/common/file_index/empty/empty_file_index_reader.h +++ b/src/paimon/common/file_index/empty/empty_file_index_reader.h @@ -23,10 +23,8 @@ #include #include -#include "paimon/file_index/bitmap_index_result.h" #include "paimon/file_index/file_index_reader.h" #include "paimon/file_index/file_index_result.h" -#include "paimon/file_index/scored_file_index_result.h" #include "paimon/result.h" #include "paimon/status.h" #include "paimon/utils/roaring_bitmap32.h" diff --git a/src/paimon/common/file_index/empty/empty_file_index_reader_test.cpp b/src/paimon/common/file_index/empty/empty_file_index_reader_test.cpp index 9e6853f70..a9d7d7081 100644 --- a/src/paimon/common/file_index/empty/empty_file_index_reader_test.cpp +++ b/src/paimon/common/file_index/empty/empty_file_index_reader_test.cpp @@ -25,7 +25,7 @@ #include #include "gtest/gtest.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/predicate/full_text_match.h" #include "paimon/predicate/full_text_search.h" #include "paimon/predicate/literal.h" diff --git a/src/paimon/common/file_index/file_index_format_test.cpp b/src/paimon/common/file_index/file_index_format_test.cpp index c8a739a8b..611d7ecb8 100644 --- a/src/paimon/common/file_index/file_index_format_test.cpp +++ b/src/paimon/common/file_index/file_index_format_test.cpp @@ -38,7 +38,6 @@ #include "paimon/data/timestamp.h" #include "paimon/defs.h" #include "paimon/file_index/file_index_result.h" -#include "paimon/file_index/scored_file_index_result.h" #include "paimon/fs/local/local_file_system.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/memory/bytes.h" diff --git a/src/paimon/common/file_index/file_index_reader.cpp b/src/paimon/common/file_index/file_index_reader.cpp index 25d3a83da..de85b2f8a 100644 --- a/src/paimon/common/file_index/file_index_reader.cpp +++ b/src/paimon/common/file_index/file_index_reader.cpp @@ -20,7 +20,7 @@ #include -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/common/index/index_reader_utils.h" #include "paimon/predicate/literal.h" #include "paimon/predicate/predicate_utils.h" #include "paimon/status.h" @@ -31,29 +31,7 @@ Result> FileIndexReader::Evaluate( PAIMON_ASSIGN_OR_RAISE( std::shared_ptr result, PredicateUtils::VisitPredicate>(predicate, this)); - if (auto bitmap = std::dynamic_pointer_cast(result)) { - if (!candidates) { - return result; - } - return std::make_shared( - [bitmap, rows = *candidates]() -> Result { - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* matches, bitmap->GetBitmap()); - RoaringBitmap32 filtered(rows); - filtered &= *matches; - return filtered; - }, - bitmap->IsExact()); - } else if (std::dynamic_pointer_cast(result)) { - if (candidates) { - return std::make_shared( - [rows = *candidates]() -> Result { return rows; }, - /*is_exact=*/false); - } - return result; - } else if (std::dynamic_pointer_cast(result)) { - return result; - } - return Status::Invalid("Scalar evaluation requires BitmapIndexResult, Skip or Remain"); + return IndexReaderUtils::RestrictScalarResult(result, candidates); } Result> FileIndexReader::VisitIsNotNull() { diff --git a/src/paimon/common/file_index/file_index_result.cpp b/src/paimon/common/file_index/file_index_result.cpp deleted file mode 100644 index eaf6ce831..000000000 --- a/src/paimon/common/file_index/file_index_result.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "paimon/file_index/file_index_result.h" - -namespace paimon { -std::shared_ptr FileIndexResult::Remain() { - static std::shared_ptr remain = std::make_shared(); - return remain; -} - -std::shared_ptr FileIndexResult::Skip() { - static std::shared_ptr skip = std::make_shared(); - return skip; -} - -Result Remain::IsRemain() const { - return true; -} - -Result> Remain::And( - const std::shared_ptr& other) { - if (!other->IsExact()) { - return other; - } - return other->And(shared_from_this()); -} - -Result> Remain::Or(const std::shared_ptr& other) { - return shared_from_this(); -} - -std::string Remain::ToString() const { - return "REMAIN"; -} - -Result Skip::IsRemain() const { - return false; -} - -Result> Skip::And(const std::shared_ptr& other) { - return shared_from_this(); -} - -Result> Skip::Or(const std::shared_ptr& other) { - return other; -} - -std::string Skip::ToString() const { - return "SKIP"; -} - -} // namespace paimon diff --git a/src/paimon/common/file_index/file_index_result_test.cpp b/src/paimon/common/file_index/file_index_result_test.cpp index 938a3e23c..fb46ce127 100644 --- a/src/paimon/common/file_index/file_index_result_test.cpp +++ b/src/paimon/common/file_index/file_index_result_test.cpp @@ -22,8 +22,6 @@ #include #include "gtest/gtest.h" -#include "paimon/file_index/bitmap_index_result.h" -#include "paimon/file_index/scored_file_index_result.h" #include "paimon/testing/utils/testharness.h" namespace paimon::test { diff --git a/src/paimon/common/file_index/rangebitmap/range_bitmap_file_index.cpp b/src/paimon/common/file_index/rangebitmap/range_bitmap_file_index.cpp index 6b76da34c..e20d1ad30 100644 --- a/src/paimon/common/file_index/rangebitmap/range_bitmap_file_index.cpp +++ b/src/paimon/common/file_index/rangebitmap/range_bitmap_file_index.cpp @@ -31,7 +31,7 @@ #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/checked_cast.h" #include "paimon/common/utils/field_type_utils.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/predicate/literal.h" #include "paimon/result.h" #include "paimon/status.h" diff --git a/src/paimon/common/file_index/rangebitmap/range_bitmap_file_index_test.cpp b/src/paimon/common/file_index/rangebitmap/range_bitmap_file_index_test.cpp index e333347a9..7454dd559 100644 --- a/src/paimon/common/file_index/rangebitmap/range_bitmap_file_index_test.cpp +++ b/src/paimon/common/file_index/rangebitmap/range_bitmap_file_index_test.cpp @@ -32,8 +32,8 @@ #include "paimon/common/utils/math.h" #include "paimon/data/decimal.h" #include "paimon/data/timestamp.h" -#include "paimon/file_index/bitmap_index_result.h" #include "paimon/file_index/file_index_format.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/file_index/file_indexer_factory.h" #include "paimon/fs/file_system.h" #include "paimon/fs/local/local_file_system.h" diff --git a/src/paimon/common/file_index/rangebitmap/range_bitmap_io_test.cpp b/src/paimon/common/file_index/rangebitmap/range_bitmap_io_test.cpp index 9ae5fbf44..104b41c33 100644 --- a/src/paimon/common/file_index/rangebitmap/range_bitmap_io_test.cpp +++ b/src/paimon/common/file_index/rangebitmap/range_bitmap_io_test.cpp @@ -28,7 +28,7 @@ #include "paimon/common/file_index/rangebitmap/range_bitmap_file_index.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/scope_guard.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/fs/file_system.h" #include "paimon/fs/local/local_file_system.h" #include "paimon/memory/memory_pool.h" diff --git a/src/paimon/common/file_index/scored_file_index_result.cpp b/src/paimon/common/file_index/scored_file_index_result.cpp deleted file mode 100644 index 6df9b6382..000000000 --- a/src/paimon/common/file_index/scored_file_index_result.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "paimon/file_index/scored_file_index_result.h" - -#include - -#include "fmt/format.h" -#include "fmt/ranges.h" -#include "paimon/status.h" - -namespace paimon { - -Result> ScoredFileIndexResult::Create( - RoaringBitmap32&& row_positions, std::vector&& scores, bool is_exact) { - if (static_cast(row_positions.Cardinality()) != scores.size()) { - return Status::Invalid(fmt::format("Vector search returned {} row positions but {} scores", - row_positions.Cardinality(), scores.size())); - } - return std::shared_ptr( - new ScoredFileIndexResult(std::move(row_positions), std::move(scores), is_exact)); -} - -ScoredFileIndexResult::ScoredFileIndexResult(RoaringBitmap32&& row_positions, - std::vector&& scores, bool is_exact) - : FileIndexResult(is_exact), - row_positions_(std::move(row_positions)), - scores_(std::move(scores)) {} - -Result> ScoredFileIndexResult::And( - const std::shared_ptr& other) { - if (std::dynamic_pointer_cast(other)) { - if (!IsExact()) { - return shared_from_this(); - } - PAIMON_ASSIGN_OR_RAISE(std::shared_ptr result, - Create(RoaringBitmap32(row_positions_), std::vector(scores_), - /*is_exact=*/false)); - return result; - } else if (std::dynamic_pointer_cast(other)) { - return FileIndexResult::Skip(); - } else { - return Status::Invalid("Cannot AND ScoredFileIndexResult with unsupported result type"); - } -} - -Result> ScoredFileIndexResult::Or( - const std::shared_ptr& other) { - if (std::dynamic_pointer_cast(other)) { - return FileIndexResult::Remain(); - } else if (std::dynamic_pointer_cast(other)) { - return shared_from_this(); - } else { - return Status::Invalid("Cannot OR ScoredFileIndexResult with unsupported result type"); - } -} - -Result ScoredFileIndexResult::IsRemain() const { - return !IsEmpty(); -} - -std::string ScoredFileIndexResult::ToString() const { - std::vector formatted_scores; - formatted_scores.reserve(scores_.size()); - for (float score : scores_) { - formatted_scores.push_back(fmt::format("{:.2f}", score)); - } - return fmt::format("row positions: {}, scores: {{{}}}", row_positions_.ToString(), - fmt::join(formatted_scores, ",")); -} - -} // namespace paimon diff --git a/src/paimon/common/file_index/scored_file_index_result_test.cpp b/src/paimon/common/file_index/scored_file_index_result_test.cpp index c18de24d2..c11288f38 100644 --- a/src/paimon/common/file_index/scored_file_index_result_test.cpp +++ b/src/paimon/common/file_index/scored_file_index_result_test.cpp @@ -16,14 +16,12 @@ * limitations under the License. */ -#include "paimon/file_index/scored_file_index_result.h" - #include #include #include #include "gtest/gtest.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/testing/utils/testharness.h" namespace paimon::test { diff --git a/src/paimon/common/global_index/rangebitmap/range_bitmap_global_index_test.cpp b/src/paimon/common/global_index/rangebitmap/range_bitmap_global_index_test.cpp index d5287d3de..929d02a27 100644 --- a/src/paimon/common/global_index/rangebitmap/range_bitmap_global_index_test.cpp +++ b/src/paimon/common/global_index/rangebitmap/range_bitmap_global_index_test.cpp @@ -36,7 +36,7 @@ #include "paimon/common/utils/scope_guard.h" #include "paimon/common/utils/string_utils.h" #include "paimon/core/global_index/global_index_file_manager.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/fs/local/local_file_system.h" #include "paimon/global_index/bitmap_global_index_result.h" #include "paimon/global_index/global_index_result.h" diff --git a/src/paimon/common/global_index/wrap/file_index_reader_wrapper.h b/src/paimon/common/global_index/wrap/file_index_reader_wrapper.h index 7cdba935b..90dda308d 100644 --- a/src/paimon/common/global_index/wrap/file_index_reader_wrapper.h +++ b/src/paimon/common/global_index/wrap/file_index_reader_wrapper.h @@ -24,8 +24,8 @@ #include #include -#include "paimon/file_index/bitmap_index_result.h" #include "paimon/file_index/file_index_reader.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/global_index/bitmap_global_index_result.h" #include "paimon/global_index/global_index_reader.h" #include "paimon/utils/roaring_bitmap64.h" diff --git a/src/paimon/common/global_index/wrap/file_index_reader_wrapper_test.cpp b/src/paimon/common/global_index/wrap/file_index_reader_wrapper_test.cpp index f13e54f48..0641ed47b 100644 --- a/src/paimon/common/global_index/wrap/file_index_reader_wrapper_test.cpp +++ b/src/paimon/common/global_index/wrap/file_index_reader_wrapper_test.cpp @@ -22,7 +22,7 @@ #include #include "gtest/gtest.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/global_index/bitmap_global_index_result.h" #include "paimon/global_index/global_index_result.h" #include "paimon/testing/utils/testharness.h" diff --git a/src/paimon/common/index/bitmap_result.cpp b/src/paimon/common/index/bitmap_result.cpp new file mode 100644 index 000000000..b7026461e --- /dev/null +++ b/src/paimon/common/index/bitmap_result.cpp @@ -0,0 +1,128 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "paimon/index/bitmap_result.h" + +#include + +#include "paimon/common/utils/checked_cast.h" +#include "paimon/status.h" +#include "paimon/utils/roaring_bitmap32.h" +#include "paimon/utils/roaring_bitmap64.h" + +namespace paimon { + +template +Result>> BitmapResult::Create(Bitmap rows, + bool is_exact) { + for (auto iter = rows.Begin(); iter != rows.End(); ++iter) { + if (*iter < 0) { + return Status::Invalid("Index result returned a negative row position"); + } + } + return std::shared_ptr>( + new BitmapResult(std::move(rows), is_exact)); +} + +template +Result BitmapResult::IsRemain() const { + PAIMON_ASSIGN_OR_RAISE(const Bitmap* rows, GetBitmap()); + return !rows->IsEmpty(); +} + +template +BitmapResult::BitmapResult(Bitmap rows, bool is_exact) + : IndexResult(is_exact), initialized_(true), bitmap_(std::move(rows)) {} + +template +BitmapResult::BitmapResult(BitmapSupplier bitmap_supplier, bool is_exact) + : IndexResult(is_exact), bitmap_supplier_(std::move(bitmap_supplier)) {} + +template +Result BitmapResult::GetBitmap() const { + if (!initialized_) { + PAIMON_ASSIGN_OR_RAISE(bitmap_, bitmap_supplier_()); + initialized_ = true; + } + return &bitmap_; +} + +template +Result>> BitmapResult::And( + const std::shared_ptr>& other) { + if (auto typed_other = std::dynamic_pointer_cast>(other)) { + return std::make_shared>( + [result = std::dynamic_pointer_cast>(this->shared_from_this()), + typed_other]() -> Result { + PAIMON_ASSIGN_OR_RAISE(const Bitmap* bitmap, result->GetBitmap()); + PAIMON_ASSIGN_OR_RAISE(const Bitmap* other_bitmap, typed_other->GetBitmap()); + return Bitmap::And(*bitmap, *other_bitmap); + }, + this->IsExact() && other->IsExact()); + } else if (std::dynamic_pointer_cast>(other)) { + if (!this->IsExact()) { + return this->shared_from_this(); + } + return std::make_shared>( + [result = checked_pointer_cast>( + this->shared_from_this())]() -> Result { + PAIMON_ASSIGN_OR_RAISE(const Bitmap* bitmap, result->GetBitmap()); + return *bitmap; + }, + /*is_exact=*/false); + } else if (std::dynamic_pointer_cast>(other)) { + return IndexResult::Skip(); + } else { + return Status::Invalid("Cannot AND BitmapResult with unsupported result type"); + } +} + +template +Result>> BitmapResult::Or( + const std::shared_ptr>& other) { + if (auto typed_other = std::dynamic_pointer_cast>(other)) { + return std::make_shared>( + [result = std::dynamic_pointer_cast>(this->shared_from_this()), + typed_other]() -> Result { + PAIMON_ASSIGN_OR_RAISE(const Bitmap* bitmap, result->GetBitmap()); + PAIMON_ASSIGN_OR_RAISE(const Bitmap* other_bitmap, typed_other->GetBitmap()); + return Bitmap::Or(*bitmap, *other_bitmap); + }, + this->IsExact() && other->IsExact()); + } else if (std::dynamic_pointer_cast>(other)) { + return IndexResult::Remain(); + } else if (std::dynamic_pointer_cast>(other)) { + return this->shared_from_this(); + } else { + return Status::Invalid("Cannot OR BitmapResult with unsupported result type"); + } +} + +template +std::string BitmapResult::ToString() const { + auto bitmap = GetBitmap(); + if (!bitmap.ok()) { + return bitmap.status().ToString(); + } + return bitmap.value()->ToString(); +} + +template class BitmapResult; +template class BitmapResult; + +} // namespace paimon diff --git a/src/paimon/common/index/index_reader_utils.h b/src/paimon/common/index/index_reader_utils.h index e46428438..1ff752095 100644 --- a/src/paimon/common/index/index_reader_utils.h +++ b/src/paimon/common/index/index_reader_utils.h @@ -22,13 +22,11 @@ #include #include #include -#include #include #include -#include "paimon/file_index/bitmap_index_result.h" #include "paimon/file_index/file_index_reader.h" -#include "paimon/file_index/scored_file_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/predicate/full_text_match.h" #include "paimon/predicate/function.h" #include "paimon/predicate/leaf_predicate.h" @@ -43,17 +41,12 @@ class IndexReaderUtils { IndexReaderUtils() = delete; ~IndexReaderUtils() = delete; - template + template struct FullTextResult { Bitmap rows; - std::shared_ptr scores; + std::shared_ptr> scores; }; - template - using FullTextScoredResult = - std::conditional_t, ScoredFileIndexResult, - ScoredRealtimeIndexResult>; - template static Result> GetSearchReader( const std::vector>& readers, @@ -98,39 +91,87 @@ class IndexReaderUtils { return estimate; } - static Result> VisitScalar( - const std::shared_ptr& reader, - const std::shared_ptr& predicate) { - PAIMON_ASSIGN_OR_RAISE( - std::shared_ptr result, - PredicateUtils::VisitPredicate>(predicate, reader)); + /// Extract scalar row selection at the reader boundary. Remain is unrestricted; + /// Skip is empty. Neither sentinel needs to own a bitmap. + template + static Result> GetScalarRows( + const std::shared_ptr>& result) { + if (!result) { + return Status::Invalid("Scalar index returned a null result"); + } + if (auto bitmap = std::dynamic_pointer_cast>(result)) { + PAIMON_ASSIGN_OR_RAISE(const Bitmap* rows, bitmap->GetBitmap()); + return std::optional(*rows); + } + if (std::dynamic_pointer_cast>(result)) { + return std::optional(Bitmap()); + } + if (std::dynamic_pointer_cast>(result)) { + return std::optional(); + } + return Status::Invalid("Scalar evaluation requires a bitmap, Skip or Remain"); + } + + /// Restrict a scalar result without changing the predicate's exactness. + template + static Result>> RestrictScalarResult( + const std::shared_ptr>& result, const Bitmap* candidates) { if (!result) { return Status::Invalid("Scalar index returned a null result"); } - if (auto bitmap = std::dynamic_pointer_cast(result)) { - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* rows, bitmap->GetBitmap()); - return std::optional(*rows); + if (auto bitmap = std::dynamic_pointer_cast>(result)) { + if (!candidates) { + return result; + } + return std::make_shared>( + [bitmap, rows = *candidates]() -> Result { + PAIMON_ASSIGN_OR_RAISE(const Bitmap* matches, bitmap->GetBitmap()); + return Bitmap::And(rows, *matches); + }, + bitmap->IsExact()); } - if (std::dynamic_pointer_cast(result)) { - return std::optional(RoaringBitmap32()); + if (std::dynamic_pointer_cast>(result)) { + if (candidates) { + return std::make_shared>( + [rows = *candidates]() -> Result { return rows; }, + /*is_exact=*/false); + } + return result; } - if (std::dynamic_pointer_cast(result)) { - return std::optional(); + if (std::dynamic_pointer_cast>(result)) { + return result; } - return Status::Invalid("Invalid scalar index result for predicate ", predicate->ToString()); + return Status::Invalid("Scalar evaluation requires a bitmap, Skip or Remain"); } - static Result> VisitScalar( - const std::shared_ptr& reader, - const std::shared_ptr& predicate) { - return PredicateUtils::VisitPredicate>(predicate, reader); + /// Each index evaluates the same input scope: inexact results cannot discard matches. + template + static Result>> EvaluateScalar( + const std::vector>& readers, + const std::shared_ptr& predicate, const Bitmap* candidates) { + if (candidates && candidates->IsEmpty()) { + return IndexResult::Skip(); + } + // TODO(xinyu.lxy): Redefine IsExact semantics and allow ANDing results from multiple + // indexes on the same field when none is exact. + for (const auto& reader : readers) { + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr> result, + reader->Evaluate(predicate, candidates)); + if (!result) { + return Status::Invalid("Scalar index returned a null result"); + } + if (result->IsExact()) { + return result; + } + } + return IndexResult::Remain(); } template - static Result>> VisitFullTextMatch( + static Result> VisitFullTextMatch( const std::shared_ptr& reader, const std::shared_ptr& match, const Bitmap& candidates, bool needs_scores) { - using ScoredResult = FullTextScoredResult; + using ScoredResult = ScoredIndexResult; auto filtered = std::make_shared(*match); RoaringBitmap64 eligible(candidates); if (filtered->include_row_ids) { @@ -138,28 +179,26 @@ class IndexReaderUtils { } else { filtered->include_row_ids = std::move(eligible); } - PAIMON_ASSIGN_OR_RAISE(auto result, reader->VisitFullTextMatch(filtered, needs_scores)); + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr> result, + reader->VisitFullTextMatch(filtered, needs_scores)); if (!result) { return Status::Invalid("Full-text match returned a null result"); } + std::shared_ptr scored; if (needs_scores) { - auto scored = std::dynamic_pointer_cast(result); + scored = std::dynamic_pointer_cast(result); if (!scored) { return Status::Invalid("Full-text index did not return requested scores"); } - return FullTextResult{scored->GetRowPositions(), - std::move(scored)}; } - if constexpr (std::is_same_v) { - auto bitmap = std::dynamic_pointer_cast(result); - if (!bitmap) { - return Status::Invalid("Full-text index did not return a bitmap"); - } - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* rows, bitmap->GetBitmap()); - return FullTextResult{*rows, nullptr}; - } else { - return FullTextResult{result->GetRowPositions(), nullptr}; + if (auto scored_result = std::dynamic_pointer_cast(result)) { + return FullTextResult{scored_result->GetRowPositions(), std::move(scored)}; + } + PAIMON_ASSIGN_OR_RAISE(std::optional rows, GetScalarRows(result)); + if (!rows) { + return Status::Invalid("Full-text index did not return row positions"); } + return FullTextResult{std::move(*rows), nullptr}; } }; diff --git a/src/paimon/common/index/index_result.cpp b/src/paimon/common/index/index_result.cpp new file mode 100644 index 000000000..47b729dcb --- /dev/null +++ b/src/paimon/common/index/index_result.cpp @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "paimon/index/index_result.h" + +#include "paimon/utils/roaring_bitmap32.h" +#include "paimon/utils/roaring_bitmap64.h" + +namespace paimon { + +template +std::shared_ptr> IndexResult::Remain() { + static std::shared_ptr> remain = + std::make_shared>(); + return remain; +} + +template +std::shared_ptr> IndexResult::Skip() { + static std::shared_ptr> skip = std::make_shared>(); + return skip; +} + +template +Result RemainIndexResult::IsRemain() const { + return true; +} + +template +Result>> RemainIndexResult::And( + const std::shared_ptr>& other) { + if (!other->IsExact()) { + return other; + } + return other->And(this->shared_from_this()); +} + +template +Result>> RemainIndexResult::Or( + const std::shared_ptr>& other) { + return this->shared_from_this(); +} + +template +std::string RemainIndexResult::ToString() const { + return "REMAIN"; +} + +template +Result SkipIndexResult::IsRemain() const { + return false; +} + +template +Result>> SkipIndexResult::And( + const std::shared_ptr>& other) { + return this->shared_from_this(); +} + +template +Result>> SkipIndexResult::Or( + const std::shared_ptr>& other) { + return other; +} + +template +std::string SkipIndexResult::ToString() const { + return "SKIP"; +} + +template class IndexResult; +template class IndexResult; +template class RemainIndexResult; +template class RemainIndexResult; +template class SkipIndexResult; +template class SkipIndexResult; + +} // namespace paimon diff --git a/src/paimon/common/index/scored_index_result.cpp b/src/paimon/common/index/scored_index_result.cpp new file mode 100644 index 000000000..88c995892 --- /dev/null +++ b/src/paimon/common/index/scored_index_result.cpp @@ -0,0 +1,99 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "paimon/index/scored_index_result.h" + +#include + +#include "fmt/format.h" +#include "fmt/ranges.h" +#include "paimon/macros.h" +#include "paimon/status.h" +#include "paimon/utils/roaring_bitmap32.h" +#include "paimon/utils/roaring_bitmap64.h" + +namespace paimon { + +template +Result>> ScoredIndexResult::Create( + Bitmap row_positions, std::vector scores, bool is_exact) { + for (auto iter = row_positions.Begin(); iter != row_positions.End(); ++iter) { + if (*iter < 0) { + return Status::Invalid("Index result returned a negative row position"); + } + } + if (static_cast(row_positions.Cardinality()) != scores.size()) { + return Status::Invalid(fmt::format("Vector search returned {} row positions but {} scores", + row_positions.Cardinality(), scores.size())); + } + return std::shared_ptr>( + new ScoredIndexResult(std::move(row_positions), std::move(scores), is_exact)); +} + +template +ScoredIndexResult::ScoredIndexResult(Bitmap row_positions, std::vector scores, + bool is_exact) + : IndexResult(is_exact), + row_positions_(std::move(row_positions)), + scores_(std::move(scores)) {} + +template +Result>> ScoredIndexResult::And( + const std::shared_ptr>& other) { + if (std::dynamic_pointer_cast>(other)) { + if (!this->IsExact()) { + return this->shared_from_this(); + } + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr> result, + Create(Bitmap(row_positions_), std::vector(scores_), + /*is_exact=*/false)); + return result; + } else if (std::dynamic_pointer_cast>(other)) { + return IndexResult::Skip(); + } else { + return Status::Invalid("Cannot AND ScoredIndexResult with unsupported result type"); + } +} + +template +Result>> ScoredIndexResult::Or( + const std::shared_ptr>& other) { + if (std::dynamic_pointer_cast>(other)) { + return IndexResult::Remain(); + } else if (std::dynamic_pointer_cast>(other)) { + return this->shared_from_this(); + } else { + return Status::Invalid("Cannot OR ScoredIndexResult with unsupported result type"); + } +} + +template +std::string ScoredIndexResult::ToString() const { + std::vector formatted_scores; + formatted_scores.reserve(scores_.size()); + for (float score : scores_) { + formatted_scores.push_back(fmt::format("{:.2f}", score)); + } + return fmt::format("row positions: {}, scores: {{{}}}", row_positions_.ToString(), + fmt::join(formatted_scores, ",")); +} + +template class ScoredIndexResult; +template class ScoredIndexResult; + +} // namespace paimon diff --git a/src/paimon/core/io/file_index_evaluator.cpp b/src/paimon/core/io/file_index_evaluator.cpp index 8fa360d18..7f5c449c4 100644 --- a/src/paimon/core/io/file_index_evaluator.cpp +++ b/src/paimon/core/io/file_index_evaluator.cpp @@ -37,10 +37,9 @@ #include "paimon/common/utils/string_utils.h" #include "paimon/core/io/data_file_meta.h" #include "paimon/core/io/data_file_path_factory.h" -#include "paimon/file_index/bitmap_index_result.h" #include "paimon/file_index/file_index_format.h" #include "paimon/file_index/file_index_reader.h" -#include "paimon/file_index/scored_file_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/io/byte_array_input_stream.h" #include "paimon/predicate/compound_predicate.h" #include "paimon/predicate/full_text_match.h" @@ -209,17 +208,7 @@ Result> FileIndexEvaluator::EvaluateLeaf( } PAIMON_ASSIGN_OR_RAISE(std::vector> readers, GetReaders(predicate->FieldName())); - for (const auto& reader : readers) { - PAIMON_ASSIGN_OR_RAISE(std::shared_ptr child, - reader->Evaluate(predicate, candidates)); - // Inexact indexes may miss matches. Try another index over the original scope. - // Remain is also inexact and contributes no row selection for this predicate. - if (!child->IsExact()) { - continue; - } - return child; - } - return FileIndexResult::Remain(); + return IndexReaderUtils::EvaluateScalar(readers, predicate, candidates); } Result> FileIndexEvaluator::EstimateSelectivity( diff --git a/src/paimon/core/io/file_index_evaluator.h b/src/paimon/core/io/file_index_evaluator.h index 82566972c..df377b3f8 100644 --- a/src/paimon/core/io/file_index_evaluator.h +++ b/src/paimon/core/io/file_index_evaluator.h @@ -17,6 +17,7 @@ */ #pragma once + #include #include #include @@ -44,7 +45,6 @@ class FileIndexReader; class MemoryPool; class Predicate; class RoaringBitmap32; -class ScoredFileIndexResult; struct DataFileMeta; struct FullTextSearch; struct VectorSearch; diff --git a/src/paimon/core/io/file_index_evaluator_test.cpp b/src/paimon/core/io/file_index_evaluator_test.cpp index e06ed87cb..d30199e28 100644 --- a/src/paimon/core/io/file_index_evaluator_test.cpp +++ b/src/paimon/core/io/file_index_evaluator_test.cpp @@ -45,10 +45,9 @@ #include "paimon/data/timestamp.h" #include "paimon/defs.h" #include "paimon/factories/factory_creator.h" -#include "paimon/file_index/bitmap_index_result.h" #include "paimon/file_index/file_index_format.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/file_index/file_indexer_factory.h" -#include "paimon/file_index/scored_file_index_result.h" #include "paimon/fs/local/local_file_system.h" #include "paimon/memory/bytes.h" #include "paimon/memory/memory_pool.h" diff --git a/src/paimon/core/operation/abstract_split_read.cpp b/src/paimon/core/operation/abstract_split_read.cpp index f14e2cede..c0a1867e4 100644 --- a/src/paimon/core/operation/abstract_split_read.cpp +++ b/src/paimon/core/operation/abstract_split_read.cpp @@ -67,7 +67,6 @@ #include "paimon/core/table/source/data_split_impl.h" #include "paimon/core/utils/field_mapping.h" #include "paimon/core/utils/nested_projection_utils.h" -#include "paimon/file_index/bitmap_index_result.h" #include "paimon/file_index/file_index_result.h" #include "paimon/format/file_format.h" #include "paimon/format/file_format_factory.h" diff --git a/src/paimon/core/operation/data_evolution_split_read.cpp b/src/paimon/core/operation/data_evolution_split_read.cpp index d13cb9199..b6b831c8b 100644 --- a/src/paimon/core/operation/data_evolution_split_read.cpp +++ b/src/paimon/core/operation/data_evolution_split_read.cpp @@ -60,7 +60,6 @@ #include "paimon/core/utils/blob_view_lookup.h" #include "paimon/core/utils/data_evolution_utils.h" #include "paimon/core/utils/field_mapping.h" -#include "paimon/file_index/bitmap_index_result.h" #include "paimon/file_index/file_index_result.h" #include "paimon/predicate/predicate_utils.h" diff --git a/src/paimon/core/operation/precise_file_index_read.cpp b/src/paimon/core/operation/precise_file_index_read.cpp index 2123a2e3f..2ca8c5218 100644 --- a/src/paimon/core/operation/precise_file_index_read.cpp +++ b/src/paimon/core/operation/precise_file_index_read.cpp @@ -48,7 +48,7 @@ #include "paimon/core/schema/schema_manager.h" #include "paimon/core/schema/table_schema.h" #include "paimon/core/utils/field_mapping.h" -#include "paimon/file_index/scored_file_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/format/reader_builder.h" #include "paimon/predicate/compound_predicate.h" #include "paimon/predicate/full_text_search.h" @@ -78,7 +78,7 @@ Status PreparePredicate( const std::map>& data_by_id, const std::vector& partition_keys, FileIndexEvaluator* indexes, std::map, std::shared_ptr>* mapped_leaves) { - return PreciseIndexEvaluator::Prepare( + return PreciseIndexEvaluator::Prepare( predicate, [&](const std::shared_ptr& leaf) -> Status { bool full_text = leaf->GetFunction().GetType() == Function::Type::FULL_TEXT_MATCH; if (!full_text && ObjectUtils::Contains(partition_keys, leaf->FieldName())) { diff --git a/src/paimon/core/operation/precise_file_index_read.h b/src/paimon/core/operation/precise_file_index_read.h index ba6e19720..3825087fc 100644 --- a/src/paimon/core/operation/precise_file_index_read.h +++ b/src/paimon/core/operation/precise_file_index_read.h @@ -28,6 +28,7 @@ #include "paimon/core/deletionvectors/deletion_vector.h" #include "paimon/core/operation/precise_index_evaluator.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/reader/file_batch_reader.h" #include "paimon/result.h" #include "paimon/status.h" @@ -43,7 +44,6 @@ class FileIndexEvaluator; class LeafPredicate; class Predicate; class RawFileSplitRead; -class ScoredFileIndexResult; struct DataFileMeta; struct FullTextSearch; struct VectorSearch; @@ -68,7 +68,7 @@ class PreciseFileIndexRead { const std::optional>& row_ranges) const; private: - using Evaluator = PreciseIndexEvaluator; + using Evaluator = PreciseIndexEvaluator; using Evaluation = Evaluator::Evaluation; PreciseFileIndexRead(const RawFileSplitRead& split_read, const BinaryRow& partition, diff --git a/src/paimon/core/operation/precise_file_index_read_test.cpp b/src/paimon/core/operation/precise_file_index_read_test.cpp index 3b69758e5..6effbf2ae 100644 --- a/src/paimon/core/operation/precise_file_index_read_test.cpp +++ b/src/paimon/core/operation/precise_file_index_read_test.cpp @@ -49,7 +49,7 @@ #include "paimon/core/utils/field_mapping.h" #include "paimon/data/timestamp.h" #include "paimon/factories/factory_creator.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/fs/local/local_file_system.h" #include "paimon/memory/bytes.h" #include "paimon/memory/memory_pool.h" @@ -259,7 +259,7 @@ class PreciseFileIndexReadTest : public ::testing::Test { }; TEST_F(PreciseFileIndexReadTest, FullTextMatchPushesDownCandidates) { - using MatchResult = IndexReaderUtils::FullTextResult; + using MatchResult = IndexReaderUtils::FullTextResult; auto reader = std::make_shared( "f0", SearchIndexType::FULL_TEXT, MockSearchFileIndex::ScoredRows{{2, 0.9f}, {0, 0.8f}, {1, 0.7f}}, statistics_); diff --git a/src/paimon/core/operation/precise_index_evaluator.h b/src/paimon/core/operation/precise_index_evaluator.h index 60b5f5c1a..4f2ff7b3f 100644 --- a/src/paimon/core/operation/precise_index_evaluator.h +++ b/src/paimon/core/operation/precise_index_evaluator.h @@ -25,7 +25,6 @@ #include #include #include -#include #include #include @@ -44,14 +43,14 @@ namespace paimon { /// Shared precise evaluation over file row positions or real-time offsets. /// Storage adapters supply readers and physical scans; this class owns tree and leaf semantics. -template +template class PreciseIndexEvaluator { public: struct Evaluation { Bitmap rows; // Sources retain physical row positions or real-time offsets until all filtering and // root TopK are complete. - std::map> scores; + std::map>> scores; }; using LeafEvaluator = std::function(const std::shared_ptr&, const Bitmap&)>; @@ -87,8 +86,8 @@ class PreciseIndexEvaluator { return prepare_leaf(leaf); } - /// Field mapping and physical scans remain with the storage adapter. Exact file - /// indexes avoid scalar scans; inexact file results recheck the original candidates. + /// Field mapping and physical scans remain with the storage adapter. Exact index + /// results avoid scalar scans; inexact results recheck the original candidates. /// @param predicate Original predicate in the query's logical schema, used for exact /// scalar filtering and binding scores to the original field name. /// @param index_predicate Predicate mapped to the source's physical schema for index @@ -114,7 +113,7 @@ class PreciseIndexEvaluator { std::shared_ptr reader, indexes->GetSearchReader(index_predicate->FieldName(), IndexReaderCapabilities::SearchType::FULL_TEXT_MATCH)); - using FullTextResult = IndexReaderUtils::FullTextResult; + using FullTextResult = IndexReaderUtils::FullTextResult; PAIMON_ASSIGN_OR_RAISE( FullTextResult indexed, IndexReaderUtils::VisitFullTextMatch(reader, full_text->GetFullTextMatch(), @@ -125,51 +124,23 @@ class PreciseIndexEvaluator { } return result; } - if constexpr (std::is_same_v) { - if (index_predicate) { - PAIMON_ASSIGN_OR_RAISE( - std::shared_ptr indexed, - indexes->EvaluateLeaf(index_predicate, /*needs_scores=*/false, &candidates)); - if (!indexed) { - return Status::Invalid("Scalar index returned a null result"); - } - if (indexed->IsExact()) { - if (auto bitmap = std::dynamic_pointer_cast(indexed)) { - PAIMON_ASSIGN_OR_RAISE(const RoaringBitmap32* rows, bitmap->GetBitmap()); - return Evaluation{*rows, {}}; - } - if (std::dynamic_pointer_cast(indexed)) { - return Evaluation{}; - } - return Status::Invalid("Invalid exact scalar index result"); - } - } - PAIMON_ASSIGN_OR_RAISE(result.rows, scan_scalar(predicate, candidates)); - return result; - } else { - if (index_predicate) { - PAIMON_ASSIGN_OR_RAISE(std::vector> readers, - indexes->GetReaders(index_predicate->FieldName())); - for (const auto& reader : readers) { - PAIMON_ASSIGN_OR_RAISE(std::optional indexed, - IndexReaderUtils::VisitScalar(reader, index_predicate)); - if (indexed) { - result.rows &= *indexed; - if (result.rows.IsEmpty()) { - break; - } - } + if (index_predicate) { + PAIMON_ASSIGN_OR_RAISE(std::vector> readers, + indexes->GetReaders(index_predicate->FieldName())); + PAIMON_ASSIGN_OR_RAISE( + std::shared_ptr> indexed, + IndexReaderUtils::EvaluateScalar(readers, index_predicate, &candidates)); + if (indexed->IsExact()) { + PAIMON_ASSIGN_OR_RAISE(std::optional rows, + IndexReaderUtils::GetScalarRows(indexed)); + if (!rows) { + return Status::Invalid("Exact scalar index result has no row positions"); } + return Evaluation{std::move(*rows), {}}; } - // TODO(xinyu.lxy): Whether to ScanScalar depends on whether the index returns exact - // results. - if (!result.rows.IsEmpty()) { - // Scalar indexes may contain false positives, even if they return a bitmap. - PAIMON_ASSIGN_OR_RAISE(Bitmap exact_rows, scan_scalar(predicate, result.rows)); - result.rows &= exact_rows; - } - return result; } + PAIMON_ASSIGN_OR_RAISE(result.rows, scan_scalar(predicate, candidates)); + return result; } Result Evaluate(const std::shared_ptr& predicate, @@ -310,7 +281,7 @@ class PreciseIndexEvaluator { if (!score_field) { return Status::Invalid("Root search field name is missing"); } - std::shared_ptr scored; + std::shared_ptr> scored; if (vector_search) { PAIMON_ASSIGN_OR_RAISE( std::shared_ptr reader, @@ -334,8 +305,8 @@ class PreciseIndexEvaluator { return Status::OK(); } - static Result> AlignScores(const std::shared_ptr& source, - const Bitmap& rows) { + static Result> AlignScores( + const std::shared_ptr>& source, const Bitmap& rows) { if (!source) { return Status::Invalid("Projected search source did not return scores"); } diff --git a/src/paimon/core/realtime/arrow_realtime_store.cpp b/src/paimon/core/realtime/arrow_realtime_store.cpp index 85d956621..1294569ec 100644 --- a/src/paimon/core/realtime/arrow_realtime_store.cpp +++ b/src/paimon/core/realtime/arrow_realtime_store.cpp @@ -31,6 +31,7 @@ #include "arrow/compute/api_aggregate.h" #include "paimon/common/data/columnar/columnar_array.h" #include "paimon/common/data/columnar/columnar_row.h" +#include "paimon/common/index/index_reader_utils.h" #include "paimon/common/metrics/metrics_impl.h" #include "paimon/common/predicate/predicate_filter.h" #include "paimon/common/reader/reader_utils.h" @@ -581,17 +582,19 @@ class ArrowRealtimeStore::AppendQueryBatchReader : public BatchReader { } if (enable_index_pruning_ && segment->GetIndex() && predicate_) { PAIMON_ASSIGN_OR_RAISE( - std::optional indexed, + std::shared_ptr indexed, RealtimeIndexEvaluator::Evaluate( segment->GetIndex(), predicate_, OffsetRange(std::max(segment_range.begin, offset_range_.begin), std::min(segment_range.end, offset_range_.end)), memory_pool_)); - if (indexed) { + PAIMON_ASSIGN_OR_RAISE(std::optional rows, + IndexReaderUtils::GetScalarRows(indexed)); + if (rows) { if (candidates_) { - *candidates_ &= *indexed; + *candidates_ &= *rows; } else { - candidates_ = std::move(indexed); + candidates_ = std::move(rows); } } } diff --git a/src/paimon/core/realtime/index/hash/hash_realtime_index.cpp b/src/paimon/core/realtime/index/hash/hash_realtime_index.cpp index a105a25ae..19cf4e9bf 100644 --- a/src/paimon/core/realtime/index/hash/hash_realtime_index.cpp +++ b/src/paimon/core/realtime/index/hash/hash_realtime_index.cpp @@ -37,6 +37,7 @@ #include "paimon/common/utils/field_type_utils.h" #include "paimon/core/realtime/realtime_utils.h" #include "paimon/defs.h" +#include "paimon/index/bitmap_result.h" #include "paimon/macros.h" #include "paimon/predicate/function.h" #include "paimon/predicate/leaf_predicate.h" @@ -76,16 +77,16 @@ std::optional HashRealtimeIndex::Reader::EstimateSelectivity( return std::min(1.0, count / static_cast(offset_range_.end - offset_range_.begin)); } -Result> HashRealtimeIndex::Reader::VisitEqual( +Result> HashRealtimeIndex::Reader::VisitEqual( const Literal& literal) { return VisitIn({literal}); } -Result> HashRealtimeIndex::Reader::VisitIn( +Result> HashRealtimeIndex::Reader::VisitIn( const std::vector& literals) { RoaringBitmap64 result; if (offset_range_.Empty()) { - return std::optional(std::move(result)); + return RealtimeIndexResult::Skip(); } for (const Literal& literal : literals) { if (literal.IsNull()) { @@ -112,7 +113,11 @@ Result> HashRealtimeIndex::Reader::VisitIn( result.Add(*begin); } } - return std::optional(std::move(result)); + if (result.IsEmpty()) { + return RealtimeIndexResult::Skip(); + } + // Treat equality and IN results as exact, assuming no hash collisions. + return BitmapResult::Create(std::move(result), /*is_exact=*/true); } HashRealtimeIndex::HashRealtimeIndex(std::shared_ptr schema, FieldType field_type) diff --git a/src/paimon/core/realtime/index/hash/hash_realtime_index.h b/src/paimon/core/realtime/index/hash/hash_realtime_index.h index 3b92d1563..d3c3cb64a 100644 --- a/src/paimon/core/realtime/index/hash/hash_realtime_index.h +++ b/src/paimon/core/realtime/index/hash/hash_realtime_index.h @@ -65,8 +65,8 @@ class HashRealtimeIndex final : public RealtimeIndex, std::optional EstimateSelectivity( const std::shared_ptr& predicate) const override; - Result> VisitEqual(const Literal& literal) override; - Result> VisitIn( + Result> VisitEqual(const Literal& literal) override; + Result> VisitIn( const std::vector& literals) override; private: diff --git a/src/paimon/core/realtime/index/realtime_index_evaluator.cpp b/src/paimon/core/realtime/index/realtime_index_evaluator.cpp index 8157fff32..cc28ce929 100644 --- a/src/paimon/core/realtime/index/realtime_index_evaluator.cpp +++ b/src/paimon/core/realtime/index/realtime_index_evaluator.cpp @@ -32,17 +32,17 @@ namespace paimon { -Result> RealtimeIndexEvaluator::Evaluate( +Result> RealtimeIndexEvaluator::Evaluate( const std::shared_ptr& indexes, const std::shared_ptr& predicate, const OffsetRange& offset_range, const std::shared_ptr& pool) { if (offset_range.begin < 0 || offset_range.begin > offset_range.end) { return Status::Invalid("real-time index query offset range is invalid"); } if (offset_range.Empty()) { - return std::optional(RoaringBitmap64()); + return RealtimeIndexResult::Skip(); } if (!indexes || !predicate) { - return std::optional(); + return RealtimeIndexResult::Remain(); } const Function::Type function = predicate->GetFunction().GetType(); if (function == Function::Type::AND || function == Function::Type::OR) { @@ -55,44 +55,41 @@ Result> RealtimeIndexEvaluator::Evaluate( } const std::shared_ptr leaf = std::dynamic_pointer_cast(predicate); if (!leaf) { - return std::optional(); + return Status::Invalid("invalid real-time index leaf predicate"); } return EvaluateLeaf(indexes, leaf, offset_range, pool); } -Result> RealtimeIndexEvaluator::EvaluateCompound( +Result> RealtimeIndexEvaluator::EvaluateCompound( const std::shared_ptr& indexes, const std::shared_ptr& compound, const OffsetRange& offset_range, const std::shared_ptr& pool) { const Function::Type function = compound->GetFunction().GetType(); - std::optional result; + std::shared_ptr result; for (const std::shared_ptr& child : compound->Children()) { - PAIMON_ASSIGN_OR_RAISE(std::optional candidates, + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr evaluated, Evaluate(indexes, child, offset_range, pool)); - if (!candidates) { - if (function == Function::Type::OR) { - return std::optional(); - } - continue; - } if (!result) { - result = std::move(candidates); + result = std::move(evaluated); } else if (function == Function::Type::AND) { - *result &= *candidates; + PAIMON_ASSIGN_OR_RAISE(result, result->And(evaluated)); } else { - *result |= *candidates; + PAIMON_ASSIGN_OR_RAISE(result, result->Or(evaluated)); } - if (function == Function::Type::AND && result->IsEmpty()) { + PAIMON_ASSIGN_OR_RAISE(bool remain, result->IsRemain()); + if ((function == Function::Type::AND && !remain) || + (function == Function::Type::OR && + std::dynamic_pointer_cast>(result))) { break; } } return result; } -Result> RealtimeIndexEvaluator::EvaluateLeaf( +Result> RealtimeIndexEvaluator::EvaluateLeaf( const std::shared_ptr& indexes, const std::shared_ptr& leaf, const OffsetRange& offset_range, const std::shared_ptr& pool) { - std::optional result; + std::shared_ptr result = RealtimeIndexResult::Remain(); for (const std::shared_ptr& index : indexes->FindIndexes(leaf->FieldName(), leaf->GetFieldType())) { PAIMON_ASSIGN_OR_RAISE(std::shared_ptr reader, @@ -101,17 +98,19 @@ Result> RealtimeIndexEvaluator::EvaluateLeaf( continue; } PAIMON_ASSIGN_OR_RAISE( - std::optional candidates, - PredicateUtils::VisitPredicate>(leaf, reader)); - if (!candidates) { - continue; + std::shared_ptr indexed, + PredicateUtils::VisitPredicate>(leaf, reader)); + if (!indexed) { + return Status::Invalid("Scalar index returned a null result"); } - if (!result) { - result = std::move(candidates); - } else { - *result &= *candidates; + // These readers guarantee no false negatives. One exact result fully resolves + // this leaf; otherwise their candidate supersets can be intersected for pruning. + if (indexed->IsExact()) { + return indexed; } - if (result->IsEmpty()) { + PAIMON_ASSIGN_OR_RAISE(result, result->And(indexed)); + PAIMON_ASSIGN_OR_RAISE(bool remain, result->IsRemain()); + if (!remain) { break; } } diff --git a/src/paimon/core/realtime/index/realtime_index_evaluator.h b/src/paimon/core/realtime/index/realtime_index_evaluator.h index 9c6485b27..925385321 100644 --- a/src/paimon/core/realtime/index/realtime_index_evaluator.h +++ b/src/paimon/core/realtime/index/realtime_index_evaluator.h @@ -20,8 +20,8 @@ #pragma once #include -#include +#include "paimon/realtime/index/realtime_index_result.h" #include "paimon/realtime/offset_range.h" #include "paimon/result.h" #include "paimon/utils/roaring_bitmap64.h" @@ -38,18 +38,18 @@ class RealtimeIndexEvaluator { public: RealtimeIndexEvaluator() = delete; - static Result> Evaluate( + static Result> Evaluate( const std::shared_ptr& indexes, const std::shared_ptr& predicate, const OffsetRange& offset_range, const std::shared_ptr& pool); private: - static Result> EvaluateCompound( + static Result> EvaluateCompound( const std::shared_ptr& indexes, const std::shared_ptr& compound, const OffsetRange& offset_range, const std::shared_ptr& pool); - static Result> EvaluateLeaf( + static Result> EvaluateLeaf( const std::shared_ptr& indexes, const std::shared_ptr& leaf, const OffsetRange& offset_range, const std::shared_ptr& pool); diff --git a/src/paimon/core/realtime/index/realtime_index_reader.cpp b/src/paimon/core/realtime/index/realtime_index_reader.cpp index 9ee217280..83aa972be 100644 --- a/src/paimon/core/realtime/index/realtime_index_reader.cpp +++ b/src/paimon/core/realtime/index/realtime_index_reader.cpp @@ -21,10 +21,19 @@ #include +#include "paimon/common/index/index_reader_utils.h" #include "paimon/macros.h" namespace paimon { +Result> RealtimeIndexReader::Evaluate( + const std::shared_ptr& predicate, const RoaringBitmap64* candidates) { + PAIMON_ASSIGN_OR_RAISE( + std::shared_ptr result, + PredicateUtils::VisitPredicate>(predicate, this)); + return IndexReaderUtils::RestrictScalarResult(result, candidates); +} + Result> RealtimeIndexReader::VisitVectorSearch( const std::shared_ptr&) { return Status::NotImplemented("Real-time index does not support vector search"); @@ -40,82 +49,80 @@ Result> RealtimeIndexReader::VisitFullTextM return Status::NotImplemented("Real-time index does not support full-text match"); } -Result> RealtimeIndexReader::VisitIsNotNull() { - return std::optional(); +Result> RealtimeIndexReader::VisitIsNotNull() { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitIsNull() { - return std::optional(); +Result> RealtimeIndexReader::VisitIsNull() { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitEqual(const Literal&) { - return std::optional(); +Result> RealtimeIndexReader::VisitEqual(const Literal&) { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitNotEqual(const Literal&) { - return std::optional(); +Result> RealtimeIndexReader::VisitNotEqual(const Literal&) { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitLessThan(const Literal&) { - return std::optional(); +Result> RealtimeIndexReader::VisitLessThan(const Literal&) { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitLessOrEqual(const Literal&) { - return std::optional(); +Result> RealtimeIndexReader::VisitLessOrEqual(const Literal&) { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitGreaterThan(const Literal&) { - return std::optional(); +Result> RealtimeIndexReader::VisitGreaterThan(const Literal&) { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitGreaterOrEqual(const Literal&) { - return std::optional(); +Result> RealtimeIndexReader::VisitGreaterOrEqual( + const Literal&) { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitIn( +Result> RealtimeIndexReader::VisitIn( const std::vector& literals) { - RoaringBitmap64 result; + std::shared_ptr result = RealtimeIndexResult::Skip(); for (const Literal& literal : literals) { - PAIMON_ASSIGN_OR_RAISE(std::optional candidates, VisitEqual(literal)); - if (!candidates) { - return std::optional(); + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr child, VisitEqual(literal)); + PAIMON_ASSIGN_OR_RAISE(result, result->Or(child)); + if (std::dynamic_pointer_cast>(result)) { + return result; } - result |= *candidates; } - return std::optional(std::move(result)); + return result; } -Result> RealtimeIndexReader::VisitNotIn( +Result> RealtimeIndexReader::VisitNotIn( const std::vector& literals) { - std::optional result; + std::shared_ptr result; for (const Literal& literal : literals) { - PAIMON_ASSIGN_OR_RAISE(std::optional candidates, VisitNotEqual(literal)); - if (!candidates) { - continue; - } + PAIMON_ASSIGN_OR_RAISE(std::shared_ptr child, VisitNotEqual(literal)); if (!result) { - result = std::move(candidates); + result = std::move(child); } else { - *result &= *candidates; + PAIMON_ASSIGN_OR_RAISE(result, result->And(child)); } } - return result; + return result ? result : RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitStartsWith(const Literal&) { - return std::optional(); +Result> RealtimeIndexReader::VisitStartsWith(const Literal&) { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitEndsWith(const Literal&) { - return std::optional(); +Result> RealtimeIndexReader::VisitEndsWith(const Literal&) { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitContains(const Literal&) { - return std::optional(); +Result> RealtimeIndexReader::VisitContains(const Literal&) { + return RealtimeIndexResult::Remain(); } -Result> RealtimeIndexReader::VisitLike(const Literal&) { - return std::optional(); +Result> RealtimeIndexReader::VisitLike(const Literal&) { + return RealtimeIndexResult::Remain(); } } // namespace paimon diff --git a/src/paimon/core/realtime/index/realtime_index_test.cpp b/src/paimon/core/realtime/index/realtime_index_test.cpp index 57b623074..6c8faadfd 100644 --- a/src/paimon/core/realtime/index/realtime_index_test.cpp +++ b/src/paimon/core/realtime/index/realtime_index_test.cpp @@ -33,6 +33,7 @@ #include "arrow/c/helpers.h" #include "arrow/ipc/json_simple.h" #include "fmt/format.h" +#include "paimon/common/index/index_reader_utils.h" #include "paimon/common/table/special_fields.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/common/utils/scope_guard.h" @@ -75,7 +76,10 @@ class RealtimeIndexTest : public testing::Test { Result> Evaluate(const std::shared_ptr& predicate, const OffsetRange& range) const { - return RealtimeIndexEvaluator::Evaluate(index_, predicate, range, GetDefaultPool()); + PAIMON_ASSIGN_OR_RAISE( + std::shared_ptr result, + RealtimeIndexEvaluator::Evaluate(index_, predicate, range, GetDefaultPool())); + return IndexReaderUtils::GetScalarRows(result); } Status Add(const std::string& json, const OffsetRange& range) const { @@ -244,28 +248,35 @@ TEST_F(RealtimeIndexTest, FieldReadersBindIndependentRangesAndShareAppendOnlyPos ASSERT_OK_AND_ASSIGN(std::shared_ptr second, key_index->CreateReader(OffsetRange(20, 21), GetDefaultPool())); ASSERT_OK(Add(R"([[25, 1, "d"]])", OffsetRange(25, 26))); - ASSERT_OK_AND_ASSIGN(std::optional candidates, + ASSERT_OK_AND_ASSIGN(std::shared_ptr indexed, first->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(std::optional candidates, + IndexReaderUtils::GetScalarRows(indexed)); ASSERT_TRUE(candidates.has_value()); ASSERT_EQ(RoaringBitmap64::From({10}), *candidates); - ASSERT_OK_AND_ASSIGN(candidates, second->VisitIn({Literal(int64_t{1}), Literal(int64_t{2})})); + ASSERT_OK_AND_ASSIGN(indexed, second->VisitIn({Literal(int64_t{1}), Literal(int64_t{2})})); + ASSERT_OK_AND_ASSIGN(candidates, IndexReaderUtils::GetScalarRows(indexed)); ASSERT_TRUE(candidates.has_value()); ASSERT_EQ(RoaringBitmap64::From({20}), *candidates); ASSERT_OK_AND_ASSIGN(std::shared_ptr later, key_index->CreateReader(OffsetRange(25, 26), GetDefaultPool())); - ASSERT_OK_AND_ASSIGN(candidates, later->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(indexed, later->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(candidates, IndexReaderUtils::GetScalarRows(indexed)); ASSERT_TRUE(candidates.has_value()); ASSERT_EQ(RoaringBitmap64::From({25}), *candidates); - ASSERT_OK_AND_ASSIGN(candidates, first->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(indexed, first->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(candidates, IndexReaderUtils::GetScalarRows(indexed)); ASSERT_TRUE(candidates.has_value()); ASSERT_EQ(RoaringBitmap64::From({10}), *candidates); - ASSERT_OK_AND_ASSIGN(candidates, first->VisitGreaterThan(Literal(int64_t{0}))); + ASSERT_OK_AND_ASSIGN(indexed, first->VisitGreaterThan(Literal(int64_t{0}))); + ASSERT_OK_AND_ASSIGN(candidates, IndexReaderUtils::GetScalarRows(indexed)); ASSERT_FALSE(candidates.has_value()); ASSERT_NOK(key_index->CreateReader(OffsetRange(-1, 20), GetDefaultPool())); ASSERT_NOK(key_index->CreateReader(OffsetRange(20, 10), GetDefaultPool())); ASSERT_OK_AND_ASSIGN(std::shared_ptr empty, key_index->CreateReader(OffsetRange(10, 10), GetDefaultPool())); - ASSERT_OK_AND_ASSIGN(candidates, empty->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(indexed, empty->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(candidates, IndexReaderUtils::GetScalarRows(indexed)); ASSERT_TRUE(candidates.has_value()); ASSERT_TRUE(candidates->IsEmpty()); @@ -274,7 +285,8 @@ TEST_F(RealtimeIndexTest, FieldReadersBindIndependentRangesAndShareAppendOnlyPos // Readers retain the index after its segment releases it. key_index.reset(); index_.reset(); - ASSERT_OK_AND_ASSIGN(candidates, second->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(indexed, second->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(candidates, IndexReaderUtils::GetScalarRows(indexed)); ASSERT_TRUE(candidates.has_value()); ASSERT_EQ(RoaringBitmap64::From({20}), *candidates); } @@ -326,8 +338,10 @@ TEST_F(RealtimeIndexTest, FactoryAcceptsOnlyOneIndexedFieldAndReaderNeedsNoField RealtimeIndexFactory::Get("hash", &c_schema, {}, GetDefaultPool())); ASSERT_OK_AND_ASSIGN(std::shared_ptr reader, index->CreateReader(OffsetRange(0, 10), GetDefaultPool())); - ASSERT_OK_AND_ASSIGN(std::optional candidates, + ASSERT_OK_AND_ASSIGN(std::shared_ptr indexed, reader->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(std::optional candidates, + IndexReaderUtils::GetScalarRows(indexed)); ASSERT_TRUE(candidates.has_value()); ASSERT_TRUE(candidates->IsEmpty()); ASSERT_NOK_WITH_MSG(reader->VisitEqual(Literal(FieldType::STRING, "1", 1)), @@ -344,7 +358,8 @@ TEST_F(RealtimeIndexTest, FactoryAcceptsOnlyOneIndexedFieldAndReaderNeedsNoField ScopeGuard batch_guard([&batch]() { ArrowArrayRelease(&batch); }); ASSERT_OK(index->AddBatch(&batch)); ASSERT_OK_AND_ASSIGN(reader, index->CreateReader(OffsetRange(11, 31), GetDefaultPool())); - ASSERT_OK_AND_ASSIGN(candidates, reader->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(indexed, reader->VisitEqual(Literal(int64_t{1}))); + ASSERT_OK_AND_ASSIGN(candidates, IndexReaderUtils::GetScalarRows(indexed)); ASSERT_TRUE(candidates.has_value()); ASSERT_EQ(RoaringBitmap64::From({30}), *candidates); } @@ -370,12 +385,15 @@ TEST_F(RealtimeIndexTest, IndexesTimeField) { ASSERT_OK_AND_ASSIGN(std::shared_ptr reader, index->CreateReader(OffsetRange(0, 41), GetDefaultPool())); - ASSERT_OK_AND_ASSIGN(std::optional candidates, + ASSERT_OK_AND_ASSIGN(std::shared_ptr indexed, reader->VisitEqual(Literal(FieldType::TIME, 45296123))); + ASSERT_OK_AND_ASSIGN(std::optional candidates, + IndexReaderUtils::GetScalarRows(indexed)); ASSERT_TRUE(candidates.has_value()); ASSERT_EQ(RoaringBitmap64::From({20, 40}), *candidates); - ASSERT_OK_AND_ASSIGN(candidates, reader->VisitIn({Literal(FieldType::TIME, 0), - Literal(FieldType::TIME, 86399999)})); + ASSERT_OK_AND_ASSIGN(indexed, reader->VisitIn({Literal(FieldType::TIME, 0), + Literal(FieldType::TIME, 86399999)})); + ASSERT_OK_AND_ASSIGN(candidates, IndexReaderUtils::GetScalarRows(indexed)); ASSERT_TRUE(candidates.has_value()); ASSERT_EQ(RoaringBitmap64::From({10, 30}), *candidates); ASSERT_NOK_WITH_MSG(reader->VisitEqual(Literal(int32_t{45296123})), diff --git a/src/paimon/core/realtime/precise_realtime_index_read.cpp b/src/paimon/core/realtime/precise_realtime_index_read.cpp index c131b7d84..ee298ada0 100644 --- a/src/paimon/core/realtime/precise_realtime_index_read.cpp +++ b/src/paimon/core/realtime/precise_realtime_index_read.cpp @@ -53,7 +53,7 @@ namespace paimon { namespace { -using Evaluator = PreciseIndexEvaluator; +using Evaluator = PreciseIndexEvaluator; using Evaluation = Evaluator::Evaluation; // Outer map: output score column name (e.g. _embedding_INDEX_SCORE) -> scores by real-time offset. // Inner map: real-time offset -> search score for that row. diff --git a/src/paimon/core/realtime/precise_realtime_index_read_test.cpp b/src/paimon/core/realtime/precise_realtime_index_read_test.cpp index 0e7130dc3..f5124d627 100644 --- a/src/paimon/core/realtime/precise_realtime_index_read_test.cpp +++ b/src/paimon/core/realtime/precise_realtime_index_read_test.cpp @@ -48,6 +48,7 @@ #include "paimon/core/table/source/topk_batch_reader.h" #include "paimon/factories/factory_creator.h" #include "paimon/fs/local/local_file_system.h" +#include "paimon/index/bitmap_result.h" #include "paimon/memory/memory_pool.h" #include "paimon/predicate/full_text_match.h" #include "paimon/predicate/full_text_search.h" @@ -225,8 +226,7 @@ class PreciseRealtimeIndexReadTest : public testing::Test { }; TEST_F(PreciseRealtimeIndexReadTest, FullTextMatchScoresAreOptional) { - using MatchResult = - IndexReaderUtils::FullTextResult; + using MatchResult = IndexReaderUtils::FullTextResult; // Scores must follow offset order even when the index ranks matches differently. state_->ranked = {{30, 0.9f}, {10, 0.8f}, {20, 0.7f}}; auto reader = std::make_shared( @@ -248,8 +248,7 @@ TEST_F(PreciseRealtimeIndexReadTest, FullTextMatchScoresAreOptional) { } TEST_F(PreciseRealtimeIndexReadTest, EmptyFullTextMatchPreservesRequestedScoreType) { - using MatchResult = - IndexReaderUtils::FullTextResult; + using MatchResult = IndexReaderUtils::FullTextResult; auto reader = std::make_shared( IndexReaderCapabilities::SearchType::FULL_TEXT_SEARCH, OffsetRange(10, 41), RoaringBitmap64::From({10, 20, 30, 40}), state_); @@ -270,7 +269,7 @@ TEST_F(PreciseRealtimeIndexReadTest, FullTextMatchRejectsMissingRequestedScores) public: Result> VisitFullTextMatch( const std::shared_ptr&, bool) override { - return RealtimeIndexResult::Create(RoaringBitmap64()); + return BitmapResult::Create(RoaringBitmap64(), /*is_exact=*/true); } }; auto reader = std::make_shared(); @@ -490,7 +489,7 @@ TEST_F(PreciseRealtimeIndexReadTest, PinnedSegmentsContributeToGlobalTopK) { TEST_F(PreciseRealtimeIndexReadTest, RejectsMisalignedScores) { ASSERT_NOK_WITH_MSG(ScoredRealtimeIndexResult::Create(RoaringBitmap64::From({10, 20}), {1.0f}), - "score count"); + "2 row positions but 1 scores"); } } // namespace diff --git a/src/paimon/core/realtime/realtime_offset_file_index_lookup.cpp b/src/paimon/core/realtime/realtime_offset_file_index_lookup.cpp index dd0fff40e..e5d39dc67 100644 --- a/src/paimon/core/realtime/realtime_offset_file_index_lookup.cpp +++ b/src/paimon/core/realtime/realtime_offset_file_index_lookup.cpp @@ -31,7 +31,7 @@ #include "paimon/core/realtime/realtime_file_schema.h" #include "paimon/core/realtime/realtime_key_offset_index.h" #include "paimon/core/realtime/realtime_utils.h" -#include "paimon/file_index/bitmap_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/fs/file_system.h" #include "paimon/predicate/literal.h" #include "paimon/predicate/predicate_builder.h" diff --git a/src/paimon/indexer/lumina/lumina_file_index.cpp b/src/paimon/indexer/lumina/lumina_file_index.cpp index e5d24d7d1..a19c91ad2 100644 --- a/src/paimon/indexer/lumina/lumina_file_index.cpp +++ b/src/paimon/indexer/lumina/lumina_file_index.cpp @@ -31,7 +31,7 @@ #include "paimon/common/io/memory_segment_output_stream.h" #include "paimon/common/io/offset_input_stream.h" #include "paimon/common/utils/arrow/status_utils.h" -#include "paimon/file_index/scored_file_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/indexer/lumina/lumina_file_writer.h" #include "paimon/indexer/lumina/lumina_utils.h" #include "paimon/memory/bytes.h" diff --git a/src/paimon/indexer/lumina/lumina_realtime_index_test.cpp b/src/paimon/indexer/lumina/lumina_realtime_index_test.cpp index efea49556..29804edb8 100644 --- a/src/paimon/indexer/lumina/lumina_realtime_index_test.cpp +++ b/src/paimon/indexer/lumina/lumina_realtime_index_test.cpp @@ -195,7 +195,9 @@ TEST_P(LuminaRealtimeIndexTest, ReportsVectorSearchCapabilityThroughBaseInterfac reader->VisitVectorSearch(Search(/*limit=*/1))); Check(result, RoaringBitmap64(), {}); std::shared_ptr base_result = result; - EXPECT_TRUE(base_result->GetRowPositions().IsEmpty()); + auto scored_result = std::dynamic_pointer_cast(base_result); + ASSERT_NE(scored_result, nullptr); + EXPECT_TRUE(scored_result->GetRowPositions().IsEmpty()); ASSERT_NOK(reader->VisitFullTextSearch(nullptr)); ASSERT_NOK(reader->VisitFullTextMatch(nullptr, /*needs_scores=*/true)); } @@ -320,8 +322,8 @@ TEST_P(LuminaRealtimeIndexTest, RejectsInvalidQueriesAndUnsupportedTags) { search = Search(/*limit=*/10); search->predicate = PredicateBuilder::Equal(0, "tag", FieldType::INT, Literal(int32_t{1})); ASSERT_NOK_WITH_MSG(reader->VisitVectorSearch(search), "tags are not supported"); - ASSERT_OK_AND_ASSIGN(std::optional candidates, reader->VisitIsNull()); - ASSERT_FALSE(candidates.has_value()); + ASSERT_OK_AND_ASSIGN(std::shared_ptr result, reader->VisitIsNull()); + ASSERT_NE(std::dynamic_pointer_cast>(result), nullptr); } TEST_P(LuminaRealtimeIndexTest, RejectsInvalidSchemasAndOptions) { diff --git a/src/paimon/testing/mock/mock_search_file_index.cpp b/src/paimon/testing/mock/mock_search_file_index.cpp index 0d7de6d74..ccd4c793d 100644 --- a/src/paimon/testing/mock/mock_search_file_index.cpp +++ b/src/paimon/testing/mock/mock_search_file_index.cpp @@ -30,8 +30,7 @@ #include "paimon/common/predicate/full_text_match_predicate.h" #include "paimon/common/utils/arrow/status_utils.h" #include "paimon/factories/factory.h" -#include "paimon/file_index/bitmap_index_result.h" -#include "paimon/file_index/scored_file_index_result.h" +#include "paimon/file_index/file_index_result.h" #include "paimon/io/data_input_stream.h" #include "paimon/memory/bytes.h" #include "paimon/predicate/full_text_match.h" diff --git a/src/paimon/testing/mock/mock_search_realtime_index_reader.h b/src/paimon/testing/mock/mock_search_realtime_index_reader.h index c313db424..cf559afda 100644 --- a/src/paimon/testing/mock/mock_search_realtime_index_reader.h +++ b/src/paimon/testing/mock/mock_search_realtime_index_reader.h @@ -28,6 +28,7 @@ #include #include +#include "paimon/index/bitmap_result.h" #include "paimon/predicate/full_text_match.h" #include "paimon/predicate/full_text_search.h" #include "paimon/predicate/vector_search.h" @@ -90,7 +91,7 @@ class MockSearchReader final : public RealtimeIndexReader { rows.Add(offset); } } - return RealtimeIndexResult::Create(std::move(rows)); + return BitmapResult::Create(std::move(rows), /*is_exact=*/true); } PAIMON_ASSIGN_OR_RAISE(std::shared_ptr result, Search(static_cast(state_->ranked.size()), filter)); From ccaa3fe954cb1ff8826a5e855a1895d1a5ee0fb6 Mon Sep 17 00:00:00 2001 From: lxy264173 Date: Thu, 26 Nov 2026 14:50:04 +0800 Subject: [PATCH 2/3] fix(index): enforce no-false-negative scalar results --- docs/source/user_guide/file_index.rst | 2 + include/paimon/file_index/file_index_reader.h | 2 + include/paimon/index/index_result.h | 3 +- include/paimon/read_context.h | 2 +- .../file_index/bitmap/bitmap_file_index.cpp | 9 +- .../bitmap/bitmap_file_index_test.cpp | 31 ++-- .../bsi/bit_slice_index_bitmap_file_index.cpp | 10 +- ...bit_slice_index_bitmap_file_index_test.cpp | 31 +--- .../file_index/file_index_format_test.cpp | 144 +++++------------- .../file_index/truncated_value_reader.h | 46 ++++++ src/paimon/common/index/index_reader_utils.h | 10 +- .../common/predicate/predicate_validator.h | 37 +++++ .../predicate/predicate_validator_test.cpp | 45 ++++++ .../core/io/file_index_evaluator_test.cpp | 43 ++++-- .../precise_file_index_read_test.cpp | 28 +++- .../core/operation/precise_index_evaluator.h | 13 +- .../index/realtime_index_evaluator.cpp | 28 +--- .../realtime/index/realtime_index_test.cpp | 50 ++++++ 18 files changed, 324 insertions(+), 210 deletions(-) create mode 100644 src/paimon/common/file_index/truncated_value_reader.h diff --git a/docs/source/user_guide/file_index.rst b/docs/source/user_guide/file_index.rst index 5a8378748..23cf3fb62 100644 --- a/docs/source/user_guide/file_index.rst +++ b/docs/source/user_guide/file_index.rst @@ -30,6 +30,8 @@ exact matching row positions within that file. within the candidates used for that evaluation. ``Remain`` is not exact, while ``Skip`` is exact. A bitmap alone does not imply exactness. Combining different predicates preserves an exact guarantee only when justified by both results. +Scalar index results never omit matches, but inexact results may contain false +positives. For a root full-text or vector TopK request, predicate filtering, row-range restrictions and deletion vectors are applied before the TopK limit. Filtering after diff --git a/include/paimon/file_index/file_index_reader.h b/include/paimon/file_index/file_index_reader.h index d1ffc8750..5a97a8e18 100644 --- a/include/paimon/file_index/file_index_reader.h +++ b/include/paimon/file_index/file_index_reader.h @@ -45,8 +45,10 @@ struct FullTextMatch; /// including when no rows match. /// /// Readers set FileIndexResult::IsExact() when creating each result; callers use that guarantee. +/// Scalar results may contain false positives but must not omit matching rows. /// @note Callers of `Visit*` for DECIMAL fields must ensure each literal's scale matches the scale /// of the indexed data; otherwise, index filtering results may be incorrect. +/// TIMESTAMP literals must match the indexed field's precision. class PAIMON_EXPORT FileIndexReader : public IndexReaderCapabilities, public FunctionVisitor> { public: diff --git a/include/paimon/index/index_result.h b/include/paimon/index/index_result.h index 9d2094cde..68d1a1c6d 100644 --- a/include/paimon/index/index_result.h +++ b/include/paimon/index/index_result.h @@ -29,7 +29,8 @@ namespace paimon { /// An index result within one source, read view and candidate scope. /// Implementations are provided for RoaringBitmap32 and RoaringBitmap64. /// Bitmap constrains And/Or to compatible result types; this base class stores no bitmap. -/// Exact results contain all and only matching rows. Inexact results may omit matches. +/// Scalar predicate results never omit matches: exact results contain only matching rows, +/// while inexact results may contain false positives. This does not guarantee search recall. template class PAIMON_EXPORT IndexResult : public std::enable_shared_from_this> { public: diff --git a/include/paimon/read_context.h b/include/paimon/read_context.h index dbefd974a..d0fb2e1c9 100644 --- a/include/paimon/read_context.h +++ b/include/paimon/read_context.h @@ -396,7 +396,7 @@ class PAIMON_EXPORT ReadContextBuilder { /// Compute exact file-local result row positions during file-index evaluation, using the /// configured Predicate and optional VectorSearch or FullTextSearch request. /// Requires file-index.read.enabled=true. Uses exact scalar index results directly and - /// rechecks the original candidate scope when indexes are inexact. If a scalar predicate's + /// rechecks intersected candidates when indexes are inexact. If a scalar predicate's /// field has no index, reads the data to compute exact matching rows. Only scalar predicates /// may be evaluated without an index. Score output must use named projections such as /// __INDEX_SCORE; projecting _INDEX_SCORE by name, field ID or read schema is not diff --git a/src/paimon/common/file_index/bitmap/bitmap_file_index.cpp b/src/paimon/common/file_index/bitmap/bitmap_file_index.cpp index ee1514078..d80c0232d 100644 --- a/src/paimon/common/file_index/bitmap/bitmap_file_index.cpp +++ b/src/paimon/common/file_index/bitmap/bitmap_file_index.cpp @@ -26,6 +26,7 @@ #include "paimon/common/file_index/bitmap/bitmap_file_index_meta.h" #include "paimon/common/file_index/bitmap/bitmap_file_index_meta_v1.h" #include "paimon/common/file_index/bitmap/bitmap_file_index_meta_v2.h" +#include "paimon/common/file_index/truncated_value_reader.h" #include "paimon/common/io/offset_input_stream.h" #include "paimon/common/memory/memory_segment_utils.h" #include "paimon/common/utils/arrow/status_utils.h" @@ -136,7 +137,13 @@ Result> BitmapFileIndex::CreateReader( auto arrow_type = arrow_schema->field(0)->type(); PAIMON_ASSIGN_OR_RAISE(FieldType data_type, FieldTypeUtils::ConvertToFieldType(arrow_type->id())); - return std::make_shared(arrow_type, data_type, bounded_stream, pool); + auto reader = + std::make_shared(arrow_type, data_type, bounded_stream, pool); + if (data_type == FieldType::TIMESTAMP && + checked_pointer_cast(arrow_type)->unit() == arrow::TimeUnit::NANO) { + return std::make_shared(std::move(reader)); + } + return reader; } Result> BitmapFileIndex::CreateWriter( diff --git a/src/paimon/common/file_index/bitmap/bitmap_file_index_test.cpp b/src/paimon/common/file_index/bitmap/bitmap_file_index_test.cpp index 32c4d8f67..5ce72d83d 100644 --- a/src/paimon/common/file_index/bitmap/bitmap_file_index_test.cpp +++ b/src/paimon/common/file_index/bitmap/bitmap_file_index_test.cpp @@ -675,31 +675,22 @@ TEST_F(BitmapIndexTest, TestTimestampType) { const Literal timestamp(Timestamp(1745542802000l, 123000)); auto predicate = std::dynamic_pointer_cast( PredicateBuilder::Equal(0, "f0", FieldType::TIMESTAMP, timestamp)); - auto candidates = RoaringBitmap32::From({0, 6}); + auto candidates = RoaringBitmap32::From({0, 1, 6}); ASSERT_OK_AND_ASSIGN(std::shared_ptr result, reader->Evaluate(predicate, &candidates)); ASSERT_FALSE(result->IsExact()); - CheckResult(result, {0, 6}); + CheckResult(result, {0, 1, 6}); CheckResult(reader->VisitIsNotNull().value(), {0, 1, 2, 3, 4, 6, 7}); ASSERT_TRUE(reader->VisitIsNotNull().value()->IsExact()); - CheckResult(reader->VisitEqual(Literal(Timestamp(1745542502000l, 123000))).value(), {}); - // as timestamp is normalized by micro seconds, there is a loss of precision in the - // nanosecond part - CheckResult(reader->VisitEqual(Literal(Timestamp(1745542802000l, 123000))).value(), {0, 6}); - CheckResult(reader->VisitNotEqual(Literal(Timestamp(1745542802000l, 123000))).value(), - {1, 2, 3, 4, 7}); - CheckResult(reader - ->VisitIn({Literal(Timestamp(1745542802000l, 123000)), - Literal(Timestamp(-1745, 123000)), - Literal(Timestamp(1745542602000, 123000))}) - .value(), - {0, 2, 3, 6}); - CheckResult(reader - ->VisitNotIn({Literal(Timestamp(1745542802000l, 123000)), - Literal(Timestamp(-1745, 123000)), - Literal(Timestamp(1745542602000, 123000))}) - .value(), - {1, 4, 7}); + // Java stores microseconds, so value comparisons on nanosecond fields must fall back. + for (const auto& comparison : + {reader->VisitEqual(timestamp), reader->VisitNotEqual(timestamp), + reader->VisitIn({timestamp}), reader->VisitNotIn({timestamp}), + reader->VisitGreaterThan(timestamp), reader->VisitGreaterOrEqual(timestamp), + reader->VisitLessThan(timestamp), reader->VisitLessOrEqual(timestamp)}) { + ASSERT_OK(comparison); + ASSERT_EQ(comparison.value(), FileIndexResult::Remain()); + } }; { // test write and read, v1 version diff --git a/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index.cpp b/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index.cpp index c99bda7eb..379972a11 100644 --- a/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index.cpp +++ b/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index.cpp @@ -31,6 +31,7 @@ #include "arrow/c/bridge.h" #include "fmt/format.h" #include "paimon/common/file_index/bsi/bit_slice_index_roaring_bitmap.h" +#include "paimon/common/file_index/truncated_value_reader.h" #include "paimon/common/io/memory_segment_output_stream.h" #include "paimon/common/io/offset_input_stream.h" #include "paimon/common/memory/memory_segment_utils.h" @@ -250,8 +251,13 @@ Result> BitSliceIndexBitmapFileIndex::CreateRea GetValueMapper(arrow_type)); PAIMON_ASSIGN_OR_RAISE(FieldType data_type, FieldTypeUtils::ConvertToFieldType(arrow_type->id())); - return std::make_shared(row_number, data_type, value_mapper, - positive, negative); + auto reader = std::make_shared( + row_number, data_type, value_mapper, positive, negative); + if (data_type == FieldType::TIMESTAMP && + checked_pointer_cast(arrow_type)->unit() == arrow::TimeUnit::NANO) { + return std::make_shared(std::move(reader)); + } + return reader; } // precondition, literal is not null diff --git a/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index_test.cpp b/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index_test.cpp index 0a803a5c5..8ed08c5fb 100644 --- a/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index_test.cpp +++ b/src/paimon/common/file_index/bsi/bit_slice_index_bitmap_file_index_test.cpp @@ -351,7 +351,7 @@ TEST_F(BitSliceIndexBitmapIndexReaderTest, TestPrimitiveType) { check_result(arrow::int32(), Literal(static_cast(1))); check_result(arrow::date32(), Literal(FieldType::DATE, 1)); check_result(arrow::int64(), Literal(static_cast(1))); - check_result(arrow::timestamp(arrow::TimeUnit::NANO), Literal(Timestamp(0, 1000))); + check_result(arrow::timestamp(arrow::TimeUnit::MICRO), Literal(Timestamp(0, 1000))); } TEST_F(BitSliceIndexBitmapIndexReaderTest, TestTimestampType) { @@ -447,37 +447,10 @@ TEST_F(BitSliceIndexBitmapIndexReaderTest, TestTimestampType) { reader->VisitGreaterThan(timestamp), reader->VisitGreaterOrEqual(timestamp), reader->VisitLessThan(timestamp), reader->VisitLessOrEqual(timestamp)}) { ASSERT_OK(result); - ASSERT_FALSE(result.value()->IsExact()); + ASSERT_EQ(result.value(), FileIndexResult::Remain()); } CheckResult(reader->VisitIsNotNull().value(), {0, 1, 2, 3, 4, 6, 7}); ASSERT_TRUE(reader->VisitIsNotNull().value()->IsExact()); - // as timestamp is normalized by micro seconds, there is a loss of precision in the nanosecond - // part - CheckResult(reader->VisitGreaterThan(Literal(Timestamp(1745542802000l, 123000))).value(), {1}); - CheckResult(reader->VisitGreaterOrEqual(Literal(Timestamp(1745542802000l, 123000))).value(), - {0, 1, 6}); - CheckResult(reader->VisitLessThan(Literal(Timestamp(-1745, 123000))).value(), {4}); - CheckResult(reader->VisitLessOrEqual(Literal(Timestamp(0, 123000))).value(), {3, 4, 7}); - CheckResult(reader->VisitEqual(Literal(Timestamp(1745542502000l, 123000))).value(), {}); - CheckResult(reader->VisitEqual(Literal(Timestamp(1745542802000l, 123000))).value(), {0, 6}); - CheckResult(reader->VisitNotEqual(Literal(Timestamp(1745542802000l, 123000))).value(), - {1, 2, 3, 4, 7}); - CheckResult(reader - ->VisitIn({Literal(Timestamp(1745542802000l, 123000)), - Literal(Timestamp(-1745, 123000)), - Literal(Timestamp(1745542602000, 123000))}) - .value(), - {0, 2, 3, 6}); - CheckResult(reader - ->VisitNotIn({Literal(Timestamp(1745542802000l, 123000)), - Literal(Timestamp(-1745, 123000)), - Literal(Timestamp(1745542602000, 123000))}) - .value(), - {1, 4, 7}); - - // test invalid case - ASSERT_NOK_WITH_MSG(reader->VisitEqual(Literal(FieldType::TIMESTAMP)).value()->IsRemain(), - "literal cannot be null when GetValue in BitSliceIndexBitmapFileIndex"); } TEST_F(BitSliceIndexBitmapIndexReaderTest, TestDecimalType) { diff --git a/src/paimon/common/file_index/file_index_format_test.cpp b/src/paimon/common/file_index/file_index_format_test.cpp index 611d7ecb8..b9b92da2e 100644 --- a/src/paimon/common/file_index/file_index_format_test.cpp +++ b/src/paimon/common/file_index/file_index_format_test.cpp @@ -850,124 +850,48 @@ TEST_F(FileIndexFormatTest, TestBitmapIndexWithTimestamp) { // 1745542802001lms, 1001ns // -1725001lms, 1001ns - // as timestamp is normalized by micro seconds, there is a loss of precision in the - // nanosecond part + // Nanosecond values lose precision in Bitmap/BSI storage. Only null checks + // can prune rows; value comparisons must retain all candidates. ASSERT_OK_AND_ASSIGN(auto index_file_readers, reader->ReadColumnIndex(field_name, CreateArrowSchema(schema).get())); ASSERT_EQ(3, index_file_readers.size()); - BitSliceIndexBitmapFileIndexReader* bsi_reader = nullptr; - BitmapFileIndexReader* bitmap_reader = nullptr; BloomFilterFileIndexReader* bloom_filter_reader = nullptr; + int32_t truncated_reader_count = 0; + for (const auto& index_reader : index_file_readers) { + if (auto* bloom = dynamic_cast(index_reader.get())) { + bloom_filter_reader = bloom; + continue; + } + ++truncated_reader_count; + ASSERT_OK_AND_ASSIGN(std::shared_ptr null_result, + index_reader->VisitIsNull()); + ASSERT_EQ("{5}", null_result->ToString()); + ASSERT_TRUE(null_result->IsExact()); + ASSERT_OK_AND_ASSIGN(std::shared_ptr nonnull_result, + index_reader->VisitIsNotNull()); + ASSERT_EQ("{0,1,2,3,4,6,7}", nonnull_result->ToString()); + ASSERT_TRUE(nonnull_result->IsExact()); - for (const auto& reader : index_file_readers) { - if (auto* r = dynamic_cast(reader.get())) { - bsi_reader = r; - } else if (auto* r = dynamic_cast(reader.get())) { - bitmap_reader = r; - } else if (auto* r = dynamic_cast(reader.get())) { - bloom_filter_reader = r; + for (const Literal& literal : + {Literal(Timestamp(1745542502001l, 1000)), + Literal(Timestamp(1745542802001l, 1000)), + Literal(Timestamp(1745542802001l, 1001)), Literal(Timestamp(-1745001l, 1000))}) { + for (const auto& result : + {index_reader->VisitEqual(literal), index_reader->VisitNotEqual(literal), + index_reader->VisitIn({literal, Literal(Timestamp(1745542602001l, 1000))}), + index_reader->VisitNotIn({literal, Literal(Timestamp(1745542602001l, 1000))}), + index_reader->VisitGreaterThan(literal), + index_reader->VisitGreaterOrEqual(literal), + index_reader->VisitLessThan(literal), + index_reader->VisitLessOrEqual(literal)}) { + ASSERT_OK(result); + ASSERT_EQ(result.value(), FileIndexResult::Remain()); + ASSERT_FALSE(result.value()->IsExact()); + } } } - ASSERT_TRUE(bsi_reader); - ASSERT_TRUE(bitmap_reader); + ASSERT_EQ(2, truncated_reader_count); ASSERT_TRUE(bloom_filter_reader); - // test bitmap - { - ASSERT_OK_AND_ASSIGN(auto result, bitmap_reader->VisitIsNull()); - ASSERT_EQ("{5}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN(auto result, bitmap_reader->VisitIsNotNull()); - ASSERT_EQ("{0,1,2,3,4,6,7}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN( - auto result, bitmap_reader->VisitEqual(Literal(Timestamp(1745542502001l, 1000)))); - ASSERT_EQ("{}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN( - auto result, bitmap_reader->VisitEqual(Literal(Timestamp(1745542802001l, 1001)))); - ASSERT_EQ("{0,6}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN(auto result, bitmap_reader->VisitNotEqual( - Literal(Timestamp(1745542802001l, 1001)))); - ASSERT_EQ("{1,2,3,4,7}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN( - auto result, bitmap_reader->VisitIn({Literal(Timestamp(1745542802001l, 1001)), - Literal(Timestamp(-1745001l, 1000)), - Literal(Timestamp(1745542602001l, 1000))})); - ASSERT_EQ("{0,2,3,6}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN( - auto result, bitmap_reader->VisitNotIn({Literal(Timestamp(1745542802001l, 1001)), - Literal(Timestamp(-1745001l, 1000)), - Literal(Timestamp(1745542602001l, 1000))})); - ASSERT_EQ("{1,4,7}", result->ToString()); - } - - // test bsi - { - ASSERT_OK_AND_ASSIGN(auto result, bsi_reader->VisitIsNull()); - ASSERT_EQ("{5}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN(auto result, bsi_reader->VisitIsNotNull()); - ASSERT_EQ("{0,1,2,3,4,6,7}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN(auto result, - bsi_reader->VisitEqual(Literal(Timestamp(1745542502001l, 1000)))); - ASSERT_EQ("{}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN(auto result, - bsi_reader->VisitEqual(Literal(Timestamp(1745542802001l, 1001)))); - ASSERT_EQ("{0,6}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN( - auto result, bsi_reader->VisitNotEqual(Literal(Timestamp(1745542802001l, 1001)))); - ASSERT_EQ("{1,2,3,4,7}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN(auto result, - bsi_reader->VisitIn({Literal(Timestamp(1745542802001l, 1001)), - Literal(Timestamp(-1745001l, 1000)), - Literal(Timestamp(1745542602001l, 1000))})); - ASSERT_EQ("{0,2,3,6}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN( - auto result, bsi_reader->VisitNotIn({Literal(Timestamp(1745542802001l, 1001)), - Literal(Timestamp(-1745001l, 1000)), - Literal(Timestamp(1745542602001l, 1000))})); - ASSERT_EQ("{1,4,7}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN(auto result, bsi_reader->VisitGreaterThan( - Literal(Timestamp(1745542802001l, 1000)))); - ASSERT_EQ("{1}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN(auto result, bsi_reader->VisitGreaterOrEqual( - Literal(Timestamp(1745542802001l, 1000)))); - ASSERT_EQ("{0,1,6}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN(auto result, - bsi_reader->VisitLessThan(Literal(Timestamp(-1745001l, 1000)))); - ASSERT_EQ("{4}", result->ToString()); - } - { - ASSERT_OK_AND_ASSIGN(auto result, - bsi_reader->VisitLessOrEqual(Literal(Timestamp(0l, 1000)))); - ASSERT_EQ("{3,4,7}", result->ToString()); - } // test bloom filter ASSERT_TRUE(bloom_filter_reader->VisitEqual(Literal(Timestamp(1745542802001l, 1001))) diff --git a/src/paimon/common/file_index/truncated_value_reader.h b/src/paimon/common/file_index/truncated_value_reader.h new file mode 100644 index 000000000..001c73d0a --- /dev/null +++ b/src/paimon/common/file_index/truncated_value_reader.h @@ -0,0 +1,46 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include "paimon/file_index/file_index_reader.h" + +namespace paimon { + +/// Truncated index values can still answer null checks. Other predicates retain all candidates. +class TruncatedValueReader : public FileIndexReader { + public: + explicit TruncatedValueReader(std::shared_ptr reader) + : reader_(std::move(reader)) {} + + Result> VisitIsNull() override { + return reader_->VisitIsNull(); + } + + Result> VisitIsNotNull() override { + return reader_->VisitIsNotNull(); + } + + private: + std::shared_ptr reader_; +}; + +} // namespace paimon diff --git a/src/paimon/common/index/index_reader_utils.h b/src/paimon/common/index/index_reader_utils.h index 1ff752095..1dd5f5f57 100644 --- a/src/paimon/common/index/index_reader_utils.h +++ b/src/paimon/common/index/index_reader_utils.h @@ -152,8 +152,7 @@ class IndexReaderUtils { if (candidates && candidates->IsEmpty()) { return IndexResult::Skip(); } - // TODO(xinyu.lxy): Redefine IsExact semantics and allow ANDing results from multiple - // indexes on the same field when none is exact. + std::shared_ptr> combined = IndexResult::Remain(); for (const auto& reader : readers) { PAIMON_ASSIGN_OR_RAISE(std::shared_ptr> result, reader->Evaluate(predicate, candidates)); @@ -163,8 +162,13 @@ class IndexReaderUtils { if (result->IsExact()) { return result; } + PAIMON_ASSIGN_OR_RAISE(combined, combined->And(result)); + PAIMON_ASSIGN_OR_RAISE(bool remain, combined->IsRemain()); + if (!remain) { + return IndexResult::Skip(); + } } - return IndexResult::Remain(); + return combined; } template diff --git a/src/paimon/common/predicate/predicate_validator.h b/src/paimon/common/predicate/predicate_validator.h index 00241723f..16925ba4c 100644 --- a/src/paimon/common/predicate/predicate_validator.h +++ b/src/paimon/common/predicate/predicate_validator.h @@ -30,6 +30,7 @@ #include "paimon/common/utils/date_time_utils.h" #include "paimon/common/utils/field_type_utils.h" #include "paimon/data/decimal.h" +#include "paimon/data/timestamp.h" #include "paimon/defs.h" #include "paimon/predicate/compound_predicate.h" #include "paimon/predicate/function.h" @@ -116,6 +117,9 @@ class PredicateValidator { *checked_pointer_cast(schema_type), *leaf_predicate)); } else if (schema_type->id() == arrow::Type::TIME32) { PAIMON_RETURN_NOT_OK(ValidateTimeLiterals(*leaf_predicate)); + } else if (schema_type->id() == arrow::Type::TIMESTAMP) { + PAIMON_RETURN_NOT_OK(ValidateTimestampLiterals( + *checked_pointer_cast(schema_type), *leaf_predicate)); } } else if (auto compound_predicate = std::dynamic_pointer_cast(predicate)) { @@ -150,6 +154,39 @@ class PredicateValidator { return Status::OK(); } + static Status ValidateTimestampLiterals(const arrow::TimestampType& field_type, + const LeafPredicate& predicate) { + for (const Literal& literal : predicate.Literals()) { + if (literal.IsNull()) { + continue; + } + const Timestamp timestamp = literal.GetValue(); + const int32_t nanos = timestamp.GetNanoOfMillisecond(); + bool aligned = false; + switch (field_type.unit()) { + case arrow::TimeUnit::SECOND: + aligned = timestamp.GetMillisecond() % 1000 == 0 && nanos == 0; + break; + case arrow::TimeUnit::MILLI: + aligned = nanos == 0; + break; + case arrow::TimeUnit::MICRO: + aligned = nanos % 1000 == 0; + break; + case arrow::TimeUnit::NANO: + aligned = true; + break; + } + if (!aligned) { + return Status::Invalid(fmt::format( + "timestamp literal for field {} cannot be represented without precision " + "loss in {}", + predicate.FieldName(), field_type.ToString())); + } + } + return Status::OK(); + } + static Status ValidateTimeLiterals(const LeafPredicate& predicate) { for (const Literal& literal : predicate.Literals()) { if (literal.IsNull()) { diff --git a/src/paimon/common/predicate/predicate_validator_test.cpp b/src/paimon/common/predicate/predicate_validator_test.cpp index 487482db9..76acfe7dc 100644 --- a/src/paimon/common/predicate/predicate_validator_test.cpp +++ b/src/paimon/common/predicate/predicate_validator_test.cpp @@ -492,6 +492,51 @@ TEST(PredicateValidatorTest, TestValidateDecimalLiteral) { } } +TEST(PredicateValidatorTest, TestValidateTimestampPrecision) { + struct TestCase { + arrow::TimeUnit::type unit; + std::vector valid; + std::vector invalid; + }; + const std::vector cases = { + {arrow::TimeUnit::SECOND, + {Timestamp(0, 0), Timestamp(1000, 0), Timestamp(-1000, 0)}, + {Timestamp(1, 0), Timestamp(-1, 0), Timestamp(1000, 1)}}, + {arrow::TimeUnit::MILLI, + {Timestamp(1, 0), Timestamp(-1, 0)}, + {Timestamp(1, 1000), Timestamp(-1, 999999)}}, + {arrow::TimeUnit::MICRO, + {Timestamp(1, 1000), Timestamp(-1, 999000)}, + {Timestamp(1, 1), Timestamp(-1, 999999)}}, + {arrow::TimeUnit::NANO, {Timestamp(1, 1), Timestamp(-1, 999999)}, {}}, + }; + for (const auto& test_case : cases) { + for (const std::string& timezone : {std::string(), std::string("UTC")}) { + auto schema = + arrow::schema({arrow::field("ts", arrow::timestamp(test_case.unit, timezone))}); + auto is_null = PredicateBuilder::IsNull(0, "ts", FieldType::TIMESTAMP); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema(*schema, is_null, + /*validate_field_idx=*/true)); + for (const Timestamp& timestamp : test_case.valid) { + auto predicate = + PredicateBuilder::Equal(0, "ts", FieldType::TIMESTAMP, Literal(timestamp)); + ASSERT_OK(PredicateValidator::ValidatePredicateWithSchema( + *schema, predicate, /*validate_field_idx=*/true)); + } + for (const Timestamp& timestamp : test_case.invalid) { + // Check every IN literal, including predicates nested in a compound. + auto in = PredicateBuilder::In(0, "ts", FieldType::TIMESTAMP, + {Literal(Timestamp(0, 0)), Literal(timestamp)}); + ASSERT_OK_AND_ASSIGN(auto predicate, PredicateBuilder::Or({is_null, in})); + ASSERT_NOK_WITH_MSG( + PredicateValidator::ValidatePredicateWithSchema(*schema, predicate, + /*validate_field_idx=*/true), + "timestamp literal for field ts cannot be represented without precision loss"); + } + } + } +} + TEST(PredicateValidatorTest, TestValidateTime) { std::shared_ptr schema = arrow::schema(arrow::FieldVector({ arrow::field("t", arrow::time32(arrow::TimeUnit::MILLI)), diff --git a/src/paimon/core/io/file_index_evaluator_test.cpp b/src/paimon/core/io/file_index_evaluator_test.cpp index d30199e28..f4fba563f 100644 --- a/src/paimon/core/io/file_index_evaluator_test.cpp +++ b/src/paimon/core/io/file_index_evaluator_test.cpp @@ -455,8 +455,8 @@ TEST_F(FileIndexEvaluatorTest, TestTimestampType) { FileIndexEvaluator::Create(data_schema, core_options_.ToMap(), data_file_path_factory, data_file_meta, /*file_system=*/fs_, /*cache=*/nullptr, pool_)); ASSERT_OK_AND_ASSIGN(auto file_index_result, evaluator->Evaluate(predicate)); - // Timestamp comparisons are inexact, so defer to data filtering. - ASSERT_EQ(file_index_result, FileIndexResult::Remain()); + // Intersect the inexact timestamp candidates before rechecking the data. + CheckResult(file_index_result, {0, 6}); ASSERT_FALSE(file_index_result->IsExact()); } @@ -941,9 +941,10 @@ TEST_P(FileIndexSearchEvaluatorTest, TestScalarIndexesUseFirstExactResult) { ASSERT_TRUE(result->IsExact()); ASSERT_TRUE(second->candidates.empty()); - // Inexact results, including empty ones, must not narrow the next reader's scope. + // Prefer an exact result over earlier candidate supersets. second->result = make_bitmap_result(RoaringBitmap32::From({2, 3}), /*is_exact=*/true); - for (const RoaringBitmap32& rows : {RoaringBitmap32::From({0}), RoaringBitmap32()}) { + for (const RoaringBitmap32& rows : + {RoaringBitmap32::From({0, 2}), RoaringBitmap32::From({0, 1, 2})}) { first->result = make_bitmap_result(rows, /*is_exact=*/false); const size_t executions = second->candidates.size(); ASSERT_OK_AND_ASSIGN(result, evaluator->EvaluateLeaf(predicate, false, &candidates)); @@ -960,27 +961,46 @@ TEST_P(FileIndexSearchEvaluatorTest, TestScalarIndexesUseFirstExactResult) { ASSERT_TRUE(result->IsExact()); ASSERT_EQ(second->candidates.back(), candidates); - // Without any exact result, return Remain and require rechecking the input scope. + // Without an exact result, intersect all candidate supersets. second->result = make_bitmap_result(RoaringBitmap32::From({2, 3}), /*is_exact=*/false); for (bool remain : {false, true}) { if (remain) { first->result = FileIndexResult::Remain(); } else { - first->result = make_bitmap_result(RoaringBitmap32(), /*is_exact=*/false); + first->result = make_bitmap_result(RoaringBitmap32::From({0, 2}), /*is_exact=*/false); } for (const RoaringBitmap32* scope : std::vector{&candidates, nullptr}) { ASSERT_OK_AND_ASSIGN(result, evaluator->EvaluateLeaf(predicate, false, scope)); - ASSERT_EQ(result, FileIndexResult::Remain()); + if (remain && !scope) { + CheckResult(result, {2, 3}); + } else { + CheckResult(result, {2}); + } ASSERT_FALSE(result->IsExact()); ASSERT_EQ(first->candidates.back(), second->candidates.back()); } } second->result = FileIndexResult::Remain(); ASSERT_OK_AND_ASSIGN(result, evaluator->EvaluateLeaf(predicate, false, &candidates)); - ASSERT_EQ(result, FileIndexResult::Remain()); + CheckResult(result, {0, 1, 2}); ASSERT_FALSE(result->IsExact()); + ASSERT_OK_AND_ASSIGN(result, evaluator->EvaluateLeaf(predicate, false, nullptr)); + ASSERT_EQ(result, FileIndexResult::Remain()); + + // An empty superset proves that there are no matches and stops later readers. + first->result = make_bitmap_result(RoaringBitmap32(), /*is_exact=*/false); + const size_t executions = second->candidates.size(); + ASSERT_OK_AND_ASSIGN(result, evaluator->EvaluateLeaf(predicate, false, &candidates)); + ASSERT_EQ(result, FileIndexResult::Skip()); + ASSERT_EQ(second->candidates.size(), executions); + + first->result = make_bitmap_result(RoaringBitmap32::From({0}), /*is_exact=*/false); + second->result = make_bitmap_result(RoaringBitmap32::From({2}), /*is_exact=*/false); + ASSERT_OK_AND_ASSIGN(result, evaluator->EvaluateLeaf(predicate, false, &candidates)); + ASSERT_EQ(result, FileIndexResult::Skip()); + RoaringBitmap32 empty_candidates; const size_t first_executions = first->candidates.size(); const size_t second_executions = second->candidates.size(); @@ -1024,12 +1044,13 @@ TEST_P(FileIndexSearchEvaluatorTest, TestPreservesReaderResultAndExactness) { for (const auto& leaf : {scalar, full_text}) { ASSERT_OK_AND_ASSIGN(std::shared_ptr result, evaluator->EvaluateLeaf(leaf, false, nullptr)); - if (leaf == scalar && !is_exact) { - ASSERT_EQ(result, FileIndexResult::Remain()); + if (leaf == scalar && !is_exact && empty) { + ASSERT_EQ(result, FileIndexResult::Skip()); + ASSERT_TRUE(result->IsExact()); } else { ASSERT_EQ(result, state->result); + ASSERT_EQ(result->IsExact(), is_exact); } - ASSERT_EQ(result->IsExact(), is_exact); } std::vector scores = empty ? std::vector() : std::vector({0.5f, 0.9f}); diff --git a/src/paimon/core/operation/precise_file_index_read_test.cpp b/src/paimon/core/operation/precise_file_index_read_test.cpp index 6effbf2ae..f99260fa7 100644 --- a/src/paimon/core/operation/precise_file_index_read_test.cpp +++ b/src/paimon/core/operation/precise_file_index_read_test.cpp @@ -77,9 +77,9 @@ class TestScalarFileIndexReader : public FileIndexReader { } Result> Evaluate(const std::shared_ptr&, - const RoaringBitmap32*) override { + const RoaringBitmap32* candidates) override { ++evaluate_count_; - return result_; + return IndexReaderUtils::RestrictScalarResult(result_, candidates); } private: @@ -633,9 +633,16 @@ TEST_F(PreciseFileIndexReadTest, TestMixedPredicateRechecksScalarIndexCandidates ASSERT_TRUE(statistics_->executions.front().needs_scores); } -TEST_F(PreciseFileIndexReadTest, TestInexactScalarIndexRecoversMissingRows) { +TEST_F(PreciseFileIndexReadTest, TestInexactScalarIndexRechecksCandidates) { auto field = arrow::field("f3", arrow::float64()); - auto predicate = PredicateBuilder::NotEqual(1, "f3", FieldType::DOUBLE, Literal(13.1)); + auto scalar = std::dynamic_pointer_cast( + PredicateBuilder::NotEqual(1, "f3", FieldType::DOUBLE, Literal(13.1))); + ASSERT_TRUE(scalar); + std::vector evaluated; + RecordingDoubleFunction function(scalar->GetLeafFunction(), &evaluated); + auto predicate = + std::make_shared(function, scalar->FieldIndex(), scalar->FieldName(), + scalar->GetFieldType(), scalar->Literals()); ReadContextBuilder builder(SearchTablePath()); builder.EnablePreciseFileIndexEvaluate(true) .SetReadFieldNames({"f0", "f3"}) @@ -663,14 +670,21 @@ TEST_F(PreciseFileIndexReadTest, TestInexactScalarIndexRecoversMissingRows) { indexes["f0"][statistics_index_type_] = text_payload; ASSERT_OK_AND_ASSIGN(std::shared_ptr index, MockSearchFileIndex::Serialize(indexes, pool_)); - // The actual matches are rows 0 and 2. Simulate partial and complete false negatives. - for (const auto& rows : {RoaringBitmap32::From({2}), RoaringBitmap32()}) { + // Both candidate sets contain all matches; the first also contains a false positive. + for (const auto& rows : {RoaringBitmap32::From({0, 1, 2}), RoaringBitmap32::From({0, 2})}) { scalar_index_result_ = std::make_shared( [rows]() -> Result { return rows; }, /*is_exact=*/false); + evaluated.clear(); ASSERT_OK_AND_ASSIGN(std::shared_ptr result, ReadWithFileIndex(context, index)); CheckSearchResult(result, {arrow::field("f0", arrow::utf8()), field}, R"([["Bob",12.1],["Tony",14.1]])"); + ASSERT_FALSE(evaluated.empty()); + if (rows == RoaringBitmap32::From({0, 2})) { + for (double value : evaluated) { + ASSERT_NE(value, 13.1); + } + } ASSERT_OK_AND_ASSIGN(result, ReadWithFileIndex(context, index, RoaringBitmap32::From({2}))); CheckSearchResult(result, {arrow::field("f0", arrow::utf8()), field}, R"([["Bob",12.1]])"); @@ -678,7 +692,7 @@ TEST_F(PreciseFileIndexReadTest, TestInexactScalarIndexRecoversMissingRows) { std::vector{Range(1, 2)})); CheckSearchResult(result, {arrow::field("f0", arrow::utf8()), field}, R"([["Tony",14.1]])"); - // Recovery must preserve the exact result of the preceding full-text predicate. + // Rechecking must preserve the exact result of the preceding full-text predicate. ASSERT_OK_AND_ASSIGN(result, ReadWithFileIndex(and_context, index)); CheckSearchResult(result, {arrow::field("f0", arrow::utf8()), field}, R"([["Bob",12.1]])"); } diff --git a/src/paimon/core/operation/precise_index_evaluator.h b/src/paimon/core/operation/precise_index_evaluator.h index 4f2ff7b3f..c90ab4037 100644 --- a/src/paimon/core/operation/precise_index_evaluator.h +++ b/src/paimon/core/operation/precise_index_evaluator.h @@ -87,7 +87,7 @@ class PreciseIndexEvaluator { } /// Field mapping and physical scans remain with the storage adapter. Exact index - /// results avoid scalar scans; inexact results recheck the original candidates. + /// results avoid scalar scans; inexact results narrow the candidates before rechecking. /// @param predicate Original predicate in the query's logical schema, used for exact /// scalar filtering and binding scores to the original field name. /// @param index_predicate Predicate mapped to the source's physical schema for index @@ -130,16 +130,21 @@ class PreciseIndexEvaluator { PAIMON_ASSIGN_OR_RAISE( std::shared_ptr> indexed, IndexReaderUtils::EvaluateScalar(readers, index_predicate, &candidates)); + PAIMON_ASSIGN_OR_RAISE(std::optional rows, + IndexReaderUtils::GetScalarRows(indexed)); if (indexed->IsExact()) { - PAIMON_ASSIGN_OR_RAISE(std::optional rows, - IndexReaderUtils::GetScalarRows(indexed)); if (!rows) { return Status::Invalid("Exact scalar index result has no row positions"); } return Evaluation{std::move(*rows), {}}; } + if (rows) { + result.rows = std::move(*rows); + } + } + if (!result.rows.IsEmpty()) { + PAIMON_ASSIGN_OR_RAISE(result.rows, scan_scalar(predicate, result.rows)); } - PAIMON_ASSIGN_OR_RAISE(result.rows, scan_scalar(predicate, candidates)); return result; } diff --git a/src/paimon/core/realtime/index/realtime_index_evaluator.cpp b/src/paimon/core/realtime/index/realtime_index_evaluator.cpp index cc28ce929..2fa54f683 100644 --- a/src/paimon/core/realtime/index/realtime_index_evaluator.cpp +++ b/src/paimon/core/realtime/index/realtime_index_evaluator.cpp @@ -20,13 +20,14 @@ #include "paimon/core/realtime/index/realtime_index_evaluator.h" #include +#include +#include "paimon/common/index/index_reader_utils.h" #include "paimon/core/realtime/index/realtime_index_set.h" #include "paimon/macros.h" #include "paimon/predicate/compound_predicate.h" #include "paimon/predicate/function.h" #include "paimon/predicate/leaf_predicate.h" -#include "paimon/predicate/predicate_utils.h" #include "paimon/realtime/index/realtime_index.h" #include "paimon/realtime/index/realtime_index_reader.h" @@ -89,32 +90,17 @@ Result> RealtimeIndexEvaluator::EvaluateCom Result> RealtimeIndexEvaluator::EvaluateLeaf( const std::shared_ptr& indexes, const std::shared_ptr& leaf, const OffsetRange& offset_range, const std::shared_ptr& pool) { - std::shared_ptr result = RealtimeIndexResult::Remain(); + std::vector> readers; for (const std::shared_ptr& index : indexes->FindIndexes(leaf->FieldName(), leaf->GetFieldType())) { PAIMON_ASSIGN_OR_RAISE(std::shared_ptr reader, index->CreateReader(offset_range, pool)); - if (!reader) { - continue; - } - PAIMON_ASSIGN_OR_RAISE( - std::shared_ptr indexed, - PredicateUtils::VisitPredicate>(leaf, reader)); - if (!indexed) { - return Status::Invalid("Scalar index returned a null result"); - } - // These readers guarantee no false negatives. One exact result fully resolves - // this leaf; otherwise their candidate supersets can be intersected for pruning. - if (indexed->IsExact()) { - return indexed; - } - PAIMON_ASSIGN_OR_RAISE(result, result->And(indexed)); - PAIMON_ASSIGN_OR_RAISE(bool remain, result->IsRemain()); - if (!remain) { - break; + if (reader) { + readers.push_back(std::move(reader)); } } - return result; + return IndexReaderUtils::EvaluateScalar(readers, leaf, + /*candidates=*/nullptr); } } // namespace paimon diff --git a/src/paimon/core/realtime/index/realtime_index_test.cpp b/src/paimon/core/realtime/index/realtime_index_test.cpp index 6c8faadfd..3c3d84c28 100644 --- a/src/paimon/core/realtime/index/realtime_index_test.cpp +++ b/src/paimon/core/realtime/index/realtime_index_test.cpp @@ -107,6 +107,56 @@ class RealtimeIndexTest : public testing::Test { std::shared_ptr index_; }; +TEST_F(RealtimeIndexTest, ScalarResultsIntersectCandidatesAndPreferExactMatches) { + const int64_t offset = int64_t{1} << 40; + auto make_result = [](RoaringBitmap64 rows, bool exact) { + return std::make_shared>( + [rows]() -> Result { return rows; }, exact); + }; + std::vector> results = { + make_result(RoaringBitmap64::From({offset, offset + 1}), false), + RealtimeIndexResult::Remain(), + make_result(RoaringBitmap64::From({offset + 1, offset + 2}), false)}; + size_t evaluated = 0; + struct ResultReader { + Result> Evaluate(const std::shared_ptr&, + const RoaringBitmap64*) { + ++*evaluated; + return result; + } + + std::shared_ptr result; + size_t* evaluated; + }; + std::vector> readers; + for (const auto& result : results) { + readers.push_back(std::make_shared(ResultReader{result, &evaluated})); + } + const auto predicate = std::dynamic_pointer_cast(EqualId(1)); + ASSERT_OK_AND_ASSIGN(auto result, IndexReaderUtils::EvaluateScalar( + readers, predicate, nullptr)); + ASSERT_OK_AND_ASSIGN(auto rows, IndexReaderUtils::GetScalarRows(result)); + ASSERT_TRUE(rows.has_value()); + ASSERT_EQ(*rows, RoaringBitmap64::From({offset + 1})); + ASSERT_FALSE(result->IsExact()); + ASSERT_EQ(evaluated, 3); + + readers[1]->result = make_result(RoaringBitmap64::From({offset + 1}), true); + evaluated = 0; + ASSERT_OK_AND_ASSIGN( + result, IndexReaderUtils::EvaluateScalar(readers, predicate, nullptr)); + ASSERT_EQ(result, readers[1]->result); + ASSERT_TRUE(result->IsExact()); + ASSERT_EQ(evaluated, 2); + + readers[0]->result = make_result(RoaringBitmap64(), false); + evaluated = 0; + ASSERT_OK_AND_ASSIGN( + result, IndexReaderUtils::EvaluateScalar(readers, predicate, nullptr)); + ASSERT_EQ(result, RealtimeIndexResult::Skip()); + ASSERT_EQ(evaluated, 1); +} + TEST_F(RealtimeIndexTest, RetainsAllKeyAndValueOffsetsWithinBothBounds) { ASSERT_OK(Add(R"([[10, 1, "a"], [13, 2, "a"], [20, 1, "b"]])", OffsetRange(10, 21))); ASSERT_OK_AND_ASSIGN(std::optional keys, From d6a4cc23beac5a79dbce7bae5fa3b2c7bdf3d4c2 Mon Sep 17 00:00:00 2001 From: lxy264173 Date: Thu, 26 Nov 2026 15:58:10 +0800 Subject: [PATCH 3/3] fix ci --- src/paimon/common/predicate/predicate_validator.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/paimon/common/predicate/predicate_validator.h b/src/paimon/common/predicate/predicate_validator.h index 16925ba4c..34df6c8a8 100644 --- a/src/paimon/common/predicate/predicate_validator.h +++ b/src/paimon/common/predicate/predicate_validator.h @@ -160,7 +160,7 @@ class PredicateValidator { if (literal.IsNull()) { continue; } - const Timestamp timestamp = literal.GetValue(); + const auto timestamp = literal.GetValue(); const int32_t nanos = timestamp.GetNanoOfMillisecond(); bool aligned = false; switch (field_type.unit()) {