lxy-9602 commented on code in PR #546:
URL: https://github.com/apache/paimon-cpp/pull/546#discussion_r4610482070


##########
src/paimon/core/realtime/precise_realtime_index_read.cpp:
##########
@@ -0,0 +1,462 @@
+/*
+ * 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/core/realtime/precise_realtime_index_read.h"
+
+#include <algorithm>
+#include <map>
+#include <optional>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "arrow/api.h"
+#include "arrow/c/bridge.h"
+#include "arrow/c/helpers.h"
+#include "fmt/format.h"
+#include "paimon/common/index/index_reader_utils.h"
+#include "paimon/common/reader/complete_row_kind_batch_reader.h"
+#include "paimon/common/reader/concat_batch_reader.h"
+#include "paimon/common/reader/index_score_batch_utils.h"
+#include "paimon/common/reader/predicate_batch_reader.h"
+#include "paimon/common/reader/reader_utils.h"
+#include "paimon/common/table/special_fields.h"
+#include "paimon/common/types/data_field.h"
+#include "paimon/common/utils/arrow/status_utils.h"
+#include "paimon/common/utils/checked_cast.h"
+#include "paimon/common/utils/scope_guard.h"
+#include "paimon/core/operation/internal_read_context.h"
+#include "paimon/core/operation/precise_index_evaluator.h"
+#include "paimon/core/realtime/realtime_reader.h"
+#include "paimon/core/realtime/realtime_schema_layout.h"
+#include "paimon/core/realtime/realtime_store_read_pipeline.h"
+#include "paimon/core/schema/table_schema.h"
+#include "paimon/predicate/full_text_match.h"
+#include "paimon/predicate/predicate_utils.h"
+#include "paimon/realtime/index/realtime_index_read_source.h"
+
+namespace paimon {
+namespace {
+
+using Evaluator = PreciseIndexEvaluator<RoaringBitmap64, 
ScoredRealtimeIndexResult>;
+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.
+using OutputScores = std::map<std::string, std::map<int64_t, float>>;
+
+/// Completes virtual scores and restores projection while offsets are still 
available.
+class RealtimeScoreBatchReader final : public BatchReader {
+ public:
+    RealtimeScoreBatchReader(std::unique_ptr<BatchReader> reader,
+                             std::shared_ptr<arrow::Schema> output_schema, 
OutputScores scores,
+                             const std::shared_ptr<arrow::MemoryPool>& 
arrow_pool)
+        : reader_(std::move(reader)),
+          output_schema_(std::move(output_schema)),
+          scores_(std::move(scores)),
+          arrow_pool_(arrow_pool) {}
+
+    Result<ReadBatch> NextBatch() override {
+        PAIMON_ASSIGN_OR_RAISE(ReadBatchWithBitmap batch, 
NextBatchWithBitmap());
+        return ReaderUtils::ApplyBitmapToReadBatch(std::move(batch), 
arrow_pool_);
+    }
+
+    Result<ReadBatchWithBitmap> NextBatchWithBitmap() override {
+        PAIMON_ASSIGN_OR_RAISE(ReadBatchWithBitmap batch, 
reader_->NextBatchWithBitmap());
+        if (IsEofBatch(batch)) {
+            return batch;
+        }
+        PAIMON_ASSIGN_OR_RAISE_FROM_ARROW(
+            std::shared_ptr<arrow::Array> imported,
+            arrow::ImportArray(batch.first.first.get(), 
batch.first.second.get()));
+        if (!imported || imported->type_id() != arrow::Type::STRUCT) {
+            return Status::Invalid("Real-time score reader requires struct 
batches");
+        }
+        auto data = checked_pointer_cast<arrow::StructArray>(imported);
+        auto offsets = std::dynamic_pointer_cast<arrow::Int64Array>(
+            data->GetFieldByName(SpecialFields::RealtimeOffset().Name()));
+        if (!offsets || offsets->null_count() != 0) {
+            return Status::Invalid("Real-time score reader requires non-null 
offsets");
+        }
+        return IndexScoreBatchUtils::CompleteScores(
+            std::move(batch), data, output_schema_, scores_,
+            [&offsets](const std::string&, const std::map<int64_t, float>& 
scores, int64_t row,
+                       size_t) -> Result<float> {
+                auto found = scores.find(offsets->Value(row));
+                if (found == scores.end()) {
+                    return Status::Invalid(
+                        "Search score is missing for a selected real-time 
offset");
+                }
+                return found->second;
+            },
+            arrow_pool_);
+    }
+
+    std::shared_ptr<Metrics> GetReaderMetrics() const override {
+        return reader_->GetReaderMetrics();
+    }
+
+    void Close() override {
+        reader_->Close();
+    }
+
+ private:
+    std::unique_ptr<BatchReader> reader_;
+    std::shared_ptr<arrow::Schema> output_schema_;
+    OutputScores scores_;
+    std::shared_ptr<arrow::MemoryPool> arrow_pool_;
+};
+
+class RealtimeSourceRead {
+ public:
+    RealtimeSourceRead(const std::shared_ptr<InternalReadContext>& context,
+                       const std::shared_ptr<RealtimeStore>& store,
+                       const std::shared_ptr<RealtimeReadView>& view,
+                       const std::shared_ptr<RealtimeIndexReadSource>& source,
+                       const RealtimeSchemaLayout& layout)
+        : context_(context), store_(store), view_(view), source_(source), 
layout_(layout) {}
+
+    Status Prepare(const std::shared_ptr<Predicate>& predicate) {
+        return Evaluator::Prepare(
+            predicate, [this](const std::shared_ptr<LeafPredicate>& leaf) -> 
Status {
+                PAIMON_ASSIGN_OR_RAISE(
+                    [[maybe_unused]] 
std::vector<std::shared_ptr<RealtimeIndexReader>> readers,
+                    GetReaders(leaf->FieldName()));
+                if (leaf->GetFunction().GetType() == 
Function::Type::FULL_TEXT_MATCH) {
+                    PAIMON_ASSIGN_OR_RAISE(
+                        [[maybe_unused]] std::shared_ptr<RealtimeIndexReader> 
reader,
+                        GetSearchReader(leaf->FieldName(),
+                                        
RealtimeIndexReader::SearchType::FULL_TEXT_MATCH));
+                }
+                return Status::OK();
+            });
+    }
+
+    Status PrepareSearch() {
+        if (context_->GetVectorSearch()) {
+            PAIMON_ASSIGN_OR_RAISE([[maybe_unused]] 
std::shared_ptr<RealtimeIndexReader> reader,
+                                   
GetSearchReader(context_->GetVectorSearch()->field_name,
+                                                   
RealtimeIndexReader::SearchType::VECTOR_SEARCH));
+        }
+        if (context_->GetFullTextSearch()) {
+            PAIMON_ASSIGN_OR_RAISE(
+                [[maybe_unused]] std::shared_ptr<RealtimeIndexReader> reader,
+                GetSearchReader(context_->GetFullTextSearch()->field_name,
+                                
RealtimeIndexReader::SearchType::FULL_TEXT_SEARCH));
+        }
+        return Status::OK();
+    }
+
+    Result<std::unique_ptr<BatchReader>> CreateReader() {
+        PAIMON_ASSIGN_OR_RAISE(RoaringBitmap64 candidates, 
source_->CreateCandidates());
+        Evaluator evaluator(
+            [this](const std::shared_ptr<LeafPredicate>& leaf, const 
RoaringBitmap64& rows) {
+                return EvaluateLeaf(leaf, rows);
+            },
+            [this](const std::shared_ptr<LeafPredicate>& leaf) {
+                return EstimateSelectivity(leaf);
+            });
+        PAIMON_ASSIGN_OR_RAISE(Evaluation evaluated,
+                               evaluator.Evaluate(context_->GetPredicate(), 
candidates));
+        if (evaluated.rows.IsEmpty()) {
+            return std::unique_ptr<BatchReader>();
+        }
+        PAIMON_RETURN_NOT_OK(ApplyRootSearch(&evaluated));
+        if (evaluated.rows.IsEmpty()) {
+            return std::unique_ptr<BatchReader>();
+        }
+
+        using AlignedScores = std::map<std::string, std::vector<float>>;
+        PAIMON_ASSIGN_OR_RAISE(
+            AlignedScores aligned_scores,
+            Evaluator::CreateOutputScores(evaluated, 
context_->GetIndexScoreBindings(),
+                                          context_->GetReadSchema()));
+        OutputScores scores;
+        for (const auto& [field, aligned] : aligned_scores) {
+            auto& output = scores[field];
+            size_t index = 0;
+            for (auto iter = evaluated.rows.Begin(); iter != 
evaluated.rows.End(); ++iter) {
+                output.emplace(*iter, aligned[index++]);
+            }
+        }
+        arrow::FieldVector fields;
+        for (const auto& field : context_->GetReadSchema()->fields()) {
+            if (!SpecialFields::ParseIndexScoreFieldName(field->name())) {
+                fields.push_back(field);
+            }
+        }
+        if (context_->GetReadSchema()->GetFieldIndex(OffsetField()->name()) < 
0) {
+            fields.push_back(OffsetField());
+        }
+        PAIMON_ASSIGN_OR_RAISE(std::unique_ptr<BatchReader> reader,
+                               ReadLogical(arrow::schema(fields), 
/*predicate=*/nullptr,
+                                           
std::make_shared<RoaringBitmap64>(evaluated.rows)));
+        return 
std::unique_ptr<BatchReader>(std::make_unique<RealtimeScoreBatchReader>(
+            std::move(reader), context_->GetReadSchema(), std::move(scores),
+            context_->GetArrowMemoryPool()));

Review Comment:
   Let’s wait until we consistently support `_VALUE_KIND` as a user-input query 
field—seems there may be additional issues in other table modes as well.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to