Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/source/api/global_index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,26 @@ Interface
:members:
:undoc-members:

.. doxygenclass:: paimon::HybridSearchBuilder
:members:
:undoc-members:

.. doxygenclass:: paimon::HybridSearchRanker
:members:
:undoc-members:

.. doxygenclass:: paimon::VectorSearchBuilder
:members:
:undoc-members:

.. doxygenclass:: paimon::VectorScan
:members:
:undoc-members:

.. doxygenclass:: paimon::VectorRead
:members:
:undoc-members:

.. doxygenclass:: paimon::FullTextSearchBuilder
:members:
:undoc-members:
Expand Down
122 changes: 119 additions & 3 deletions docs/source/user_guide/global_index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ satisfy the filter before ranking. It falls back to ``global-index.search-mode``
A raw split always evaluates the filter on its data. All its live, non-null text contributes to
the temporary index's scores, even when the filter excludes a row from the results.

Only single-field indexes that do not support full-text search evaluate a filter. A filter with a
Only single-field scalar indexes evaluate a filter. A filter with a
``PredicateBuilder::FullTextMatch`` predicate fails with ``NotImplemented``.

Pinning the Data Read
Expand Down Expand Up @@ -528,5 +528,121 @@ combined with the ``pre_filter`` of the ``VectorSearch``. In Data Evolution tabl
deletion vectors of the data files the index covers are read. As for full-text search, pass one
snapshot id to both the index scan and the data scan.

A search across multiple index shards returns up to ``limit`` rows from each shard, and the merged
result is not truncated to ``limit``.
A low-level ``GlobalIndexReader`` returns up to ``limit`` rows from each shard. Its merged
result can therefore contain more than ``limit`` rows.

For table-level top-k on a Data Evolution table, use ``VectorSearchBuilder`` from
``paimon/table/source/vector_search_builder.h``. Set the column and vector with
``SetQuery("embedding", vector)``, then call ``SetLimit(k)`` and ``ExecuteLocal()``.
Higher scores indicate more similar vectors. For Lumina, the table-level score is
``1 / (1 + squared_distance)`` for L2, cosine similarity for cosine, and the dot
product for inner product. Pass the returned row ids and scores to
``ScanContextBuilder::SetGlobalIndexResult()`` to read the matching rows.
To reuse a snapshot and its filters, create a plan with ``VectorScan::CreatePlan()``
and pass it to ``VectorRead::Read()`` in the same process. Each read can use a different
query vector, limit, candidate multiplier and ``global-index.filter.refine-from-data`` setting.
Creating another plan resolves the snapshot selector again. An existing plan retains the
snapshot metadata and can still be read after the snapshot file expires, provided its index
and data files remain available.
Vector queries across multiple shards use the executor supplied by ``WithExecutor()`` or an
executor sized by ``global-index.thread-num``. A reused plan keeps the executor it was created
with. When the search must verify candidates against table data, it does so after each group of
shard queries completes.
Scalar index results narrow the shards before deletion vectors are read. The search reads
deletion vectors for data files overlapping those shards and opens only shards that can
still contain matching live rows.
If a searched shard declines the query, the other shards can still contribute hits.
An error while opening or querying a searched shard fails the search.

Hybrid Search
-------------

``HybridSearchBuilder`` combines vector and full-text routes on a data-evolution table.
Each route ranks live rows in the same snapshot, applies the partition and row filters,
and contributes up to its own limit of candidates. A route's weight defaults to 1 and
must be finite and positive. An empty route contributes no scores. The final limit controls
how many distinct rows survive fusion. Vector routes support the ``fast`` index search mode.
Full-text routes use the builder's full-text and scalar options as described in `Search Modes`_
and `Row Filters`_.
Set ``PAIMON_ENABLE_LUMINA=ON`` when building with Lumina. Enable the backend that matches
the table's full-text indexes with ``PAIMON_ENABLE_FULL_TEXT=ON`` for ``full-text`` or
``PAIMON_ENABLE_LUCENE=ON`` for ``lucene-fts``.

Each call to ``WithPartitionFilter()`` on a vector or hybrid builder intersects the current
partition selection with the union of the supplied specs. An empty list adds no restriction.
Each call to ``WithFilter()`` adds a conjunct to the search filter. If a conjunct uses
only partition keys, the search intersects it with the selection from ``WithPartitionFilter()``.

Builders created by a ``Table`` inherit its branch. To search a different branch, load the
table on that branch or construct the builder from its path and set the ``branch`` option.
Use ``SetOptions()`` to select a snapshot, tag or timestamp. The options passed to
``AddVectorRoute()`` or ``VectorSearchBuilder::SetQuery()`` tune the backend
and can override the vector and scalar search modes, the candidate multiplier and filter
refinement for that query. Full-text routes require an empty route options map.

In ``fast`` mode, if scalar indexes can evaluate a vector route's filter, only rows
identified by those indexes are eligible. Scalar index candidates that require verification
are excluded with a warning by default. Set ``global-index.filter.refine-from-data=true``
to check them against table data.
When no scalar index can evaluate the filter, a vector route fetches up to
``limit × vector-index.post-filter.candidates-factor`` candidates from each shard and
checks them against the pinned data. The factor defaults to 10 and can be set per vector
route. A selective predicate may leave fewer than ``limit`` matches. Full-text routes
apply the rules in `Row Filters`_.

To read the matching rows while the table is changing, choose a snapshot before searching.
Set ``scan.mode=from-snapshot`` and the same ``scan.snapshot-id`` on both the search and
the data scan. A ``scan.tag-name`` also works if the tag points to the same snapshot for
both operations. The search resolves columns using the selected snapshot's field IDs.
Pass the fused result to ``ScanContextBuilder::SetGlobalIndexResult()`` to read those rows
and their ``_INDEX_SCORE``.

.. code-block:: cpp

#include "paimon/catalog/table.h"
#include "paimon/defs.h"
#include "paimon/read_context.h"
#include "paimon/reader/batch_reader.h"
#include "paimon/scan_context.h"
#include "paimon/table/source/hybrid_search_builder.h"
#include "paimon/table/source/table_read.h"
#include "paimon/table/source/table_scan.h"

const std::map<std::string, std::string> options = {
{paimon::Options::SCAN_MODE, "from-snapshot"},
{paimon::Options::SCAN_SNAPSHOT_ID, std::to_string(snapshot_id)},
};
PAIMON_ASSIGN_OR_RAISE(std::unique_ptr<paimon::HybridSearchBuilder> search,
table->NewHybridSearchBuilder());
search->SetOptions(options)
.AddVectorRoute("embedding", {0.1f, 0.9f}, 20)
.AddFullTextRoute("content", R"({"match":{"query":"paimon lake"}})", 30, 2.0f)
.WithWeightedScoreRanker()
.SetLimit(10);
PAIMON_ASSIGN_OR_RAISE(std::shared_ptr<paimon::ScoredGlobalIndexResult> hits,
search->ExecuteLocal());
paimon::ScanContextBuilder scan_builder(table->GetRootPath());
scan_builder.SetOptions(options).SetGlobalIndexResult(hits);
PAIMON_ASSIGN_OR_RAISE(std::unique_ptr<paimon::ScanContext> context, scan_builder.Finish());
PAIMON_ASSIGN_OR_RAISE(std::unique_ptr<paimon::TableScan> scan,
table->NewScan(std::move(context)));
PAIMON_ASSIGN_OR_RAISE(std::shared_ptr<paimon::Plan> plan, scan->CreatePlan());

paimon::ReadContextBuilder read_builder(table->GetRootPath());
read_builder.SetReadFieldNames({"content", "_INDEX_SCORE"});
PAIMON_ASSIGN_OR_RAISE(std::unique_ptr<paimon::ReadContext> read_context, read_builder.Finish());
PAIMON_ASSIGN_OR_RAISE(std::unique_ptr<paimon::TableRead> read,
table->NewRead(std::move(read_context)));
PAIMON_ASSIGN_OR_RAISE(std::unique_ptr<paimon::BatchReader> reader,
read->CreateReader(plan->Splits()));

The default ranker, ``rrf``, sums ``weight / (60 + rank)``. ``mrr`` sums
``weight / rank``. Both count ranks from one and order tied route scores by ascending
row id. For a route with finite scores, ``weighted_score`` rescales them to [0, 1] and
multiplies them by the route weight. If all scores are equal or any score is NaN, every
hit receives the route weight. The ranker sums these contributions by row id. Final ties
favor the smaller row id. The result iterates in ascending row-id order.

Source-backed primary-key indexes use file-local physical positions and currently return
``NotImplemented`` for table-level hybrid search. Format tables also return ``NotImplemented``
when accessed through the catalog or a path containing their schema.
7 changes: 7 additions & 0 deletions include/paimon/catalog/table.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ namespace paimon {
class CommitContext;
class FileStoreCommit;
class FileStoreWrite;
class HybridSearchBuilder;
class VectorSearchBuilder;
class ReadContext;
class ScanContext;
class TableRead;
Expand Down Expand Up @@ -99,6 +101,11 @@ class PAIMON_EXPORT Table {
virtual Result<std::unique_ptr<FileStoreCommit>> NewCommit(
std::unique_ptr<CommitContext> context) const = 0;

/// Creates a hybrid search bound to the table's branch. Search requires data evolution.
virtual Result<std::unique_ptr<HybridSearchBuilder>> NewHybridSearchBuilder() const;
/// Creates a vector search bound to the table's branch. Search requires data evolution.
virtual Result<std::unique_ptr<VectorSearchBuilder>> NewVectorSearchBuilder() const;

protected:
/// @param file_system File system the table's data is accessed through.
/// @param root_path Root path of the table in the file system.
Expand Down
16 changes: 10 additions & 6 deletions include/paimon/defs.h
Original file line number Diff line number Diff line change
Expand Up @@ -645,20 +645,24 @@ struct PAIMON_EXPORT Options {
/// search the gaps if a selected partition has a full-text index for the column.
/// Defaults to "global-index.search-mode", then "fast".
static const char FULL_TEXT_INDEX_SEARCH_MODE[];
/// "scalar-index.search-mode" - Controls row filtering on full-text index shards. "fast"
/// uses scalar index candidates. "full" and "detail" also read the filter columns for gaps
/// in scalar index coverage. Defaults to "global-index.search-mode", then "fast".
/// "scalar-index.search-mode" - Controls row filtering on search shards. "fast" uses scalar
/// index candidates. For full-text search, "full" and "detail" also read the filter columns
/// for gaps in scalar index coverage. Vector search supports "fast".
/// Defaults to "global-index.search-mode", then "fast".
static const char SCALAR_INDEX_SEARCH_MODE[];
/// "vector-index.search-mode" - Reserved for table-level vector search. Accepts "fast",
/// "full" or "detail". Defaults to "global-index.search-mode", then "fast".
/// "vector-index.search-mode" - Vector search coverage. Defaults to "global-index.search-mode"
/// or "fast". Table-level vector searches currently support "fast".
static const char VECTOR_INDEX_SEARCH_MODE[];
/// "vector-index.post-filter.candidates-factor" - Positive multiplier of the vector route's
/// top-k when candidate rows must be checked against table data. Defaults to 10.
static const char VECTOR_INDEX_POST_FILTER_CANDIDATES_FACTOR[];
/// "global-index.filter.refine-from-data" - Whether a vector, hybrid or full-text search may
/// read the filter columns of candidate rows to verify a row filter that the scalar global
/// index can only answer with a superset, such as contains, ends-with or like on a BTree index
/// or a conjunction with a member no index can evaluate. When false, such candidates are
/// excluded from the search, which never returns a non-matching row but may return fewer than
/// the requested top-k. When true, the read runs on the caller and may cover every candidate
/// row. Default value is "false". Paimon C++ reads it only in full-text search so far.
/// row. Default value is "false".
static const char GLOBAL_INDEX_FILTER_REFINE_FROM_DATA[];
/// "pk-btree.index.columns" - Comma-separated columns indexed by primary-key BTree indexes.
/// No default value.
Expand Down
6 changes: 6 additions & 0 deletions include/paimon/global_index/global_indexer.h
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ class PAIMON_EXPORT GlobalIndexer {
virtual bool SupportsFullTextSearch() const {
return false;
}

/// Whether the primary field supports table-level vector search. Its readers must honor
/// `VectorSearch::return_similarity_score` so the caller can rank hits across shards.
virtual bool SupportsVectorSearch() const {
return false;
}
};

} // namespace paimon
54 changes: 54 additions & 0 deletions include/paimon/global_index/hybrid_search_ranker.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* 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 <cstdint>
#include <memory>
#include <string>
#include <vector>

#include "paimon/global_index/global_index_result.h"
#include "paimon/visibility.h"

namespace paimon {
/// Fuses scored results in the same global row-id space.
class PAIMON_EXPORT HybridSearchRanker {
public:
HybridSearchRanker() = delete;
~HybridSearchRanker() = delete;

enum class Type { RRF, WEIGHTED_SCORE, MRR };

struct WeightedResult {
std::shared_ptr<ScoredGlobalIndexResult> result;
float weight = 1.0f;
};

/// Parses rrf (the default for a blank name), weighted_score or mrr, ignoring case and
/// surrounding whitespace.
static Result<Type> Parse(const std::string& name);

/// Keeps the top limit rows by fused score, breaking ties by ascending row id. RRF sums
/// weight / (60 + rank), MRR sums weight / rank, with ranks starting at one. Weighted
/// score sums each route's min-max normalized scores times its weight. All hits of a
/// constant-score route receive its full weight. Result iteration is in row-id order.
static Result<std::shared_ptr<ScoredGlobalIndexResult>> Rank(
Type ranker, const std::vector<WeightedResult>& routes, int32_t limit);
};
} // namespace paimon
4 changes: 4 additions & 0 deletions include/paimon/predicate/vector_search.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,5 +101,9 @@ struct PAIMON_EXPORT VectorSearch {
/// If null, the search uses the reader's pool. Must support concurrent allocations when
/// the search runs in parallel or the pool is shared by concurrent queries.
std::shared_ptr<MemoryPool> pool;

/// Requests higher-is-better similarity scores from global index readers for table-level
/// ranking. Low-level callers receive the backend's native scores by default.
bool return_similarity_score = false;
};
} // namespace paimon
83 changes: 83 additions & 0 deletions include/paimon/table/source/hybrid_search_builder.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* 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 <cstdint>
#include <map>
#include <memory>
#include <string>
#include <vector>

#include "paimon/global_index/global_index_result.h"
#include "paimon/predicate/predicate.h"
#include "paimon/type_fwd.h"
#include "paimon/visibility.h"

namespace paimon {
class Executor;
class FileStoreTable;

/// Combines vector and full-text searches on one snapshot of a data-evolution table.
/// Each route has its own candidate limit.
class PAIMON_EXPORT HybridSearchBuilder {
public:
explicit HybridSearchBuilder(const std::string& table_path);
~HybridSearchBuilder();

/// Intersects the current partition selection with the union of the given specs on each call.
/// An empty list adds no restriction.
HybridSearchBuilder& WithPartitionFilter(
const std::vector<std::map<std::string, std::string>>& partitions);
/// Adds a conjunct to the row filter applied by every route.
HybridSearchBuilder& WithFilter(const std::shared_ptr<Predicate>& predicate);
/// Adds a vector route with a finite positive weight and optional backend query options.
HybridSearchBuilder& AddVectorRoute(const std::string& column, const std::vector<float>& vector,
int32_t limit, float weight = 1.0f,
const std::map<std::string, std::string>& options = {});
/// Passes the query unchanged to the full-text index. The weight must be finite and positive,
/// and the route options must be empty.
HybridSearchBuilder& AddFullTextRoute(const std::string& field, const std::string& query,
int32_t limit, float weight = 1.0f,
const std::map<std::string, std::string>& options = {});
/// Sets the positive limit on the fused results.
HybridSearchBuilder& SetLimit(int32_t limit);
/// Selects rrf (default), weighted_score or mrr.
HybridSearchBuilder& WithRanker(const std::string& ranker);
HybridSearchBuilder& WithRrfRanker();
HybridSearchBuilder& WithWeightedScoreRanker();

/// Replaces table option overrides, including the snapshot, tag or timestamp to search.
/// A builder created by a Table uses that table's branch.
HybridSearchBuilder& SetOptions(const std::map<std::string, std::string>& options);
HybridSearchBuilder& WithFileSystem(const std::shared_ptr<FileSystem>& file_system);
/// The pool must support concurrent allocations when searching multiple shards.
HybridSearchBuilder& WithMemoryPool(const std::shared_ptr<MemoryPool>& pool);
/// Sets the executor for shard searches and data reads.
HybridSearchBuilder& WithExecutor(const std::shared_ptr<Executor>& executor);

/// Returns the fused scores in ascending row-id order, suitable for SetGlobalIndexResult().
Result<std::shared_ptr<ScoredGlobalIndexResult>> ExecuteLocal() const;

private:
friend class FileStoreTable;
class Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace paimon
Loading
Loading