This is an automated email from the ASF dual-hosted git repository.
JingsongLi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/paimon-rust.git
The following commit(s) were added to refs/heads/main by this push:
new f56057a7 [core] Support range-sharded MultiVector MaxSim search (#1492)
f56057a7 is described below
commit f56057a7bfd93fbafbe696ba31adb5c168800c19
Author: Jingsong Lee <[email protected]>
AuthorDate: Sun Nov 22 14:33:46 2026 +0800
[core] Support range-sharded MultiVector MaxSim search (#1492)
---
.../python/python/pypaimon_rust/datafusion.pyi | 3 +
bindings/python/src/vector_search.rs | 9 +
bindings/python/tests/test_vector_search.py | 33 ++
.../datafusion/src/procedures/compat.rs | 25 +-
.../integrations/datafusion/src/vector_search.rs | 58 ++-
.../integrations/datafusion/tests/read_tables.rs | 41 ++
crates/paimon/src/table/de_vector_read.rs | 325 +++++++++++---
.../src/table/de_vector_read/multi_vector.rs | 128 ++++++
crates/paimon/src/table/de_vector_read/tests.rs | 14 +-
.../paimon/src/table/global_index_build_builder.rs | 1 +
crates/paimon/src/table/global_index_options.rs | 40 +-
crates/paimon/src/table/index_build/vector.rs | 15 +-
.../src/table/index_build/vector_extraction.rs | 67 ++-
crates/paimon/src/table/pk_index_options.rs | 2 +-
crates/paimon/src/table/search_task.rs | 7 +-
crates/paimon/src/table/vector_read.rs | 50 +++
crates/paimon/src/table/vector_search_builder.rs | 58 ++-
.../paimon/src/table/vindex_index_build_builder.rs | 14 +
.../multi_vector_tests.rs | 497 +++++++++++++++++++++
.../src/table/vindex_index_build_builder/tests.rs | 3 +
.../table/vindex_index_build_builder/validation.rs | 6 +-
.../src/table/vindex_index_build_builder/writer.rs | 5 +-
crates/paimon/src/vindex/mod.rs | 29 +-
crates/paimon/src/vindex/multi_vector.rs | 174 ++++++++
crates/paimon/src/vindex/reader.rs | 336 +++++++++++++-
docs/src/sql.md | 25 +-
26 files changed, 1814 insertions(+), 151 deletions(-)
diff --git a/bindings/python/python/pypaimon_rust/datafusion.pyi
b/bindings/python/python/pypaimon_rust/datafusion.pyi
index e2348529..b12f930f 100644
--- a/bindings/python/python/pypaimon_rust/datafusion.pyi
+++ b/bindings/python/python/pypaimon_rust/datafusion.pyi
@@ -1181,6 +1181,9 @@ class VectorSearchBuilder:
def with_vector_column(self, name: str) -> "VectorSearchBuilder": ...
def with_limit(self, limit: int) -> "VectorSearchBuilder": ...
def with_query_vector(self, vector: Sequence[float]) ->
"VectorSearchBuilder": ...
+ def with_multi_vector(
+ self, vectors: Sequence[Sequence[float]]
+ ) -> "VectorSearchBuilder": ...
def with_option(self, key: str, value: str) -> "VectorSearchBuilder": ...
def with_options(self, options: Dict[str, str]) -> "VectorSearchBuilder":
...
def with_filter(self, predicate: Dict[str, Any]) -> "VectorSearchBuilder":
...
diff --git a/bindings/python/src/vector_search.rs
b/bindings/python/src/vector_search.rs
index 45394422..cb3ec670 100644
--- a/bindings/python/src/vector_search.rs
+++ b/bindings/python/src/vector_search.rs
@@ -101,6 +101,15 @@ impl PyVectorSearchBuilder {
slf.inner.with_query_vector(vector);
slf
}
+ /// Rank each row's embedding list with cosine MaxSim for a query matrix.
+ fn with_multi_vector(
+ mut slf: PyRefMut<'_, Self>,
+ vectors: Vec<Vec<f32>>,
+ ) -> PyRefMut<'_, Self> {
+ slf.inner.with_multi_vector(vectors);
+ slf
+ }
+
fn with_option(mut slf: PyRefMut<'_, Self>, key: String, value: String) ->
PyRefMut<'_, Self> {
slf.inner.with_options(HashMap::from([(key, value)]));
slf
diff --git a/bindings/python/tests/test_vector_search.py
b/bindings/python/tests/test_vector_search.py
index a139c497..3f120c91 100644
--- a/bindings/python/tests/test_vector_search.py
+++ b/bindings/python/tests/test_vector_search.py
@@ -286,6 +286,39 @@ def test_single_vector_keyword_matches_stub(table):
assert builder.execute().row_ids() ==
_single(table).with_limit(1).execute().row_ids()
+def test_multi_vector_query_reranks_complete_embedding_lists(tmp_path):
+ ctx = SQLContext()
+ ctx.register_catalog('paimon', {'warehouse': str(tmp_path)})
+ ctx.sql('CREATE SCHEMA paimon.db')
+ ctx.sql("CREATE TABLE paimon.db.chunks (id INT, embeddings FLOAT[][]) "
+ "WITH ('bucket'='-1', 'data-evolution.enabled'='true', "
+ "'row-tracking.enabled'='true', 'global-index.enabled'='true', "
+ "'vector-index.search-mode'='fast')")
+ table = PaimonCatalog({'warehouse': str(tmp_path)}).get_table('db.chunks')
+ write = table.new_batch_write_builder()
+ writer = write.new_write()
+ commit = write.new_commit()
+ try:
+ writer.write_arrow(pa.record_batch([
+ pa.array([10, 20, 30], type=pa.int32()),
+ pa.array([[[1, 0], [1, 0]], [[0, 1]], [[1, 1]]],
+ type=pa.list_(pa.list_(pa.float32()))),
+ ], names=['id', 'embeddings']))
+ commit.commit(writer.prepare_commit())
+ finally:
+ writer.close()
+ commit.close()
+
+ assert
(table.new_global_index_build_builder().with_index_column('embeddings')
+ .with_index_type('ivf-flat').with_options({
+ 'ivf-flat.dimension': '2', 'ivf-flat.nlist': '1'}).execute())
== 1
+ result =
(table.new_vector_search_builder().with_vector_column('embeddings')
+ .with_multi_vector(vectors=[(1, 0), (0,
1)]).with_limit(1).execute())
+ assert list(result.row_ids().values()) == pytest.approx([2 ** 0.5])
+ rows =
pa.Table.from_batches(result.new_read_builder().with_projection(['id']).read())
+ assert rows.column('id').to_pylist() == [30]
+
+
@pytest.mark.parametrize('batch', [False, True])
def test_raw_options_survive_scan_read_and_use_raw_metric_options(table,
batch):
import pickle
diff --git a/crates/integrations/datafusion/src/procedures/compat.rs
b/crates/integrations/datafusion/src/procedures/compat.rs
index d4569fff..b5fd1480 100644
--- a/crates/integrations/datafusion/src/procedures/compat.rs
+++ b/crates/integrations/datafusion/src/procedures/compat.rs
@@ -44,7 +44,7 @@ use super::{
};
use crate::full_text_search::FullTextSearchFunction;
use crate::sql_context::ok_result;
-use crate::vector_search::VectorSearchFunction;
+use crate::vector_search::{VectorQuery, VectorSearchFunction};
use crate::SQLContext;
async fn validate_write_target(
@@ -491,20 +491,31 @@ fn vector_json(query: &str) -> DFResult<String> {
let query = query.trim();
let invalid = || {
DataFusionError::Plan(
- "query_vector must be a non-empty JSON array or comma-separated list
of finite FLOAT values"
+ "query_vector must be a non-empty JSON vector, rectangular JSON
matrix, or comma-separated list of finite FLOAT values"
.into(),
)
};
- let values: Vec<f32> = if query.starts_with('[') {
- serde_json::from_str(query).map_err(|_| invalid())?
+ let values = if query.starts_with('[') {
+ VectorQuery::parse(query).map_err(|_| invalid())?
} else {
- query
+ let values = query
.split(',')
.map(|value| value.trim().parse::<f32>())
.collect::<Result<_, _>>()
- .map_err(|_| invalid())?
+ .map_err(|_| invalid())?;
+ VectorQuery::Single(values)
};
- if values.is_empty() || values.iter().any(|value| !value.is_finite()) {
+ let vectors = match &values {
+ VectorQuery::Single(vector) => std::slice::from_ref(vector),
+ VectorQuery::Matrix(vectors) => vectors.as_slice(),
+ };
+ let Some(first) = vectors.first().filter(|vector| !vector.is_empty()) else
{
+ return Err(invalid());
+ };
+ if vectors
+ .iter()
+ .any(|vector| vector.len() != first.len() || vector.iter().any(|value|
!value.is_finite()))
+ {
return Err(invalid());
}
serde_json::to_string(&values).map_err(|_| invalid())
diff --git a/crates/integrations/datafusion/src/vector_search.rs
b/crates/integrations/datafusion/src/vector_search.rs
index 626885cb..c291dfc1 100644
--- a/crates/integrations/datafusion/src/vector_search.rs
+++ b/crates/integrations/datafusion/src/vector_search.rs
@@ -118,6 +118,23 @@ impl VectorSearchFunction {
}
}
+#[derive(Debug, Clone, serde::Serialize)]
+#[serde(untagged)]
+pub(crate) enum VectorQuery {
+ Single(Vec<f32>),
+ Matrix(Vec<Vec<f32>>),
+}
+
+impl VectorQuery {
+ pub(crate) fn parse(json: &str) -> Result<Self, serde_json::Error> {
+ // Parse directly into floats. Untagged enum buffering turns decimal
+ // numbers into a private map with serde_json's arbitrary_precision.
+ serde_json::from_str::<Vec<f32>>(json)
+ .map(Self::Single)
+ .or_else(|_|
serde_json::from_str::<Vec<Vec<f32>>>(json).map(Self::Matrix))
+ }
+}
+
impl TableFunctionImpl for VectorSearchFunction {
fn call(&self, args: &[Expr]) -> DFResult<Arc<dyn TableProvider>> {
if args.len() != 4 {
@@ -172,14 +189,14 @@ impl TableFunctionImpl for VectorSearchFunction {
Err(err) => return Err(err),
};
- let query_vector: Vec<f32> =
serde_json::from_str(&query_vector_json).map_err(|e| {
+ let query_vector = VectorQuery::parse(&query_vector_json).map_err(|e| {
DataFusionError::Plan(format!(
- "vector_search: query_vector_json must be a JSON array of
floats, got '{}': {}",
+ "vector_search: query_vector_json must be a JSON vector or
matrix of floats, got '{}': {}",
query_vector_json, e
))
})?;
- if query_vector.is_empty() {
+ if matches!(&query_vector, VectorQuery::Single(vector) if
vector.is_empty()) {
return Err(DataFusionError::Plan(
"vector_search: query vector cannot be empty".to_string(),
));
@@ -247,7 +264,7 @@ impl TableProvider for LateralVectorSearchTableProvider {
struct VectorSearchTableProvider {
inner: PaimonTableProvider,
column_name: String,
- query_vector: Vec<f32>,
+ query_vector: VectorQuery,
limit: usize,
}
@@ -332,7 +349,7 @@ impl TableProvider for VectorSearchTableProvider {
struct VectorSearchExec {
table: Table,
column_name: String,
- query_vector: Vec<f32>,
+ query_vector: VectorQuery,
/// The table function's own top-k — drives the ANN search width; never
reduced.
search_limit: usize,
/// The outer DataFusion `LIMIT`, applied by truncating the ranked result.
@@ -347,7 +364,7 @@ impl VectorSearchExec {
fn new(
table: Table,
column_name: String,
- query_vector: Vec<f32>,
+ query_vector: VectorQuery,
search_limit: usize,
output_limit: Option<usize>,
projection: Option<Vec<usize>>,
@@ -387,17 +404,21 @@ impl VectorSearchExec {
// recall is unchanged (data-evolution / global-index path; PK-vector
tables are
// unsupported here, as before).
let mut search_result = await_with_runtime(async {
- let mut builder = search_table.new_batch_vector_search_builder();
+ let mut builder = search_table.new_vector_search_builder();
builder
.with_vector_column(&self.column_name)
- .with_query_vectors(vec![self.query_vector.clone()])
.with_limit(self.search_limit);
+ match &self.query_vector {
+ VectorQuery::Single(vector) =>
builder.with_query_vector(vector.clone()),
+ VectorQuery::Matrix(vectors) =>
builder.with_multi_vector(vectors.clone()),
+ };
if let Some(filter) = &self.filter {
builder.with_filter(filter.clone());
}
- let mut results =
builder.execute().await.map_err(to_datafusion_error)?;
- results
- .remove(0)
+ builder
+ .execute()
+ .await
+ .map_err(to_datafusion_error)?
.into_row_ids()
.map_err(to_datafusion_error)
})
@@ -647,6 +668,19 @@ mod tests {
use super::*;
use crate::SQLContext;
+ #[test]
+ fn vector_query_accepts_decimal_vectors_and_matrices() {
+ assert!(matches!(
+ VectorQuery::parse("[1.0, -2.5]").unwrap(),
+ VectorQuery::Single(vector) if vector == [1.0, -2.5]
+ ));
+ assert!(matches!(
+ VectorQuery::parse("[[1.0, -2.5], [0.0, 3e-1]]").unwrap(),
+ VectorQuery::Matrix(vectors) if vectors == [vec![1.0, -2.5],
vec![0.0, 0.3]]
+ ));
+ assert!(VectorQuery::parse("[1.0, [2.5]]").is_err());
+ }
+
#[test]
fn unfiltered_snapshot_io_uses_runtime_bridge_when_polled_without_tokio() {
let temp_dir = tempfile::tempdir().unwrap();
@@ -668,7 +702,7 @@ mod tests {
let exec = VectorSearchExec::new(
table,
"embedding".into(),
- vec![1.0],
+ VectorQuery::Single(vec![1.0]),
1,
None,
None,
diff --git a/crates/integrations/datafusion/tests/read_tables.rs
b/crates/integrations/datafusion/tests/read_tables.rs
index 2e1f04ad..9eb32b37 100644
--- a/crates/integrations/datafusion/tests/read_tables.rs
+++ b/crates/integrations/datafusion/tests/read_tables.rs
@@ -1965,6 +1965,47 @@ mod vector_search_tests {
assert!(batches.iter().all(|batch| batch.num_columns() == 1));
}
+ #[tokio::test]
+ async fn test_multi_vector_call_matches_table_function() {
+ let (ctx, _catalog, _tmp) = create_empty_vector_search_context().await;
+ for sql in [
+ "CREATE TABLE paimon.default.multi_vector_sql (id INT, chunks
FLOAT[][]) \
+ WITH ('bucket'='-1', 'row-tracking.enabled'='true', \
+ 'data-evolution.enabled'='true', 'global-index.enabled'='true', \
+ 'vector-index.search-mode'='fast')",
+ "INSERT INTO paimon.default.multi_vector_sql (id, chunks) VALUES \
+ (0, [[1.0, 0.0]]), (1, [[0.0, 1.0]]), (2, [[1.0, 1.0]])",
+ "CALL sys.create_global_index(table => 'default.multi_vector_sql',
\
+ index_column => 'chunks', index_type => 'ivf-flat', \
+ options => 'ivf-flat.dimension=2,ivf-flat.nlist=1')",
+ "SET 'paimon.ivf.nprobe' = '1'",
+ "SET 'paimon.diskann.l_search' = '100'",
+ ] {
+ ctx.sql(sql)
+ .await
+ .unwrap_or_else(|error| panic!("{sql}: {error}"))
+ .collect()
+ .await
+ .unwrap_or_else(|error| panic!("{sql}: {error}"));
+ }
+
+ for sql in [
+ "SELECT id FROM vector_search('paimon.default.multi_vector_sql',
'chunks', \
+ '[[1.0, 0.0], [0.0, 1.0]]', 1)",
+ "CALL paimon.sys.vector_search('default.multi_vector_sql',
'chunks', \
+ '[[1.0, 0.0], [0.0, 1.0]]', 1, 'id')",
+ ] {
+ let batches = ctx.sql(sql).await.unwrap().collect().await.unwrap();
+ assert_eq!(extract_ids_in_order(&batches), [2], "{sql}");
+ }
+ super::common::assert_sql_error(
+ &ctx,
+ "CALL sys.vector_search('default.multi_vector_sql', 'chunks',
'[[1.0], [0.0, 1.0]]', 1)",
+ "rectangular JSON matrix",
+ )
+ .await;
+ }
+
/// `vector_search` must return rows in relevance order, not file order.
Querying
/// id 2's vector ranks `[2, 5, 1]` by L2 distance, which differs from the
/// ascending-id file order `[1, 2, 5]` the pre-fix scan produced.
diff --git a/crates/paimon/src/table/de_vector_read.rs
b/crates/paimon/src/table/de_vector_read.rs
index 4e3b2559..e5281d93 100644
--- a/crates/paimon/src/table/de_vector_read.rs
+++ b/crates/paimon/src/table/de_vector_read.rs
@@ -69,11 +69,14 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
mod centroid;
+mod multi_vector;
mod post_filter;
+use multi_vector::{ListScorer, ListScoring};
/// Owns the queries and executes the snapshot-scoped plan from `DeVectorScan`.
pub(super) struct DeVectorRead {
vector_searches: Vec<VectorSearch>,
+ max_sim: bool,
}
impl DeVectorRead {
@@ -102,7 +105,15 @@ impl DeVectorRead {
.map(|search| search.with_options(options.clone()))
})
.collect::<crate::Result<_>>()?;
- Ok(Self { vector_searches })
+ Ok(Self {
+ vector_searches,
+ max_sim: false,
+ })
+ }
+
+ pub(super) fn with_max_sim(mut self) -> Self {
+ self.max_sim = true;
+ self
}
/// Validate a result read, including projections over an empty result.
@@ -134,7 +145,9 @@ impl DeVectorRead {
DataType::Array(t) => matches!(t.element_type(),
DataType::Float(_)),
_ => false,
};
- if !is_float_vector {
+ if !is_float_vector
+ &&
crate::vindex::multi_vector::embedding_type(field.data_type()).is_none()
+ {
return Err(crate::Error::DataInvalid {
message: format!(
"vector search column '{vector_column}' must be a FLOAT
vector column \
@@ -241,7 +254,14 @@ impl DeVectorRead {
};
let evaluate_start = (timing_enabled &&
!skip_search).then(Instant::now);
let results = if skip_search {
- vec![ScoredRowIds::empty(); self.vector_searches.len()]
+ vec![
+ ScoredRowIds::empty();
+ if self.max_sim {
+ 1
+ } else {
+ self.vector_searches.len()
+ }
+ ]
} else {
let mut vector_searches =
Cow::Borrowed(self.vector_searches.as_slice());
if let Some(include_row_ids) = include_row_ids {
@@ -263,6 +283,7 @@ impl DeVectorRead {
&vector_searches,
executor,
source_splits.as_deref(),
+ self.max_sim,
)
.await?
};
@@ -318,6 +339,23 @@ async fn execute_vector_file_work(
"Unsupported vector task index",
));
}
+ let list_row_count = evaluation
+ .schema_fields
+ .iter()
+ .find(|field| field.id() == global_meta.index_field_id)
+ .and_then(|field|
crate::vindex::multi_vector::embedding_type(field.data_type()))
+ .map(|_| {
+ global_meta
+ .row_range_end
+ .checked_sub(global_meta.row_range_start)
+ .and_then(|count| count.checked_add(1))
+ .filter(|&count| count > 0 && global_meta.row_range_start >= 0)
+ .map(|count| count as u64)
+ .ok_or_else(|| {
+ crate::vindex::multi_vector::invalid("Invalid MultiVector
source row range")
+ })
+ })
+ .transpose()?;
let table_path = evaluation.table_path.trim_end_matches('/');
let path = IndexFileLocation::Global { table_path }.resolve(
&work.entry.index_file.file_name,
@@ -440,6 +478,7 @@ async fn execute_vector_file_work(
file_name.clone(),
VectorIndexSearchContext {
parallelism: batch_index_parallelism,
+ list_row_count,
metrics: metric_check,
post_filter,
},
@@ -468,6 +507,7 @@ async fn execute_vector_file_work(
file_name.clone(),
VectorIndexSearchContext {
parallelism: batch_index_parallelism,
+ list_row_count,
metrics: metric_check,
post_filter,
},
@@ -562,7 +602,8 @@ async fn execute_vindex_searches<S: SeekRead + 'static, G:
Send + 'static>(
};
execute_global_index_with_guard(panic_context, guard, move || {
let mut reader = VindexVectorGlobalIndexReader::new(io_meta, options)
- .with_batch_index_parallelism(context.parallelism);
+ .with_batch_index_parallelism(context.parallelism)
+ .with_list_row_count(context.list_row_count);
reader
.visit_batch_vector_search_validated(
&vector_searches,
@@ -594,7 +635,8 @@ async fn execute_post_filter_vindex_searches<S: SeekRead +
'static, G: Send + 's
post_filter::batch_size(vector_searches.iter().map(|q|
q.limit).max().unwrap_or(1));
let mut queries = vector_searches.into_iter().zip(filter.targets);
let mut reader = VindexVectorGlobalIndexReader::new(io_meta, options)
- .with_batch_index_parallelism(context.parallelism);
+ .with_batch_index_parallelism(context.parallelism)
+ .with_list_row_count(context.list_row_count);
let mut source = Some(source);
let mut first_guard = Some(guard);
let mut results = Vec::new();
@@ -713,6 +755,7 @@ impl VectorMetricCheck {
struct VectorIndexSearchContext {
parallelism: usize,
+ list_row_count: Option<u64>,
metrics: VectorMetricCheck,
post_filter: Option<VectorIndexPostFilter>,
}
@@ -863,6 +906,7 @@ async fn evaluate_batch_vector_search(
vector_searches,
None,
None,
+ false,
)
.await
}
@@ -873,6 +917,7 @@ async fn evaluate_batch_vector_search_with_executor(
vector_searches: &[VectorSearch],
executor: Option<&dyn SearchTaskExecutor>,
sources: Option<&[crate::table::SearchScanSplit]>,
+ max_sim: bool,
) -> crate::Result<Vec<ScoredRowIds>> {
let timing_enabled = vector_search_timing_enabled();
let total_start = timing_enabled.then(Instant::now);
@@ -911,10 +956,22 @@ async fn evaluate_batch_vector_search_with_executor(
let effective_core = CoreOptions::new(&effective_options);
let search_mode = effective_core.vector_index_search_mode()?;
- let field_id = match find_field_id_by_name(evaluation.schema_fields,
field_name) {
- Some(id) => id,
- None => return Ok(vec![ScoredRowIds::empty(); vector_searches.len()]),
+ let result_count = if max_sim { 1 } else { vector_searches.len() };
+ let Some(field) = evaluation
+ .schema_fields
+ .iter()
+ .find(|field| field.name() == field_name)
+ else {
+ return Ok(vec![ScoredRowIds::empty(); result_count]);
};
+ let field_id = field.id();
+ let list_scoring =
crate::vindex::multi_vector::embedding_type(field.data_type()).map(|_| {
+ if max_sim {
+ ListScoring::MaxSim
+ } else {
+ ListScoring::Independent
+ }
+ });
validate_global_vector_index_types(index_entries, field_id, field_name)?;
let vector_entries: Vec<_> = index_entries
@@ -931,7 +988,7 @@ async fn evaluate_batch_vector_search_with_executor(
if sources.is_none() && vector_entries.is_empty() && search_mode ==
GlobalIndexSearchMode::Fast
{
- return Ok(vec![ScoredRowIds::empty(); vector_searches.len()]);
+ return Ok(vec![ScoredRowIds::empty(); result_count]);
}
let (vector_search_entries, mut centroid_files) =
centroid::plan(&vector_entries)?;
@@ -1078,7 +1135,7 @@ async fn evaluate_batch_vector_search_with_executor(
.map(|vector_search| vector_search.limit)
.max()
.unwrap_or(0);
- let refine_factor = match vector_search_entries.first() {
+ let mut refine_factor = match vector_search_entries.first() {
Some(entry) => super::vector_search_common::resolved_refine_factor(
&configuration.query_options,
&configuration.resolved.options,
@@ -1087,6 +1144,9 @@ async fn evaluate_batch_vector_search_with_executor(
)?,
None => 0,
};
+ if refine_factor == 0 && list_scoring.is_some() {
+ refine_factor = if max_sim { 4 } else { 1 };
+ }
let index_search_limit = indexed_search_limit(max_limit, refine_factor)?;
let vector_entry_count = vector_search_entries.len();
@@ -1124,13 +1184,20 @@ async fn evaluate_batch_vector_search_with_executor(
.map(|entry| (entry, None))
.collect::<Vec<_>>()
};
+ let requested_metric =
+ resolved_vector_metric_override(&configuration.query_options,
field_name, index_type)?;
+ if list_scoring.is_some()
+ && requested_metric.is_some_and(|metric| metric !=
RawVectorMetric::Cosine)
+ {
+ return Err(crate::vindex::multi_vector::invalid(
+ "MultiVector searches require cosine similarity",
+ ));
+ }
let metric_check = VectorMetricCheck {
persisted: Arc::new(std::sync::Mutex::new(None)),
- requested: resolved_vector_metric_override(
- &configuration.query_options,
- field_name,
- index_type,
- )?,
+ requested: list_scoring
+ .map(|_| RawVectorMetric::Cosine)
+ .or(requested_metric),
};
let mut permit_wait = Duration::ZERO;
let mut file_reader_open = Duration::ZERO;
@@ -1162,10 +1229,10 @@ async fn evaluate_batch_vector_search_with_executor(
.remove(entry.index_file.file_name.as_str())
.unwrap_or_default();
let meta =
entry.index_file.global_index_meta.as_ref().unwrap();
- let is_centroid = !centroid_files.is_empty();
+ let prefilter_deleted = !centroid_files.is_empty() ||
list_scoring.is_some();
let deleted = deleted_row_index.as_ref();
- // Deleted rows must not consume the routed candidate budget.
- let live_rows = if is_centroid {
+ // Reserve centroid and MultiVector candidate budgets for live
rows.
+ let live_rows = if prefilter_deleted {
deleted
.and_then(|deleted| {
local_live_row_ids(deleted, meta.row_range_start,
meta.row_range_end)
@@ -1178,7 +1245,7 @@ async fn evaluate_batch_vector_search_with_executor(
index_search_limit,
meta.row_range_start,
meta.row_range_end,
- if is_centroid { None } else { deleted },
+ if prefilter_deleted { None } else { deleted },
)
.min(i32::MAX as usize);
let mut searches = indexed_searches.to_vec();
@@ -1248,6 +1315,8 @@ async fn evaluate_batch_vector_search_with_executor(
// ignoring an unfamiliar predicate payload.
if !work.centroid_files.is_empty() {
"vector-index-centroid"
+ } else if list_scoring.is_some() {
+ "vector-index-multivector"
} else if work.filter.is_some() {
"vector-index-filtered"
} else {
@@ -1297,17 +1366,33 @@ async fn evaluate_batch_vector_search_with_executor(
};
index_search = index_search_start.map_or(Duration::ZERO, |start|
start.elapsed());
let merge_start = timing_enabled.then(Instant::now);
- for (per_entry, entry_timing) in &results {
+ for (per_entry, entry_timing) in results {
permit_wait = permit_wait.saturating_add(entry_timing.permit_wait);
file_reader_open =
file_reader_open.saturating_add(entry_timing.file_reader_open);
- for (query_index, result) in per_entry.iter().enumerate() {
- merged[query_index] = merged[query_index].or(result);
+ for (merged, mut result) in merged.iter_mut().zip(per_entry) {
+ merged.row_ids.append(&mut result.row_ids);
+ merged.scores.append(&mut result.scores);
}
}
merge = merge_start.map_or(Duration::ZERO, |start| start.elapsed());
}
- if refine_factor != 0 {
+ if let Some(mode) = list_scoring {
+ let refine_start = timing_enabled.then(Instant::now);
+ let candidates = merged
+ .into_iter()
+ .map(|result| {
+ let result =
result.without_deleted_row_ranges(deleted_row_index.as_ref())?;
+ Ok(match mode {
+ ListScoring::Independent =>
result.top_k(index_search_limit),
+ ListScoring::MaxSim => result,
+ })
+ })
+ .collect::<crate::Result<Vec<_>>>()?;
+ merged =
+ rerank_list_candidates(evaluation, vector_searches, mode,
candidates, executor).await?;
+ refine = refine_start.map_or(Duration::ZERO, |start| start.elapsed());
+ } else if refine_factor != 0 {
let refine_start = timing_enabled.then(Instant::now);
if let Some(deleted) = deleted_row_index.as_ref() {
for result in &mut merged {
@@ -1394,25 +1479,30 @@ async fn evaluate_batch_vector_search_with_executor(
source: None,
})?;
let metric_start = timing_enabled.then(Instant::now);
- let metric = resolve_raw_vector_metric_resolved(
- evaluation.file_io,
- table_path,
- evaluation.table_options,
- &configuration,
- index_entries,
- field_id,
- field_name,
- )
- .await?;
+ let metric = if list_scoring.is_some() {
+ RawVectorMetric::Cosine
+ } else {
+ resolve_raw_vector_metric_resolved(
+ evaluation.file_io,
+ table_path,
+ evaluation.table_options,
+ &configuration,
+ index_entries,
+ field_id,
+ field_name,
+ )
+ .await?
+ };
let metric_resolve = metric_start.map_or(Duration::ZERO, |start|
start.elapsed());
metric_check.check(metric)?;
- let (raw_results, raw_timing) =
read_raw_batch_vector_search_with_executor(
+ let (raw_results, raw_timing) = read_raw_vector_scores(
table,
vector_searches,
&raw_ranges,
metric,
evaluation.filter,
executor,
+ list_scoring,
)
.await?;
if let Some(raw_timing) = raw_timing {
@@ -1679,6 +1769,53 @@ fn attach_scores_by_row_id(
Ok(vec![out])
}
+async fn rerank_list_candidates(
+ evaluation: VectorSearchEvaluation<'_>,
+ searches: &[VectorSearch],
+ mode: ListScoring,
+ candidates: Vec<ScoredRowIds>,
+ executor: Option<&dyn SearchTaskExecutor>,
+) -> crate::Result<Vec<ScoredRowIds>> {
+ let union: RoaringTreemap = candidates
+ .iter()
+ .flat_map(|hits| hits.row_ids.iter().copied())
+ .collect();
+ if union.is_empty() {
+ return Ok(vec![
+ ScoredRowIds::empty();
+ mode.result_count(searches.len())
+ ]);
+ }
+ let ranges = sorted_row_ids_to_row_ranges(union.iter())?;
+ let table = evaluation.table.ok_or_else(|| {
+ crate::vindex::multi_vector::invalid("MultiVector reranking requires
table context")
+ })?;
+ let mut searches = searches.to_vec();
+ for (search, hits) in searches.iter_mut().zip(candidates) {
+ match mode {
+ ListScoring::Independent => {
+
search.set_shared_include_row_ids(Arc::new(hits.row_ids.into_iter().collect()));
+ }
+ ListScoring::MaxSim => {
+ // The read ranges already contain exactly the union of
candidates.
+ search.include_row_ids = None;
+ search.shared_include_row_ids = None;
+ }
+ }
+ }
+ let (results, _) = read_raw_vector_scores(
+ table,
+ &searches,
+ &ranges,
+ RawVectorMetric::Cosine,
+ None,
+ executor,
+ Some(mode),
+ )
+ .await?;
+ Ok(results)
+}
+
#[allow(clippy::too_many_arguments)]
async fn maybe_rerank_indexed_batch_results(
evaluation: VectorSearchEvaluation<'_>,
@@ -2168,9 +2305,13 @@ async fn execute_raw_vector_tasks(
vector_searches: &[VectorSearch],
metric: RawVectorMetric,
executor: &dyn SearchTaskExecutor,
+ list_scoring: Option<ListScoring>,
) -> crate::Result<Vec<ScoredRowIds>> {
let queries = TaskVectorQueries::capture(vector_searches)?;
- let mut merged = vec![ScoredRowIds::empty(); vector_searches.len()];
+ let result_count = list_scoring.map_or(vector_searches.len(), |mode| {
+ mode.result_count(vector_searches.len())
+ });
+ let mut merged = vec![ScoredRowIds::empty(); result_count];
for window in splits.chunks(SEARCH_TASK_WINDOW) {
let tasks = window
.iter()
@@ -2179,10 +2320,15 @@ async fn execute_raw_vector_tasks(
splits: vec![split.clone()],
queries: queries.clone(),
metric,
+ list_scoring,
};
SearchTask::new(
table,
- "vector-rows",
+ if list_scoring.is_some() {
+ "vector-list-rows"
+ } else {
+ "vector-rows"
+ },
serde_json::to_value(work)
.map_err(|error|
crate::table::search_task::invalid(error.to_string()))?,
)
@@ -2213,17 +2359,41 @@ async fn read_raw_batch_vector_search_with_executor(
filter: Option<&Predicate>,
executor: Option<&dyn SearchTaskExecutor>,
) -> crate::Result<(Vec<ScoredRowIds>, Option<RawVectorReadTiming>)> {
+ read_raw_vector_scores(
+ table,
+ vector_searches,
+ raw_ranges,
+ metric,
+ filter,
+ executor,
+ None,
+ )
+ .await
+}
+
+async fn read_raw_vector_scores(
+ table: &Table,
+ vector_searches: &[VectorSearch],
+ raw_ranges: &[RowRange],
+ metric: RawVectorMetric,
+ filter: Option<&Predicate>,
+ executor: Option<&dyn SearchTaskExecutor>,
+ list_scoring: Option<ListScoring>,
+) -> crate::Result<(Vec<ScoredRowIds>, Option<RawVectorReadTiming>)> {
+ let result_count = list_scoring.map_or(vector_searches.len(), |mode| {
+ mode.result_count(vector_searches.len())
+ });
let timing_enabled = vector_search_timing_enabled();
let total_start = timing_enabled.then(Instant::now);
if vector_searches.is_empty() {
return Ok((Vec::new(), None));
}
if raw_ranges.is_empty() {
- return Ok((vec![ScoredRowIds::empty(); vector_searches.len()], None));
+ return Ok((vec![ScoredRowIds::empty(); result_count], None));
}
let raw_ranges = prune_raw_ranges_by_include_row_ids(raw_ranges,
vector_searches)?;
if raw_ranges.is_empty() {
- return Ok((vec![ScoredRowIds::empty(); vector_searches.len()], None));
+ return Ok((vec![ScoredRowIds::empty(); result_count], None));
}
let field_name = &vector_searches[0].field_name;
@@ -2256,7 +2426,7 @@ async fn read_raw_batch_vector_search_with_executor(
.sum();
if plan.splits().is_empty() {
return Ok((
- vec![ScoredRowIds::empty(); vector_searches.len()],
+ vec![ScoredRowIds::empty(); result_count],
total_start.map(|start| RawVectorReadTiming {
plan: plan_elapsed,
total: start.elapsed(),
@@ -2285,16 +2455,24 @@ async fn read_raw_batch_vector_search_with_executor(
search.set_shared_include_row_ids(eligible);
}
}
- let merged =
- execute_raw_vector_tasks(table, plan.splits(), &searches, metric,
executor).await?;
+ let merged = execute_raw_vector_tasks(
+ table,
+ plan.splits(),
+ &searches,
+ metric,
+ executor,
+ list_scoring,
+ )
+ .await?;
return Ok((merged, None));
}
let read = read_builder.new_read()?;
let mut stream = read.to_arrow(plan.splits())?;
- let scoring_plan = RawScoringPlan::new(vector_searches, metric);
+ let scoring_plan = RawBatchScoring::new(vector_searches, metric,
list_scoring)?;
let mut top_k = vector_searches
.iter()
+ .take(result_count)
.map(|vector_search| RawScoreTopK::new(vector_search.limit))
.collect::<Vec<_>>();
let mut timing = timing_enabled.then(|| RawVectorReadTiming {
@@ -2319,7 +2497,7 @@ async fn read_raw_batch_vector_search_with_executor(
timing.row_count =
timing.row_count.saturating_add(batch.num_rows());
}
let score_start = timing_enabled.then(Instant::now);
- collect_raw_batch_vector_batch(&batch, vector_searches, metric,
&scoring_plan, &mut top_k)?;
+ scoring_plan.collect(&batch, vector_searches, metric, &mut top_k)?;
if let (Some(timing), Some(score_start)) = (&mut timing, score_start) {
timing.score_cpu =
timing.score_cpu.saturating_add(score_start.elapsed());
}
@@ -2337,6 +2515,39 @@ async fn read_raw_batch_vector_search_with_executor(
))
}
+enum RawBatchScoring {
+ Vector(RawScoringPlan),
+ List(ListScorer),
+}
+
+impl RawBatchScoring {
+ fn new(
+ searches: &[VectorSearch],
+ metric: RawVectorMetric,
+ list_scoring: Option<ListScoring>,
+ ) -> crate::Result<Self> {
+ match list_scoring {
+ Some(mode) => Ok(Self::List(ListScorer::new(mode, searches)?)),
+ None => Ok(Self::Vector(RawScoringPlan::new(searches, metric))),
+ }
+ }
+
+ fn collect(
+ &self,
+ batch: &RecordBatch,
+ searches: &[VectorSearch],
+ metric: RawVectorMetric,
+ top_k: &mut [RawScoreTopK],
+ ) -> crate::Result<()> {
+ match self {
+ Self::Vector(plan) => {
+ collect_raw_batch_vector_batch(batch, searches, metric, plan,
top_k)
+ }
+ Self::List(scorer) => scorer.collect(batch, searches, top_k),
+ }
+ }
+}
+
struct RawScoringPlan {
all_query_indices: Vec<usize>,
shared_filter_groups: Vec<SharedRawFilterGroup>,
@@ -3073,6 +3284,8 @@ struct VectorRowsTask {
splits: Vec<crate::table::DataSplit>,
queries: TaskVectorQueries,
metric: RawVectorMetric,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ list_scoring: Option<ListScoring>,
}
#[derive(Serialize, Deserialize)]
struct TaskScoredRows {
@@ -3123,7 +3336,10 @@ pub(super) async fn execute_search_task(
payload: &serde_json::Value,
) -> crate::Result<serde_json::Value> {
let scores = match kind {
- "vector-index" | "vector-index-filtered" | "vector-index-centroid" => {
+ "vector-index"
+ | "vector-index-filtered"
+ | "vector-index-centroid"
+ | "vector-index-multivector" => {
let work: VectorIndexTask = serde_json::from_value(payload.clone())
.map_err(|error|
crate::table::search_task::invalid(error.to_string()))?;
if kind == "vector-index-filtered" && work.filter.is_none() {
@@ -3173,7 +3389,7 @@ pub(super) async fn execute_search_task(
.map_err(|_| crate::table::search_task::invalid("Vector metric
lock poisoned"))?;
VectorTaskScores::capture(results, metric)
}
- "vector-rows" => {
+ "vector-rows" | "vector-list-rows" => {
let work: VectorRowsTask = serde_json::from_value(payload.clone())
.map_err(|error|
crate::table::search_task::invalid(error.to_string()))?;
let searches = work.queries.restore()?;
@@ -3186,19 +3402,22 @@ pub(super) async fn execute_search_task(
builder.with_projection(&[searches[0].field_name.as_str(),
ROW_ID_FIELD_NAME])?;
let read = builder.new_read()?;
let mut stream = read.to_arrow(&work.splits)?;
- let scoring = RawScoringPlan::new(&searches, work.metric);
+ if (kind == "vector-list-rows") != work.list_scoring.is_some() {
+ return Err(crate::table::search_task::invalid(
+ "Invalid MultiVector scoring task",
+ ));
+ }
+ let scoring = RawBatchScoring::new(&searches, work.metric,
work.list_scoring)?;
+ let result_count = work
+ .list_scoring
+ .map_or(searches.len(), |mode|
mode.result_count(searches.len()));
let mut top_k = searches
.iter()
+ .take(result_count)
.map(|search| RawScoreTopK::new(search.limit))
.collect::<Vec<_>>();
while let Some(batch) = stream.try_next().await? {
- collect_raw_batch_vector_batch(
- &batch,
- &searches,
- work.metric,
- &scoring,
- &mut top_k,
- )?;
+ scoring.collect(&batch, &searches, work.metric, &mut top_k)?;
}
VectorTaskScores::capture(
top_k
diff --git a/crates/paimon/src/table/de_vector_read/multi_vector.rs
b/crates/paimon/src/table/de_vector_read/multi_vector.rs
new file mode 100644
index 00000000..23b46435
--- /dev/null
+++ b/crates/paimon/src/table/de_vector_read/multi_vector.rs
@@ -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.
+
+use super::{RawScoreTopK, VectorSearch};
+use crate::spec::ROW_ID_FIELD_NAME;
+use crate::vindex::multi_vector::{cosine, invalid, norm, validate_queries,
MultiVectorArray};
+use crate::Result;
+use arrow_array::{Array, Int64Array, RecordBatch};
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Copy, Serialize, Deserialize)]
+pub(super) enum ListScoring {
+ Independent,
+ MaxSim,
+}
+
+impl ListScoring {
+ pub(super) fn result_count(self, query_count: usize) -> usize {
+ match self {
+ Self::Independent => query_count,
+ Self::MaxSim => 1,
+ }
+ }
+}
+
+pub(super) struct ListScorer {
+ mode: ListScoring,
+ query_norms: Vec<f64>,
+}
+
+impl ListScorer {
+ pub(super) fn new(mode: ListScoring, searches: &[VectorSearch]) ->
Result<Self> {
+ let queries = searches
+ .iter()
+ .map(|search| search.vector.as_slice())
+ .collect::<Vec<_>>();
+ validate_queries(&queries, None)?;
+ Ok(Self {
+ mode,
+ query_norms: queries.into_iter().map(norm).collect(),
+ })
+ }
+
+ pub(super) fn collect(
+ &self,
+ batch: &RecordBatch,
+ searches: &[VectorSearch],
+ top_k: &mut [RawScoreTopK],
+ ) -> Result<()> {
+ let field_name = &searches[0].field_name;
+ let dimension = searches[0].vector.len();
+ let column = batch
+ .column_by_name(field_name)
+ .ok_or_else(|| invalid(format!("MultiVector column '{field_name}'
is missing")))?;
+ let column = MultiVectorArray::new(column.as_ref())?;
+ let row_ids = batch
+ .column_by_name(ROW_ID_FIELD_NAME)
+ .and_then(|array| array.as_any().downcast_ref::<Int64Array>())
+ .filter(|ids| ids.null_count() == 0)
+ .ok_or_else(|| invalid("MultiVector scoring requires non-null
Int64 _ROW_ID"))?;
+ let mut selected = Vec::with_capacity(searches.len());
+ let mut maxima = vec![f64::NEG_INFINITY; searches.len()];
+ let shared_filter = searches[0].effective_include_row_ids();
+ for (row, &id) in row_ids.values().iter().enumerate() {
+ let id = u64::try_from(id).map_err(|_| invalid("Negative
MultiVector row ID"))?;
+ selected.clear();
+ match self.mode {
+ ListScoring::MaxSim => {
+ if shared_filter.is_some_and(|ids| !ids.contains(id)) {
+ continue;
+ }
+ selected.extend(0..searches.len());
+ }
+ ListScoring::Independent => {
+
selected.extend(searches.iter().enumerate().filter_map(|(i, search)| {
+ search
+ .effective_include_row_ids()
+ .is_none_or(|ids| ids.contains(id))
+ .then_some(i)
+ }));
+ }
+ }
+ if selected.is_empty() {
+ continue;
+ }
+ let mut found = false;
+ maxima.fill(f64::NEG_INFINITY);
+ for embedding in column.row(row, dimension) {
+ let embedding = embedding?;
+ found = true;
+ let vector_norm = norm(embedding);
+ for &i in &selected {
+ maxima[i] = maxima[i].max(cosine(
+ &searches[i].vector,
+ self.query_norms[i],
+ embedding,
+ vector_norm,
+ ));
+ }
+ }
+ if found {
+ match self.mode {
+ ListScoring::MaxSim => top_k[0].offer(id,
maxima.iter().sum::<f64>() as f32),
+ ListScoring::Independent => {
+ for &i in &selected {
+ top_k[i].offer(id, maxima[i] as f32);
+ }
+ }
+ }
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/crates/paimon/src/table/de_vector_read/tests.rs
b/crates/paimon/src/table/de_vector_read/tests.rs
index 0247fd6e..78cb16d8 100644
--- a/crates/paimon/src/table/de_vector_read/tests.rs
+++ b/crates/paimon/src/table/de_vector_read/tests.rs
@@ -2228,10 +2228,16 @@ async fn
scheduled_raw_vector_merges_bounded_windows_without_losing_late_winners
batch_sizes: std::sync::Mutex::new(Vec::new()),
ordinal: std::sync::atomic::AtomicUsize::new(0),
};
- let results =
- execute_raw_vector_tasks(&table, &splits, &queries,
RawVectorMetric::L2, &executor)
- .await
- .unwrap();
+ let results = execute_raw_vector_tasks(
+ &table,
+ &splits,
+ &queries,
+ RawVectorMetric::L2,
+ &executor,
+ None,
+ )
+ .await
+ .unwrap();
assert_eq!(
*executor.batch_sizes.lock().unwrap(),
vec![
diff --git a/crates/paimon/src/table/global_index_build_builder.rs
b/crates/paimon/src/table/global_index_build_builder.rs
index 8c07ff86..bd68ee9f 100644
--- a/crates/paimon/src/table/global_index_build_builder.rs
+++ b/crates/paimon/src/table/global_index_build_builder.rs
@@ -124,6 +124,7 @@ impl<'a> GlobalIndexBuildBuilder<'a> {
columns[0],
index_type,
index_type,
+ true,
)?;
Ok(effective.copy_with_options(defaults))
}
diff --git a/crates/paimon/src/table/global_index_options.rs
b/crates/paimon/src/table/global_index_options.rs
index ac40ee58..068cda9d 100644
--- a/crates/paimon/src/table/global_index_options.rs
+++ b/crates/paimon/src/table/global_index_options.rs
@@ -17,7 +17,7 @@
//! Shared field declarations and native options for global-index maintenance
and raw reads.
-use crate::spec::CoreOptions;
+use crate::spec::{CoreOptions, DataField, TableSchema};
use crate::table::global_index_types::normalize_global_index_type;
use crate::table::{GlobalIndexBuildBuilder, Table};
use crate::Result;
@@ -42,8 +42,8 @@ impl Definition {
}
/// Ownership is shared by maintenance and both table modes' read paths.
-pub(super) fn declarations(options: &HashMap<String, String>) ->
Result<Vec<Definition>> {
- declarations_impl(options, true)
+pub(super) fn declarations(schema: &TableSchema) -> Result<Vec<Definition>> {
+ declarations_impl(schema.options(), Some(schema.fields()))
}
/// Read planning can encounter unresolved legacy schema properties. Ignore
@@ -51,13 +51,17 @@ pub(super) fn declarations(options: &HashMap<String,
String>) -> Result<Vec<Defi
pub(super) fn declarations_for_read(
options: &HashMap<String, String>,
) -> Result<Vec<(String, String)>> {
- Ok(declarations_impl(options, false)?
+ Ok(declarations_impl(options, None)?
.into_iter()
.map(|definition| (definition.column, definition.index_type))
.collect())
}
-fn declarations_impl(options: &HashMap<String, String>, strict: bool) ->
Result<Vec<Definition>> {
+fn declarations_impl(
+ options: &HashMap<String, String>,
+ fields: Option<&[DataField]>,
+) -> Result<Vec<Definition>> {
+ let strict = fields.is_some();
let core = CoreOptions::new(options);
for kind in core.global_index_types() {
if strict && kind != "vector" &&
normalize_global_index_type(&kind).is_none() {
@@ -93,8 +97,14 @@ fn declarations_impl(options: &HashMap<String, String>,
strict: bool) -> Result<
if !owners.insert(column.clone()) {
return Err(crate::Error::ConfigInvalid { message:
format!("Column '{column}' can own at most one primary-key index or
automatically maintained global index") });
}
- let (kind, resolved) = if family == "vector" && strict {
- let resolved = core.vector_index_options(None, &column, true)?;
+ let (kind, resolved) = if let ("vector", Some(fields)) = (family,
fields) {
+ let default_metric = fields
+ .iter()
+ .find(|field| field.name() == column)
+ .is_none_or(|field| {
+
crate::vindex::multi_vector::embedding_type(field.data_type()).is_none()
+ });
+ let resolved = core.vector_index_options(None, &column,
default_metric)?;
let kind = resolved
.index_type
.ok_or_else(|| crate::Error::ConfigInvalid {
@@ -133,7 +143,7 @@ fn declarations_impl(options: &HashMap<String, String>,
strict: bool) -> Result<
pub(super) fn definitions(table: &Table) -> Result<Vec<Definition>> {
let options = table.schema().options();
- let owners = declarations(options)?
+ let owners = declarations(table.schema())?
.into_iter()
.map(|definition| (definition.column.clone(), definition))
.collect::<HashMap<_, _>>();
@@ -171,10 +181,19 @@ pub(super) fn field_index_options(
column: &str,
_family: &str,
index_type: &str,
+) -> Result<HashMap<String, String>> {
+ field_index_option_overrides(table_options, column, index_type, true)
+}
+
+fn field_index_option_overrides(
+ table_options: &HashMap<String, String>,
+ column: &str,
+ index_type: &str,
+ default_vector_metric: bool,
) -> Result<HashMap<String, String>> {
let core = CoreOptions::new(table_options);
let resolved = if crate::vindex::is_vindex_index_type(index_type) {
- core.vector_index_options(Some(index_type), column, true)?
+ core.vector_index_options(Some(index_type), column,
default_vector_metric)?
.options
} else {
core.global_index_options(index_type, column)?
@@ -292,6 +311,7 @@ pub(super) fn declared_options(
column: &str,
family: &str,
index_type: &str,
+ default_vector_metric: bool,
) -> Result<HashMap<String, String>> {
let prefixes = [
format!("fields.{column}.global-index.{family}."),
@@ -303,7 +323,7 @@ pub(super) fn declared_options(
.keys()
.any(|key| prefixes.iter().any(|prefix| key.starts_with(prefix)))
{
- field_index_options(options, column, family, index_type)
+ field_index_option_overrides(options, column, index_type,
default_vector_metric)
} else {
Ok(HashMap::new())
}
diff --git a/crates/paimon/src/table/index_build/vector.rs
b/crates/paimon/src/table/index_build/vector.rs
index 294e937f..7f25e99a 100644
--- a/crates/paimon/src/table/index_build/vector.rs
+++ b/crates/paimon/src/table/index_build/vector.rs
@@ -16,7 +16,7 @@
// under the License.
//! Shared sparse-vector spill, training, and native serialization.
-use super::vector_extraction::{local_ids, validate_vector_batch};
+use super::vector_extraction::{local_ids, validate_multi_vector_batch,
validate_vector_batch};
use super::vector_validation::{
checked_std_vector_bytes, checked_training_sample_index,
checked_training_vector_count,
checked_vector_bytes,
@@ -44,6 +44,7 @@ pub(in crate::table) struct VectorSpill {
ids: tokio::fs::File,
range: RowRange,
dimension: usize,
+ multi_vector: bool,
next_id: i64,
rows: usize,
vectors: usize,
@@ -66,11 +67,17 @@ impl VectorSpill {
next_id: range.from(),
range,
dimension,
+ multi_vector: false,
rows: 0,
vectors: 0,
bytes: 0,
})
}
+ pub fn with_multi_vector(mut self, multi_vector: bool) -> Self {
+ self.multi_vector = multi_vector;
+ self
+ }
+
pub fn bytes_written(&self) -> usize {
self.bytes
}
@@ -81,7 +88,11 @@ impl VectorSpill {
column: &str,
timing_enabled: bool,
) -> Result<Duration> {
- let vectors = validate_vector_batch(batch, column, self.dimension,
&mut self.next_id)?;
+ let vectors = if self.multi_vector {
+ validate_multi_vector_batch(batch, column, self.dimension, &mut
self.next_id)?
+ } else {
+ validate_vector_batch(batch, column, self.dimension, &mut
self.next_id)?
+ };
self.rows =
self.rows
.checked_add(vectors.source_rows)
diff --git a/crates/paimon/src/table/index_build/vector_extraction.rs
b/crates/paimon/src/table/index_build/vector_extraction.rs
index 1784c85a..88414066 100644
--- a/crates/paimon/src/table/index_build/vector_extraction.rs
+++ b/crates/paimon/src/table/index_build/vector_extraction.rs
@@ -56,22 +56,59 @@ pub(in crate::table) fn validate_vector_batch(
expected_row_id: &mut i64,
) -> Result<ValidatedVectorBatch> {
validate_vector_batch_with(batch, index_column, dimension, |row_id| {
- if row_id != *expected_row_id {
- return Err(Error::DataInvalid {
- message: format!(
- "vindex vector extraction expected _ROW_ID {}, got {}",
- expected_row_id, row_id
- ),
- source: None,
- });
+ validate_contiguous_row_id(row_id, expected_row_id)
+ })
+}
+
+fn validate_contiguous_row_id(row_id: i64, expected_row_id: &mut i64) ->
Result<()> {
+ if row_id != *expected_row_id {
+ return Err(Error::DataInvalid {
+ message: format!(
+ "vindex vector extraction expected _ROW_ID {}, got {}",
+ expected_row_id, row_id
+ ),
+ source: None,
+ });
+ }
+ *expected_row_id = expected_row_id
+ .checked_add(1)
+ .ok_or_else(|| Error::DataInvalid {
+ message: "vindex expected row id overflows i64".to_string(),
+ source: None,
+ })?;
+ Ok(())
+}
+
+pub(in crate::table) fn validate_multi_vector_batch(
+ batch: &RecordBatch,
+ index_column: &str,
+ dimension: usize,
+ expected_row_id: &mut i64,
+) -> Result<ValidatedVectorBatch> {
+ use crate::vindex::multi_vector::{invalid, normalize_into,
MultiVectorArray};
+ let column = batch
+ .column_by_name(index_column)
+ .ok_or_else(|| invalid(format!("MultiVector column '{index_column}' is
missing")))?;
+ let vectors = MultiVectorArray::new(column.as_ref())?;
+ let ids = batch
+ .column_by_name(ROW_ID_FIELD_NAME)
+ .and_then(|array| array.as_any().downcast_ref::<Int64Array>())
+ .filter(|ids| ids.null_count() == 0)
+ .ok_or_else(|| invalid("MultiVector extraction requires non-null Int64
_ROW_ID"))?;
+ let mut values = Vec::new();
+ let mut row_ids = Vec::new();
+ for (row, &row_id) in ids.values().iter().enumerate() {
+ validate_contiguous_row_id(row_id, expected_row_id)?;
+ for vector in vectors.row(row, dimension) {
+ normalize_into(vector?, &mut values);
+ row_ids.push(row_id);
}
- *expected_row_id = expected_row_id
- .checked_add(1)
- .ok_or_else(|| Error::DataInvalid {
- message: "vindex expected row id overflows i64".to_string(),
- source: None,
- })?;
- Ok(())
+ }
+ Ok(ValidatedVectorBatch {
+ vector_count: row_ids.len(),
+ source_rows: batch.num_rows(),
+ values: values.into(),
+ row_ids: row_ids.into(),
})
}
diff --git a/crates/paimon/src/table/pk_index_options.rs
b/crates/paimon/src/table/pk_index_options.rs
index d426a5bd..7c423d70 100644
--- a/crates/paimon/src/table/pk_index_options.rs
+++ b/crates/paimon/src/table/pk_index_options.rs
@@ -41,7 +41,7 @@ pub(super) fn field_options(
pub(super) fn definitions(schema: &TableSchema) -> Result<Vec<Definition>> {
let options = schema.options();
- let owners = crate::table::global_index_options::declarations(options)?
+ let owners = crate::table::global_index_options::declarations(schema)?
.into_iter()
.map(|definition| (definition.column.clone(), definition))
.collect::<HashMap<_, _>>();
diff --git a/crates/paimon/src/table/search_task.rs
b/crates/paimon/src/table/search_task.rs
index a6774e36..db68609f 100644
--- a/crates/paimon/src/table/search_task.rs
+++ b/crates/paimon/src/table/search_task.rs
@@ -240,7 +240,12 @@ impl SearchTask {
.copy_with_resolved_schema(self.schema.clone(), &self.branch)?
.copy_with_pinned_snapshot(self.snapshot.as_ref());
let payload = match self.kind.as_str() {
- "vector-index" | "vector-index-filtered" | "vector-index-centroid"
| "vector-rows" => {
+ "vector-index"
+ | "vector-index-filtered"
+ | "vector-index-centroid"
+ | "vector-index-multivector"
+ | "vector-rows"
+ | "vector-list-rows" => {
super::de_vector_read::execute_search_task(&pinned,
&self.kind, &self.payload)
.await?
}
diff --git a/crates/paimon/src/table/vector_read.rs
b/crates/paimon/src/table/vector_read.rs
index a4a6fd83..bb8acc21 100644
--- a/crates/paimon/src/table/vector_read.rs
+++ b/crates/paimon/src/table/vector_read.rs
@@ -94,6 +94,7 @@ impl BatchVectorRead {
table, options, filter, &pk_col, queries, limit,
)))
} else {
+ validate_list_queries(table, column, queries, false)?;
VectorReadKind::DataEvolution(DeVectorRead::new(column, queries,
limit, options)?)
};
Ok(Self {
@@ -103,6 +104,23 @@ impl BatchVectorRead {
})
}
+ pub(super) fn new_max_sim(
+ table: &Table,
+ column: &str,
+ queries: &[&[f32]],
+ limit: usize,
+ options: &HashMap<String, String>,
+ context: PlanContext,
+ ) -> crate::Result<Self> {
+ validate_list_queries(table, column, queries, true)?;
+ let reader = DeVectorRead::new(column, queries, limit,
options)?.with_max_sim();
+ Ok(Self {
+ context,
+ table: table.clone(),
+ reader: VectorReadKind::DataEvolution(reader),
+ })
+ }
+
pub async fn read(&self, plan: VectorScanPlan) ->
crate::Result<Vec<GlobalIndexResult>> {
self.read_impl(plan, None).await
}
@@ -188,3 +206,35 @@ impl BatchVectorRead {
}
}
}
+
+fn validate_list_queries(
+ table: &Table,
+ column: &str,
+ queries: &[&[f32]],
+ matrix: bool,
+) -> crate::Result<()> {
+ use crate::vindex::multi_vector::{embedding_type, invalid,
validate_queries};
+ let list = table
+ .schema()
+ .fields()
+ .iter()
+ .find(|field| field.name() == column)
+ .and_then(|field| embedding_type(field.data_type()));
+ if let Some(inner) = list {
+ let schema = table.schema();
+ if !schema.core_options().data_evolution_enabled() ||
!schema.primary_keys().is_empty() {
+ return Err(invalid(
+ "MultiVector search requires a Data Evolution append table",
+ ));
+ }
+ let width = match inner {
+ crate::spec::DataType::Vector(v) => Some(v.length() as usize),
+ _ => None,
+ };
+ validate_queries(queries, width)
+ } else if matrix {
+ Err(invalid("MaxSim queries require an embedding-list column"))
+ } else {
+ Ok(())
+ }
+}
diff --git a/crates/paimon/src/table/vector_search_builder.rs
b/crates/paimon/src/table/vector_search_builder.rs
index 098c76ca..e1b2ada6 100644
--- a/crates/paimon/src/table/vector_search_builder.rs
+++ b/crates/paimon/src/table/vector_search_builder.rs
@@ -40,7 +40,8 @@ pub struct VectorSearchBuilder<'a> {
#[derive(Clone, Default)]
struct VectorSearchConfig {
vector_column: Option<String>,
- query_vector: Option<Vec<f32>>,
+ query_vectors: Option<Vec<Vec<f32>>>,
+ max_sim: bool,
limit: Option<usize>,
options: HashMap<String, String>,
filter: Option<Predicate>,
@@ -75,7 +76,20 @@ impl<'a> VectorSearchBuilder<'a> {
}
pub fn with_query_vector(&mut self, vector: Vec<f32>) -> &mut Self {
- self.config.write().unwrap().query_vector = Some(vector);
+ let mut config = self.config.write().unwrap();
+ config.query_vectors = Some(vec![vector]);
+ config.max_sim = false;
+ drop(config);
+ self
+ }
+
+ /// Query a list of embeddings with MaxSim, returning a single ranked
result.
+ /// Each query vector contributes its highest cosine similarity per row.
+ pub fn with_multi_vector(&mut self, vectors: Vec<Vec<f32>>) -> &mut Self {
+ let mut config = self.config.write().unwrap();
+ config.query_vectors = Some(vectors);
+ config.max_sim = true;
+ drop(config);
self
}
@@ -142,19 +156,30 @@ impl<'a> VectorSearchBuilder<'a> {
}
fn read_with_config(&self, config: &VectorSearchConfig) ->
crate::Result<VectorRead> {
- let (column, query, limit) = self.query(config)?;
+ let (column, queries, limit) = self.query(config)?;
let context = PlanContext::new(&self.table, column,
config.filter.as_ref(), None, None)?;
- Ok(VectorRead {
- batch: BatchVectorRead::new(
+ let queries = queries.iter().map(Vec::as_slice).collect::<Vec<_>>();
+ let batch = if config.max_sim {
+ BatchVectorRead::new_max_sim(
+ &self.table,
+ column,
+ &queries,
+ limit,
+ &config.options,
+ context,
+ )?
+ } else {
+ BatchVectorRead::new(
&self.table,
column,
- &[query],
+ &queries,
limit,
&config.options,
config.filter.as_ref(),
context,
- )?,
- })
+ )?
+ };
+ Ok(VectorRead { batch })
}
pub(crate) fn new_scan_and_read(&self) -> crate::Result<(VectorScan,
VectorRead)> {
@@ -173,7 +198,7 @@ impl<'a> VectorSearchBuilder<'a> {
fn query<'c>(
&self,
config: &'c VectorSearchConfig,
- ) -> crate::Result<(&'c str, &'c [f32], usize)> {
+ ) -> crate::Result<(&'c str, &'c [Vec<f32>], usize)> {
CoreOptions::new(self.table.schema().options()).ensure_read_authorized()?;
let column =
config
@@ -182,16 +207,17 @@ impl<'a> VectorSearchBuilder<'a> {
.ok_or_else(|| crate::Error::ConfigInvalid {
message: "Vector column must be set via
with_vector_column()".to_string(),
})?;
- let vector = config
- .query_vector
- .as_deref()
- .ok_or_else(|| crate::Error::ConfigInvalid {
- message: "Query vector must be set via
with_query_vector()".to_string(),
- })?;
+ let queries =
+ config
+ .query_vectors
+ .as_deref()
+ .ok_or_else(|| crate::Error::ConfigInvalid {
+ message: "Query vector must be set via
with_query_vector()".to_string(),
+ })?;
let limit = config.limit.ok_or_else(|| crate::Error::ConfigInvalid {
message: "Limit must be set via with_limit()".to_string(),
})?;
- Ok((column, vector, limit))
+ Ok((column, queries, limit))
}
}
diff --git a/crates/paimon/src/table/vindex_index_build_builder.rs
b/crates/paimon/src/table/vindex_index_build_builder.rs
index 7125dc70..5b2bb8cd 100644
--- a/crates/paimon/src/table/vindex_index_build_builder.rs
+++ b/crates/paimon/src/table/vindex_index_build_builder.rs
@@ -83,11 +83,13 @@ impl<'a> VindexIndexBuildBuilder<'a> {
&procedure,
column,
);
+ let multi_vector =
crate::vindex::multi_vector::embedding_type(field.data_type()).is_some();
let defaults = super::global_index_options::declared_options(
&effective,
column,
"vector",
&self.index_type,
+ !multi_vector,
)?;
let user =
super::global_index_options::build_options(&procedure, column,
&self.index_type)?;
@@ -98,6 +100,18 @@ impl<'a> VindexIndexBuildBuilder<'a> {
&self.index_type,
column,
)?;
+ if multi_vector {
+ if !self.table.schema().core_options().data_evolution_enabled() {
+ return Err(crate::vindex::multi_vector::invalid(
+ "MultiVector indexes require a Data Evolution table",
+ ));
+ }
+ if centroid.is_some() {
+ return Err(crate::vindex::multi_vector::invalid(
+ "MultiVector indexes require range sharding",
+ ));
+ }
+ }
let mut native_defaults = defaults.clone();
let mut native_user = crate::vindex::build_parameters(&user,
&self.index_type, column);
for options in [&mut native_defaults, &mut native_user] {
diff --git
a/crates/paimon/src/table/vindex_index_build_builder/multi_vector_tests.rs
b/crates/paimon/src/table/vindex_index_build_builder/multi_vector_tests.rs
new file mode 100644
index 00000000..ae3f75b2
--- /dev/null
+++ b/crates/paimon/src/table/vindex_index_build_builder/multi_vector_tests.rs
@@ -0,0 +1,497 @@
+// 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.
+
+use super::*;
+use crate::spec::{Datum, PredicateBuilder, VectorType};
+use crate::table::{DataSplit, SearchTask, SearchTaskExecutor,
SearchTaskResult};
+use arrow_array::Array;
+use std::sync::Mutex;
+
+struct Worker<'a>(&'a Table);
+
+#[async_trait::async_trait]
+impl SearchTaskExecutor for Worker<'_> {
+ async fn execute(&self, tasks: Vec<SearchTask>) ->
Result<Vec<SearchTaskResult>> {
+ let (context, frames) = SearchTask::serialize_batch(&tasks)?;
+ let mut results = vec![];
+ for frame in frames {
+ let result = self.0.execute_search_task(&frame, &context).await?;
+ results.push(SearchTaskResult::deserialize(&result)?);
+ }
+ Ok(results)
+ }
+}
+
+struct RecordingWorker<'a> {
+ table: &'a Table,
+ list_reads: Mutex<Vec<serde_json::Value>>,
+}
+
+#[async_trait::async_trait]
+impl SearchTaskExecutor for RecordingWorker<'_> {
+ async fn execute(&self, tasks: Vec<SearchTask>) ->
Result<Vec<SearchTaskResult>> {
+ for task in &tasks {
+ let work = serde_json::to_value(task).unwrap();
+ if work["kind"] == "vector-list-rows" {
+ self.list_reads
+ .lock()
+ .unwrap()
+ .push(work["payload"].clone());
+ }
+ }
+ Worker(self.table).execute(tasks).await
+ }
+}
+
+fn list_schema(fixed: bool) -> Schema {
+ let float = DataType::Float(FloatType::new());
+ let embedding = if fixed {
+ DataType::Vector(VectorType::new(2, float).unwrap())
+ } else {
+ DataType::Array(ArrayType::new(float))
+ };
+ Schema::builder()
+ .column("id", DataType::Int(IntType::new()))
+ .column("chunks", DataType::Array(ArrayType::new(embedding)))
+ .options(table_options("5"))
+ .option("write-only", "true")
+ .build()
+ .unwrap()
+}
+
+fn append_value(builder: &mut Float32Builder, coordinates: [f32; 2]) {
+ for coordinate in coordinates {
+ builder.append_value(coordinate);
+ }
+}
+
+type EmbeddingList = Option<Vec<Option<[f32; 2]>>>;
+
+async fn append_lists(table: &Table, first_id: i32, fixed: bool, rows:
&[EmbeddingList]) {
+ let column: ArrayRef = if fixed {
+ let mut outer =
ListBuilder::new(FixedSizeListBuilder::new(Float32Builder::new(), 2));
+ for row in rows {
+ if let Some(embeddings) = row {
+ for embedding in embeddings {
+ // Arrow requires two placeholder coordinates for a null
fixed-size list.
+ append_value(outer.values().values(),
embedding.unwrap_or([0.0, 0.0]));
+ outer.values().append(embedding.is_some());
+ }
+ }
+ outer.append(row.is_some());
+ }
+ Arc::new(outer.finish())
+ } else {
+ let mut outer =
ListBuilder::new(ListBuilder::new(Float32Builder::new()));
+ for row in rows {
+ if let Some(embeddings) = row {
+ for embedding in embeddings {
+ if let Some(coordinates) = embedding {
+ append_value(outer.values().values(), *coordinates);
+ }
+ outer.values().append(embedding.is_some());
+ }
+ }
+ outer.append(row.is_some());
+ }
+ Arc::new(outer.finish())
+ };
+ let schema = Arc::new(ArrowSchema::new(vec![
+ ArrowField::new("id", ArrowDataType::Int32, false),
+ ArrowField::new("chunks", column.data_type().clone(), true),
+ ]));
+ let ids = Int32Array::from((first_id..first_id + rows.len() as
i32).collect::<Vec<_>>());
+ let batch = RecordBatch::try_new(schema, vec![Arc::new(ids),
column]).unwrap();
+ let mut writer = TableWrite::new(table,
format!("lists-{first_id}")).unwrap();
+ writer.write_arrow_batch(&batch).await.unwrap();
+ TableCommit::new(table.clone(), format!("lists-{first_id}"))
+ .commit(writer.prepare_commit().await.unwrap())
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn
multi_vector_indexes_rank_distinct_rows_and_rerank_the_full_candidate_union() {
+ for fixed in [false, true] {
+ let path = format!("memory:/multivector_candidates_{fixed}");
+ let io = FileIOBuilder::new("memory").build().unwrap();
+ let table = test_table_with_io(io, &path, list_schema(fixed));
+ setup_dirs(table.file_io(), &path).await;
+ append_lists(
+ &table,
+ 0,
+ fixed,
+ &[
+ Some(vec![Some([1.0, 0.0]); 24]),
+ Some(vec![Some([0.8, 0.6])]),
+ Some(vec![Some([0.0, 1.0])]),
+ None,
+ Some(vec![None]),
+ Some(vec![Some([0.0, 1.0]), None, Some([1.0, 0.0])]),
+ Some(vec![]),
+ ],
+ )
+ .await;
+ let mut build = table.new_global_index_build_builder();
+ let mut options = HashMap::from([("ivf-flat.nlist".into(),
"1".into())]);
+ if !fixed {
+ options.insert("ivf-flat.dimension".into(), "2".into());
+ }
+ build
+ .with_index_column("chunks")
+ .with_index_type("ivf-flat")
+ .with_options(options);
+ assert_eq!(build.execute().await.unwrap(), 2);
+
+ let mut search = table.new_vector_search_builder();
+ let result = search
+ .with_vector_column("chunks")
+ .with_query_vector(vec![1.0, 0.0])
+ .with_limit(3)
+ .execute()
+ .await
+ .unwrap();
+ assert_eq!(result.row_ids().unwrap().row_ids, [0, 5, 1]);
+
+ search
+ .with_multi_vector(vec![vec![f32::MAX, 0.0], vec![0.0,
f32::MIN_POSITIVE]])
+ .with_limit(3);
+ let plan = search.new_scan().unwrap().plan().await.unwrap();
+ let result = search
+ .new_read()
+ .unwrap()
+ .read_with_executor(plan, &Worker(&table))
+ .await
+ .unwrap();
+ let scores = result.row_ids().unwrap();
+ assert_eq!(scores.row_ids, [5, 1, 0]);
+ assert_eq!(scores.scores, [2.0, 1.4, 1.0]);
+
+ // DETAIL adds a later row with no ANN file and uses the same matrix
scorer.
+ append_lists(
+ &table,
+ 7,
+ fixed,
+ &[Some(vec![Some([1.0, 1.0])]), None, Some(vec![])],
+ )
+ .await;
+ search.with_options(HashMap::from([(
+ "vector-index.search-mode".into(),
+ "detail".into(),
+ )]));
+ assert_eq!(
+ search.execute().await.unwrap().row_ids().unwrap().row_ids,
+ [5, 7, 1]
+ );
+ }
+}
+
+#[tokio::test]
+async fn multi_vector_post_filter_counts_only_live_candidate_rows() {
+ let path = "memory:/multivector_live_candidates";
+ let table = test_table_with_io(
+ FileIOBuilder::new("memory").build().unwrap(),
+ path,
+ list_schema(true),
+ )
+ .copy_with_options(HashMap::from([(
+ "deletion-vectors.enabled".into(),
+ "true".into(),
+ )]));
+ setup_dirs(table.file_io(), path).await;
+ append_lists(
+ &table,
+ 0,
+ true,
+ &[
+ Some(vec![Some([1.0, 0.0]); 8]),
+ Some(vec![Some([0.8, 0.6])]),
+ Some(vec![Some([0.0, 1.0])]),
+ ],
+ )
+ .await;
+ table
+ .new_global_index_build_builder()
+ .with_index_column("chunks")
+ .with_index_type("ivf-flat")
+ .with_options(HashMap::from([("ivf-flat.nlist".into(), "1".into())]))
+ .execute()
+ .await
+ .unwrap();
+ let writer = table.new_write_builder();
+ let update = writer.new_update().unwrap();
+ writer
+ .new_commit()
+ .commit(update.delete_by_row_id(vec![0]).await.unwrap())
+ .await
+ .unwrap();
+
+ let mut search = table.new_vector_search_builder();
+ search
+ .with_vector_column("chunks")
+ .with_multi_vector(vec![vec![1.0, 0.0]])
+ .with_limit(1)
+ .with_filter(
+ PredicateBuilder::new(table.schema().fields())
+ .equal("id", Datum::Int(2))
+ .unwrap(),
+ )
+ .with_options(HashMap::from([
+ ("refine_factor".into(), "1".into()),
+ (
+ "vector-index.post-filter.candidates-factor".into(),
+ "2".into(),
+ ),
+ ]));
+ let plan = search.new_scan().unwrap().plan().await.unwrap();
+ let reader = search.new_read().unwrap();
+ let local = reader.read(plan.clone()).await.unwrap();
+ let scheduled = reader
+ .read_with_executor(plan, &Worker(&table))
+ .await
+ .unwrap();
+ for result in [local, scheduled] {
+ assert_eq!(result.row_ids().unwrap().row_ids, [2]);
+ }
+}
+
+#[tokio::test]
+async fn multi_vector_declared_index_uses_cosine_without_a_metric_override() {
+ let path = "memory:/multivector_declared_cosine";
+ let table = test_table_with_io(
+ FileIOBuilder::new("memory").build().unwrap(),
+ path,
+ list_schema(true),
+ )
+ .copy_with_options(HashMap::from([
+ ("write-only".into(), "false".into()),
+ (
+ "global-index.ivf-flat.index-columns".into(),
+ "chunks".into(),
+ ),
+ ("ivf-flat.nlist".into(), "1".into()),
+ ]));
+ setup_dirs(table.file_io(), path).await;
+ table
+ .new_global_index_build_builder()
+ .with_index_column("chunks")
+ .with_index_type("ivf-flat")
+ .plan()
+ .await
+ .unwrap();
+ append_lists(
+ &table,
+ 0,
+ true,
+ &[Some(vec![Some([10.0, 10.0])]), Some(vec![Some([1.0, 0.0])])],
+ )
+ .await;
+ let result = table
+ .new_vector_search_builder()
+ .with_vector_column("chunks")
+ .with_multi_vector(vec![vec![1.0, 0.0]])
+ .with_limit(1)
+ .with_options(HashMap::from([(
+ "vector-index.search-mode".into(),
+ "fast".into(),
+ )]))
+ .execute()
+ .await
+ .unwrap();
+ assert_eq!(result.row_ids().unwrap().row_ids, [1]);
+ assert_eq!(result.row_ids().unwrap().scores, [1.0]);
+}
+
+#[tokio::test]
+async fn
multi_vector_refinement_keeps_distinct_single_and_matrix_candidate_scopes() {
+ let path = "memory:/multivector_refine_scope";
+ let table = test_table_with_io(
+ FileIOBuilder::new("memory").build().unwrap(),
+ path,
+ list_schema(true),
+ );
+ setup_dirs(table.file_io(), path).await;
+ for (id, coordinates) in [[1., 0.], [0., 1.], [1.,
1.]].into_iter().enumerate() {
+ append_lists(&table, id as i32, true,
&[Some(vec![Some(coordinates)])]).await;
+ }
+ assert_eq!(
+ table
+ .new_global_index_build_builder()
+ .with_index_column("chunks")
+ .with_index_type("ivf-flat")
+ .with_options(HashMap::from([
+ ("ivf-flat.nlist".into(), "1".into()),
+ ("global-index.row-count-per-shard".into(), "1".into()),
+ ]))
+ .execute()
+ .await
+ .unwrap(),
+ 3
+ );
+ let worker = RecordingWorker {
+ table: &table,
+ list_reads: Mutex::new(Vec::new()),
+ };
+ let options = HashMap::from([
+ ("refine_factor".into(), "1".into()),
+ ("vector-index.search-mode".into(), "fast".into()),
+ ]);
+ let mut search = table.new_batch_vector_search_builder();
+ search
+ .with_vector_column("chunks")
+ .with_query_vectors(vec![vec![1., 0.], vec![0., 1.]])
+ .with_limit(1)
+ .with_options(options.clone());
+ let plan = search.new_scan().unwrap().plan().await.unwrap();
+ let independent = search
+ .new_read()
+ .unwrap()
+ .read_with_executor(plan, &worker)
+ .await
+ .unwrap();
+ assert_eq!(independent[0].row_ids().unwrap().row_ids, [0]);
+ assert_eq!(independent[1].row_ids().unwrap().row_ids, [1]);
+ let selected_rows = |work: &[serde_json::Value]| {
+ let mut rows = std::collections::BTreeSet::new();
+ for payload in work {
+ let splits: Vec<DataSplit> =
serde_json::from_value(payload["splits"].clone()).unwrap();
+ for split in splits {
+ for range in split.row_ranges().unwrap() {
+ rows.extend(range.from()..=range.to());
+ }
+ }
+ }
+ rows.into_iter().collect::<Vec<_>>()
+ };
+ let work = std::mem::take(&mut *worker.list_reads.lock().unwrap());
+ assert_eq!(selected_rows(&work), [0, 1]);
+
+ let mut matrix = table.new_vector_search_builder();
+ matrix
+ .with_vector_column("chunks")
+ .with_multi_vector(vec![vec![1., 0.], vec![0., 1.]])
+ .with_limit(1)
+ .with_options(options);
+ let plan = matrix.new_scan().unwrap().plan().await.unwrap();
+ let read = matrix.new_read().unwrap();
+ let local = read.read(plan.clone()).await.unwrap();
+ let scheduled = read.read_with_executor(plan, &worker).await.unwrap();
+ assert_eq!(local.row_ids().unwrap().row_ids, [2]);
+ assert_eq!(scheduled.row_ids().unwrap().row_ids, [2]);
+ assert_eq!(
+ scheduled.row_ids().unwrap().scores,
+ local.row_ids().unwrap().scores
+ );
+ let work = worker.list_reads.lock().unwrap();
+ assert_eq!(selected_rows(&work), [0, 1, 2]);
+ assert!(work.iter().all(|payload| payload["queries"]["filters"]
+ .as_array()
+ .is_none_or(Vec::is_empty)));
+}
+
+#[tokio::test]
+async fn multi_vector_zero_scores_break_ties_by_row_id() {
+ let path = "memory:/multivector_zero_scores";
+ let table = test_table_with_io(
+ FileIOBuilder::new("memory").build().unwrap(),
+ path,
+ list_schema(true),
+ );
+ setup_dirs(table.file_io(), path).await;
+ append_lists(
+ &table,
+ 0,
+ true,
+ &[Some(vec![Some([0., -1.])]), Some(vec![Some([0., 1.])])],
+ )
+ .await;
+ table
+ .new_global_index_build_builder()
+ .with_index_column("chunks")
+ .with_index_type("ivf-flat")
+ .with_options(HashMap::from([("ivf-flat.nlist".into(), "1".into())]))
+ .execute()
+ .await
+ .unwrap();
+ let result = table
+ .new_vector_search_builder()
+ .with_vector_column("chunks")
+ .with_multi_vector(vec![vec![-1., 0.], vec![-2., 0.]])
+ .with_limit(1)
+ .execute()
+ .await
+ .unwrap();
+ let scores = result.row_ids().unwrap();
+ assert_eq!(scores.row_ids, [0]);
+ assert_eq!(scores.scores[0].to_bits(), 0.0_f32.to_bits());
+}
+
+#[tokio::test]
+async fn multi_vector_build_and_query_reject_invalid_options_and_shapes() {
+ let table = test_table_with_io(
+ FileIOBuilder::new("memory").build().unwrap(),
+ "memory:/multivector_invalid",
+ list_schema(false),
+ );
+ let mut build = table.new_global_index_build_builder();
+ build
+ .with_index_type("ivf-flat")
+ .with_index_column("chunks");
+ assert!(build
+ .plan()
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("dimension option"));
+ build.with_options(HashMap::from([
+ ("ivf-flat.dimension".into(), "2".into()),
+ ("ivf-flat.metric".into(), "l2".into()),
+ ]));
+ assert!(build
+ .plan()
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("cosine similarity"));
+ build.with_options(HashMap::from([
+ ("ivf-flat.dimension".into(), "2".into()),
+ ("ivf-flat.sharding".into(), "centroid".into()),
+ ]));
+ assert!(build
+ .plan()
+ .await
+ .unwrap_err()
+ .to_string()
+ .contains("range sharding"));
+
+ let mut search = table.new_vector_search_builder();
+ search.with_vector_column("chunks").with_limit(1);
+ for query in [
+ vec![],
+ vec![vec![1.0], vec![1.0, 2.0]],
+ vec![vec![f32::NAN, 0.0]],
+ ] {
+ search.with_multi_vector(query);
+ assert!(search.new_read().is_err());
+ }
+ let mut batch = table.new_batch_vector_search_builder();
+ batch
+ .with_vector_column("chunks")
+ .with_limit(1)
+ .with_query_vectors(vec![vec![1.0], vec![1.0, 2.0]]);
+ assert!(batch.new_read().is_err());
+}
diff --git a/crates/paimon/src/table/vindex_index_build_builder/tests.rs
b/crates/paimon/src/table/vindex_index_build_builder/tests.rs
index a8f0a9d7..edb5f904 100644
--- a/crates/paimon/src/table/vindex_index_build_builder/tests.rs
+++ b/crates/paimon/src/table/vindex_index_build_builder/tests.rs
@@ -1652,3 +1652,6 @@ mod sparse_tests;
#[path = "centroid_tests.rs"]
mod centroid_tests;
+
+#[path = "multi_vector_tests.rs"]
+mod multi_vector_tests;
diff --git a/crates/paimon/src/table/vindex_index_build_builder/validation.rs
b/crates/paimon/src/table/vindex_index_build_builder/validation.rs
index 76ecf381..cbe16b1d 100644
--- a/crates/paimon/src/table/vindex_index_build_builder/validation.rs
+++ b/crates/paimon/src/table/vindex_index_build_builder/validation.rs
@@ -28,7 +28,11 @@ pub(super) fn find_index_field<'a>(table: &'a Table, column:
&str) -> Result<&'a
}
pub(super) fn validate_vector_field(field: &DataField) -> Result<()> {
- validate_common_vector_field(field, "vindex")
+ if
crate::vindex::multi_vector::embedding_type(field.data_type()).is_some() {
+ Ok(())
+ } else {
+ validate_common_vector_field(field, "vindex")
+ }
}
pub(super) use crate::table::index_build::vector_validation::*;
diff --git a/crates/paimon/src/table/vindex_index_build_builder/writer.rs
b/crates/paimon/src/table/vindex_index_build_builder/writer.rs
index 661e730f..520d4d3c 100644
--- a/crates/paimon/src/table/vindex_index_build_builder/writer.rs
+++ b/crates/paimon/src/table/vindex_index_build_builder/writer.rs
@@ -61,7 +61,7 @@ impl<'a> VindexIndexBuildBuilder<'a> {
message: "vindex row count does not fit usize".into(),
source: Some(Box::new(error)),
})?;
- let use_granule = self.index_type != DISKANN_IDENTIFIER
+ let use_granule = !options.multi_vector && self.index_type !=
DISKANN_IDENTIFIER
&& options.granule_build_enabled
&& !options.needs_vector_count()
// Invalid training options still produce no file for an all-NULL
@@ -139,7 +139,8 @@ impl<'a> VindexIndexBuildBuilder<'a> {
let mut spill = VectorSpill::new(
RowRange::new(shard.row_range_start, shard.row_range_end),
dimension_usize,
- )?;
+ )?
+ .with_multi_vector(options.multi_vector);
let split = data_split_for_shard(shard)?;
let mut read_builder = self.table.new_read_builder();
read_builder.with_projection(&[index_column, ROW_ID_FIELD_NAME])?;
diff --git a/crates/paimon/src/vindex/mod.rs b/crates/paimon/src/vindex/mod.rs
index edaa8196..0ba70a34 100644
--- a/crates/paimon/src/vindex/mod.rs
+++ b/crates/paimon/src/vindex/mod.rs
@@ -16,6 +16,7 @@
// under the License.
pub(crate) mod executor;
+pub(crate) mod multi_vector;
pub(crate) mod range_reader;
pub mod reader;
@@ -113,6 +114,7 @@ pub(crate) struct VindexVectorIndexOptions {
pub native_options: HashMap<String, String>,
pub train_sample_ratio: f64,
pub granule_build_enabled: bool,
+ pub(crate) multi_vector: bool,
}
impl VindexVectorIndexOptions {
@@ -138,6 +140,7 @@ impl VindexVectorIndexOptions {
index_type: &str,
field: &DataField,
) -> crate::Result<Self> {
+ let list = multi_vector::embedding_type(field.data_type());
let mut native_options = Self::resolve_native_options(
table_options,
defaults,
@@ -145,8 +148,26 @@ impl VindexVectorIndexOptions {
index_type,
field.name(),
)?;
- let dimension = match field.data_type() {
+ let metric = native_options.entry("metric".into()).or_insert_with(|| {
+ if list.is_some() {
+ "cosine".into()
+ } else {
+ DEFAULT_METRIC.into()
+ }
+ });
+ *metric = normalize_metric(metric);
+ if list.is_some() && metric != "cosine" {
+ return Err(multi_vector::invalid(
+ "MultiVector indexes require cosine similarity",
+ ));
+ }
+ let dimension = match list.unwrap_or(field.data_type()) {
DataType::Vector(vector) => vector.length().to_string(),
+ DataType::Array(_) if list.is_some() => {
+ native_options.get("dimension").cloned().ok_or_else(|| {
+ multi_vector::invalid("ARRAY<ARRAY<FLOAT>> indexes require
a dimension option")
+ })?
+ }
_ => native_options
.get("dimension")
.cloned()
@@ -180,6 +201,7 @@ impl VindexVectorIndexOptions {
native_options,
train_sample_ratio,
granule_build_enabled,
+ multi_vector: list.is_some(),
})
}
@@ -215,11 +237,6 @@ impl VindexVectorIndexOptions {
collect_native_options(&mut native_options, defaults, index_type,
column, true)?;
collect_native_options(&mut native_options, user_options, index_type,
column, true)?;
native_options.insert("index.type".into(), native_index_type.into());
- let metric = native_options
- .entry("metric".into())
- .or_insert_with(|| DEFAULT_METRIC.into());
- *metric = normalize_metric(metric);
-
Ok(native_options)
}
diff --git a/crates/paimon/src/vindex/multi_vector.rs
b/crates/paimon/src/vindex/multi_vector.rs
new file mode 100644
index 00000000..58686aeb
--- /dev/null
+++ b/crates/paimon/src/vindex/multi_vector.rs
@@ -0,0 +1,174 @@
+// 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.
+
+//! Shared schema, Arrow and cosine semantics for embedding-list columns.
+
+use crate::spec::DataType;
+use crate::{Error, Result};
+use arrow_array::{Array, FixedSizeListArray, Float32Array, ListArray};
+
+/// An ARRAY of variable or fixed-width FLOAT embeddings.
+pub(crate) fn embedding_type(data_type: &DataType) -> Option<&DataType> {
+ let DataType::Array(array) = data_type else {
+ return None;
+ };
+ let inner = array.element_type();
+ let is_embedding = match inner {
+ DataType::Vector(vector) => matches!(vector.element_type(),
DataType::Float(_)),
+ DataType::Array(array) => matches!(array.element_type(),
DataType::Float(_)),
+ _ => false,
+ };
+ is_embedding.then_some(inner)
+}
+
+pub(crate) fn validate_queries(queries: &[&[f32]], width: Option<usize>) ->
Result<()> {
+ let dimension = queries.first().map_or(0, |query| query.len());
+ if dimension == 0
+ || width.is_some_and(|width| width != dimension)
+ || queries.iter().any(|vector| {
+ vector.len() != dimension || vector.iter().any(|coordinate|
!coordinate.is_finite())
+ })
+ {
+ return Err(invalid(
+ "MultiVector queries require at least one vector with a
consistent, positive dimension and finite coordinates",
+ ));
+ }
+ Ok(())
+}
+
+pub(crate) fn normalize_into(vector: &[f32], output: &mut Vec<f32>) {
+ let norm = norm(vector);
+ let scale = if norm == 0.0 { 1.0 } else { 1.0 / norm };
+ output.extend(
+ vector
+ .iter()
+ .map(|value| (f64::from(*value) * scale) as f32),
+ );
+}
+
+pub(crate) fn norm(vector: &[f32]) -> f64 {
+ vector
+ .iter()
+ .map(|&value| f64::from(value) * f64::from(value))
+ .sum::<f64>()
+ .sqrt()
+}
+
+pub(crate) fn cosine(query: &[f32], query_norm: f64, vector: &[f32],
vector_norm: f64) -> f64 {
+ let denominator = query_norm * vector_norm;
+ if denominator == 0.0 {
+ return 0.0;
+ }
+ vector.iter().zip(query).fold(0.0, |sum, (&left, &right)| {
+ sum + f64::from(left) * f64::from(right)
+ }) / denominator
+}
+
+enum Embeddings<'a> {
+ Array(&'a ListArray),
+ Vector(&'a FixedSizeListArray),
+}
+
+pub(crate) struct MultiVectorArray<'a> {
+ rows: &'a ListArray,
+ embeddings: Embeddings<'a>,
+ values: &'a Float32Array,
+}
+
+impl<'a> MultiVectorArray<'a> {
+ pub(crate) fn new(column: &'a dyn Array) -> Result<Self> {
+ let rows = column
+ .as_any()
+ .downcast_ref::<ListArray>()
+ .ok_or_else(|| invalid("MultiVector columns require an Arrow
ListArray"))?;
+ let inner = rows.values().as_any();
+ let (embeddings, coordinates) = if let Some(list) =
inner.downcast_ref::<ListArray>() {
+ (Embeddings::Array(list), list.values())
+ } else if let Some(list) = inner.downcast_ref::<FixedSizeListArray>() {
+ (Embeddings::Vector(list), list.values())
+ } else {
+ return Err(invalid(
+ "MultiVector embeddings must be Arrow Lists or FixedSizeLists",
+ ));
+ };
+ let values = coordinates
+ .as_any()
+ .downcast_ref::<Float32Array>()
+ .ok_or_else(|| invalid("MultiVector coordinates must be
Float32"))?;
+ Ok(Self {
+ rows,
+ embeddings,
+ values,
+ })
+ }
+
+ /// Null lists and null embeddings represent no vectors. Only validate
+ /// coordinates belonging to this visible row, including on sliced batches.
+ pub(crate) fn row(
+ &self,
+ row: usize,
+ dimension: usize,
+ ) -> impl Iterator<Item = Result<&'a [f32]>> + '_ {
+ let offsets = self.rows.value_offsets();
+ let start = offsets[row] as usize;
+ let end = if self.rows.is_null(row) {
+ start
+ } else {
+ offsets[row + 1] as usize
+ };
+ (start..end).filter_map(move |index| {
+ let (start, end) = match self.embeddings {
+ Embeddings::Array(list) => {
+ if list.is_null(index) {
+ return None;
+ }
+ let offsets = list.value_offsets();
+ (offsets[index] as usize, offsets[index + 1] as usize)
+ }
+ Embeddings::Vector(list) => {
+ if list.is_null(index) {
+ return None;
+ }
+ let start = list.value_offset(index) as usize;
+ (start, start + list.value_length() as usize)
+ }
+ };
+ if end - start != dimension {
+ return Some(Err(invalid(format!(
+ "MultiVector dimension mismatch: expected {dimension}, got
{}",
+ end - start
+ ))));
+ }
+ let values = &self.values.values()[start..end];
+ if (self.values.null_count() != 0 && (start..end).any(|i|
self.values.is_null(i)))
+ || values.iter().any(|coordinate| !coordinate.is_finite())
+ {
+ return Some(Err(invalid(
+ "MultiVector coordinates must be non-null and finite",
+ )));
+ }
+ Some(Ok(values))
+ })
+ }
+}
+
+pub(crate) fn invalid(message: impl Into<String>) -> Error {
+ Error::DataInvalid {
+ message: message.into(),
+ source: None,
+ }
+}
diff --git a/crates/paimon/src/vindex/reader.rs
b/crates/paimon/src/vindex/reader.rs
index a203fe76..f2629fdd 100644
--- a/crates/paimon/src/vindex/reader.rs
+++ b/crates/paimon/src/vindex/reader.rs
@@ -19,8 +19,8 @@ use crate::vector_search::{GlobalIndexIOMeta, VectorSearch};
use crate::vindex::vector_search_timing_enabled;
use paimon_vindex_core::distance::MetricType;
use paimon_vindex_core::index::{
- IndexType, VectorIndexMetadata, VectorIndexReader as VIndexReader,
VectorIndexReaderOptions,
- VectorSearchParams,
+ IndexType, SearchWidth, VectorIndexMetadata, VectorIndexReader as
VIndexReader,
+ VectorIndexReaderOptions, VectorSearchParams,
};
use paimon_vindex_core::io::{ReadRequest, SeekRead, SeekReadCapabilities};
use std::collections::BinaryHeap;
@@ -163,6 +163,7 @@ pub struct VindexVectorGlobalIndexReader {
io_meta: GlobalIndexIOMeta,
options: HashMap<String, String>,
batch_index_parallelism: usize,
+ list_row_count: Option<u64>,
reader: Option<VIndexReader<VindexInput>>,
metadata: Option<VectorIndexMetadata>,
timing_enabled: bool,
@@ -176,6 +177,7 @@ impl VindexVectorGlobalIndexReader {
io_meta,
options,
batch_index_parallelism: 1,
+ list_row_count: None,
reader: None,
metadata: None,
timing_enabled: vector_search_timing_enabled(),
@@ -189,6 +191,11 @@ impl VindexVectorGlobalIndexReader {
self
}
+ pub(crate) fn with_list_row_count(mut self, row_count: Option<u64>) ->
Self {
+ self.list_row_count = row_count;
+ self
+ }
+
pub fn visit_vector_search<S: SeekRead + 'static>(
&mut self,
vector_search: &VectorSearch,
@@ -302,6 +309,24 @@ impl VindexVectorGlobalIndexReader {
message: "vindex metadata not initialized".to_string(),
source: None,
})?;
+ if let Some(row_count) = self.list_row_count {
+ if metadata.metric != MetricType::Cosine {
+ return Err(super::multi_vector::invalid(
+ "MultiVector indexes require cosine similarity",
+ ));
+ }
+ let prepared = prepare_batch_searches(metadata, &self.options,
vector_searches, true)?;
+ return vector_searches
+ .iter()
+ .zip(prepared)
+ .map(|(query, prepared)| match prepared {
+ Some(prepared) => {
+ search_distinct_rows(reader, metadata, query,
row_count, prepared)
+ }
+ None => Ok(None),
+ })
+ .collect();
+ }
let (results, batch_stats) = search_batch_vindex(
reader,
metadata,
@@ -411,7 +436,7 @@ fn search_vindex(
let Some(prepared) = prepare_search(metadata, options, vector_search)?
else {
return Ok(None);
};
- let (labels, distances) = execute_scalar_search(reader, vector_search,
&prepared)?;
+ let (labels, distances) = execute_scalar_search(reader,
&vector_search.vector, &prepared)?;
let id_to_scores = collect_results(&labels, &distances,
prepared.params.top_k, metadata.metric);
if id_to_scores.is_empty() {
return Ok(None);
@@ -445,7 +470,7 @@ fn prepare_search(
options: &HashMap<String, String>,
vector_search: &VectorSearch,
) -> crate::Result<Option<PreparedSearch>> {
- prepare_search_with_shared_filter(metadata, options, vector_search, None)
+ prepare_search_with_shared_filter(metadata, options, vector_search, None,
false)
}
fn prepare_search_with_shared_filter(
@@ -453,6 +478,7 @@ fn prepare_search_with_shared_filter(
options: &HashMap<String, String>,
vector_search: &VectorSearch,
shared_filter_bytes: Option<&Arc<[u8]>>,
+ multi_vector: bool,
) -> crate::Result<Option<PreparedSearch>> {
// Query options override the defaults of a reusable index reader.
let mut merged_options;
@@ -479,10 +505,17 @@ fn prepare_search_with_shared_filter(
if top_k == 0 {
return Ok(None);
}
- let mut params = match (
+ let (nprobe, l_search) = (
options.get(NPROBE_PARAMETER),
options.get(L_SEARCH_PARAMETER),
- ) {
+ );
+ // MultiVector uses the width for the shard's actual algorithm, as Java
does.
+ let (nprobe, l_search) = match (multi_vector, metadata.index_type) {
+ (true, IndexType::DiskAnn) => (None, l_search),
+ (true, _) => (nprobe, None),
+ (false, _) => (nprobe, l_search),
+ };
+ let mut params = match (nprobe, l_search) {
(Some(_), Some(_)) => {
return Err(crate::Error::DataInvalid {
message: format!(
@@ -558,6 +591,7 @@ fn prepare_batch_searches(
metadata: &VectorIndexMetadata,
options: &HashMap<String, String>,
vector_searches: &[VectorSearch],
+ multi_vector: bool,
) -> crate::Result<Vec<Option<PreparedSearch>>> {
let shared_filter_bytes = shared_batch_include_row_ids(vector_searches)
.filter(|include_row_ids| !include_row_ids.is_empty())
@@ -571,6 +605,7 @@ fn prepare_batch_searches(
options,
search,
shared_filter_bytes.as_ref(),
+ multi_vector,
)
})
.collect()
@@ -578,28 +613,149 @@ fn prepare_batch_searches(
fn execute_scalar_search(
reader: &mut VIndexReader<impl SeekRead>,
- vector_search: &VectorSearch,
+ vector: &[f32],
prepared: &PreparedSearch,
) -> crate::Result<(Vec<i64>, Vec<f32>)> {
let params = prepared.params;
match &prepared.filter_bytes {
Some(filter) => reader
- .search_with_roaring_filter(&vector_search.vector, params, filter)
+ .search_with_roaring_filter(vector, params, filter)
.map_err(|e| crate::Error::DataInvalid {
message: format!("paimon-vindex-core filtered search failed:
{}", e),
source: Some(Box::new(e)),
}),
- None => {
- reader
- .search(&vector_search.vector, params)
- .map_err(|e| crate::Error::DataInvalid {
- message: format!("paimon-vindex-core search failed: {}",
e),
- source: Some(Box::new(e)),
- })
- }
+ None => reader
+ .search(vector, params)
+ .map_err(|e| crate::Error::DataInvalid {
+ message: format!("paimon-vindex-core search failed: {}", e),
+ source: Some(Box::new(e)),
+ }),
}
}
+/// Some native algorithms return Top-K embeddings. Page through unseen row
+/// labels so several hits from one document cannot consume its neighbors'
slots.
+fn search_distinct_rows(
+ reader: &mut VIndexReader<impl SeekRead>,
+ metadata: &VectorIndexMetadata,
+ query: &VectorSearch,
+ row_count: u64,
+ mut prepared: PreparedSearch,
+) -> crate::Result<Option<HashMap<u64, f32>>> {
+ super::multi_vector::validate_queries(&[&query.vector],
Some(metadata.dimension))?;
+ let limit = prepared.params.top_k;
+ let vectors = usize::try_from(metadata.total_vectors).unwrap_or(0);
+ let mut normalized = Vec::with_capacity(query.vector.len());
+ super::multi_vector::normalize_into(&query.vector, &mut normalized);
+ let mut scores = HashMap::<u64, f32>::new();
+ let include = query.effective_include_row_ids();
+ let initial_params = prepared.params;
+ let graph_hits = if include.is_none() && metadata.index_type ==
IndexType::DiskAnn {
+ initial_params
+ .configured_diskann_l_search()
+ .unwrap_or_else(|| limit.saturating_mul(2).max(100))
+ .min(vectors)
+ .min(i32::MAX as usize)
+ } else {
+ 0
+ };
+ let mut remaining = None;
+ let mut requested = limit;
+ loop {
+ prepared.params.top_k = requested;
+ let expected = remaining
+ .as_ref()
+ .or(include)
+ .map_or(requested, |ids| requested.min(ids.len() as usize));
+ let (ids, distances) = execute_scalar_search(reader, &normalized,
&prepared)?;
+ let previous_count = scores.len();
+ let mut hits = 0;
+ for (id, distance) in ids.into_iter().zip(distances) {
+ if id >= 0 {
+ let id = id as u64;
+ if id >= row_count {
+ return Err(super::multi_vector::invalid(
+ "MultiVector index label is outside its row range",
+ ));
+ }
+ let score = 1.0 - distance;
+ scores
+ .entry(id)
+ .and_modify(|previous| *previous = previous.max(score))
+ .or_insert(score);
+ if let Some(remaining) = &mut remaining {
+ remaining.remove(id);
+ }
+ hits += 1;
+ }
+ }
+
+ let used_graph_retry = remaining.is_none() && requested == graph_hits
&& graph_hits > limit;
+ if scores.len() >= limit || (!used_graph_retry && hits < expected) ||
hits == vectors {
+ break;
+ }
+
+ let mut added = scores.len() - previous_count;
+ if remaining.is_none() {
+ // DiskANN treats an exclusion bitmap as a filtered scan. First try
+ // taking more embeddings from the configured graph frontier.
+ if requested < graph_hits {
+ requested = graph_hits;
+ prepared.params =
VectorSearchParams::with_l_search(graph_hits, graph_hits);
+ continue;
+ }
+ if include.is_none() && row_count >> 16 > vectors as u64 {
+ // A filter spanning an exceptionally sparse range can cost
+ // more than widening the native search itself.
+ let next = requested
+ .saturating_mul(2)
+ .min(vectors)
+ .min(i32::MAX as usize);
+ if next == requested {
+ break;
+ }
+ requested = next;
+ continue;
+ }
+ let mut ids = match include {
+ Some(ids) => ids.clone(),
+ None => {
+ let mut ids = roaring::RoaringTreemap::new();
+ ids.insert_range(0..row_count);
+ ids
+ }
+ };
+ for &id in scores.keys() {
+ ids.remove(id);
+ }
+ added = scores.len();
+ remaining = Some(ids);
+ prepared.params = initial_params;
+ if include.is_none()
+ && metadata.index_type != IndexType::DiskAnn
+ && prepared.params.search_width == SearchWidth::Auto
+ {
+ // Excluded labels are already collected. Their cardinality
+ // should not inflate the initial IVF probe count.
+ prepared.params =
prepared.params.with_max_initial_filter_expansion_factor(1);
+ }
+ }
+ let remaining = remaining.as_ref().expect("remaining rows
initialized");
+ let missing = (limit - scores.len()).min(remaining.len() as usize);
+ if added == 0 || missing == 0 {
+ break;
+ }
+ const MAX_RETRY_HITS: usize = 16_384;
+ requested = (missing as u128 * hits.max(added) as u128)
+ .div_ceil(added as u128)
+ .min(requested.saturating_mul(2) as u128)
+ .min(vectors.min(limit.max(MAX_RETRY_HITS)) as u128) as usize;
+ prepared.filter_bytes = Some(serialize_row_id_filter(remaining)?);
+ }
+ let top =
crate::vector_search::ScoredRowIds::from_scored_map(scores).top_k(limit);
+ Ok((!top.row_ids.is_empty()).then(||
top.row_ids.into_iter().zip(top.scores).collect()))
+}
+
fn search_batch_vindex(
reader: &mut VIndexReader<impl SeekRead>,
metadata: &VectorIndexMetadata,
@@ -617,7 +773,7 @@ fn search_batch_vindex(
..VindexBatchStats::default()
});
- for (index, prepared) in prepare_batch_searches(metadata, options,
vector_searches)?
+ for (index, prepared) in prepare_batch_searches(metadata, options,
vector_searches, false)?
.into_iter()
.enumerate()
{
@@ -646,7 +802,7 @@ fn search_batch_vindex(
}
let index = indices[0];
let (labels, distances) =
- execute_scalar_search(reader, &vector_searches[index],
&prepared)?;
+ execute_scalar_search(reader,
&vector_searches[index].vector, &prepared)?;
let map =
collect_results(&labels, &distances,
prepared.params.top_k, metadata.metric);
if !map.is_empty() {
@@ -929,6 +1085,7 @@ mod tests {
use paimon_vindex_core::diskann_io::DiskAnnHeader;
use paimon_vindex_core::index::{VectorIndexConfig, VectorIndexTrainer,
VectorIndexWriter};
use paimon_vindex_core::io::{PosWriter, SeekReadCapabilities};
+ use paimon_vindex_core::ivfflat::IVFFlatIndex;
use std::cell::Cell;
use std::io::Cursor;
use std::ops::Range;
@@ -1123,7 +1280,8 @@ mod tests {
};
let defaults = HashMap::from([(NPROBE_PARAMETER.into(), "1".into())]);
let explicit =
query().with_options(HashMap::from([(NPROBE_PARAMETER.into(), "7".into())]));
- let prepared = prepare_batch_searches(&metadata, &defaults,
&[explicit, query()]).unwrap();
+ let prepared =
+ prepare_batch_searches(&metadata, &defaults, &[explicit, query()],
false).unwrap();
assert_eq!(prepared[0].as_ref().unwrap().params.width, 7);
assert_eq!(prepared[1].as_ref().unwrap().params.width, 1);
let conflicting =
@@ -1258,7 +1416,8 @@ mod tests {
search.set_shared_include_row_ids(Arc::clone(&shared_filter));
}
- let prepared = prepare_batch_searches(&metadata, &HashMap::new(),
&searches).unwrap();
+ let prepared =
+ prepare_batch_searches(&metadata, &HashMap::new(), &searches,
false).unwrap();
let first = prepared[0]
.as_ref()
.and_then(|search| search.filter_bytes.as_ref())
@@ -1406,10 +1565,24 @@ mod tests {
("diskann.l_search".to_string(), "64".to_string()),
]);
assert!(prepare_search(&metadata, &mixed_options, &query()).is_err());
+ let diskann = prepare_batch_searches(&metadata, &mixed_options,
&[query()], true).unwrap();
+ assert_eq!(
+ diskann[0]
+ .as_ref()
+ .unwrap()
+ .params
+ .configured_diskann_l_search(),
+ Some(64)
+ );
let mut ivf_metadata = metadata;
ivf_metadata.index_type = IndexType::IvfFlat;
assert!(prepare_search(&ivf_metadata, &mixed_options,
&query()).is_err());
+ let ivf = prepare_batch_searches(&ivf_metadata, &mixed_options,
&[query()], true).unwrap();
+ assert_eq!(
+ ivf[0].as_ref().unwrap().params.configured_ivf_nprobe(),
+ Some(4)
+ );
}
#[test]
@@ -1448,6 +1621,129 @@ mod tests {
assert_eq!(explicit.params.width, 32);
}
+ #[test]
+ fn multi_vector_diskann_keeps_duplicate_label_retry_on_the_graph() {
+ let dimension = 8;
+ let mut vectors = Vec::new();
+ let mut labels = Vec::new();
+ for id in 0..32 {
+ let angle = std::f32::consts::PI * id as f32 / 32.0;
+ let mut vector = [0.0; 8];
+ (vector[1], vector[0]) = angle.sin_cos();
+ for _ in 0..if id == 0 { 8 } else { 1 } {
+ vectors.extend_from_slice(&vector);
+ labels.push(id);
+ }
+ }
+ let config = VectorIndexConfig::DiskAnn {
+ dimension,
+ metric: MetricType::Cosine,
+ pq_m: 2,
+ pq_bits: 4,
+ build: DiskAnnBuildParams {
+ max_degree: 8,
+ build_search_list_size: 32,
+ ..DiskAnnBuildParams::default()
+ },
+ pq_train_max_points_per_centroid: 256,
+ };
+ let training = VectorIndexTrainer::train(config, &vectors,
labels.len()).unwrap();
+ let mut writer = VectorIndexWriter::new(training);
+ writer.add_vectors(&labels, &vectors, labels.len()).unwrap();
+ let mut index = Vec::new();
+ writer.write(&mut PosWriter::new(&mut index)).unwrap();
+ let query =
+ VectorSearch::new(vectors[..dimension].to_vec(), 2,
"embedding".into()).unwrap();
+
+ let mut reader = VIndexReader::open(Cursor::new(index)).unwrap();
+ let metadata = reader.metadata();
+ let params = VectorSearchParams::with_l_search(query.limit, 64);
+ assert_eq!(reader.search(&query.vector, params).unwrap().0, [0, 0]);
+
+ let prepared = PreparedSearch {
+ params,
+ filter_bytes: None,
+ };
+ let hits = search_distinct_rows(&mut reader, &metadata, &query, 32,
prepared)
+ .unwrap()
+ .unwrap();
+ assert_eq!(hits.len(), 2);
+ assert!(hits.contains_key(&0));
+ assert_eq!(
+ reader
+ .diskann_search_stats()
+ .unwrap()
+ .filtered_exhaustive_queries,
+ 0
+ );
+ }
+
+ #[test]
+ fn multi_vector_ivf_continuation_does_not_inflate_automatic_probes() {
+ struct CountedInput<'a>(Cursor<Vec<u8>>, &'a AtomicUsize);
+
+ impl SeekRead for CountedInput<'_> {
+ fn pread(&mut self, ranges: &mut [ReadRequest<'_>]) ->
io::Result<()> {
+ self.1.fetch_add(
+ ranges.iter().map(|range| range.buf.len()).sum(),
+ Ordering::Relaxed,
+ );
+ self.0.pread(ranges)
+ }
+ }
+
+ let rows = 64;
+ let embeddings_per_row = 8;
+ let centroids = (0..rows)
+ .flat_map(|row| {
+ let (sin, cos) = (std::f32::consts::TAU * row as f32 / rows as
f32).sin_cos();
+ [cos, sin]
+ })
+ .collect::<Vec<_>>();
+ let mut vectors = Vec::new();
+ let mut labels = Vec::new();
+ for (row, centroid) in centroids.as_chunks::<2>().0.iter().enumerate()
{
+ for _ in 0..embeddings_per_row {
+ vectors.extend_from_slice(centroid);
+ labels.push(row as i64);
+ }
+ }
+ let mut writer = IVFFlatIndex::new(2, rows, MetricType::Cosine);
+ writer.set_quantizer_centroids(centroids);
+ let mut writer = VectorIndexWriter::IvfFlat(writer);
+ writer.add_vectors(&labels, &vectors, labels.len()).unwrap();
+ let mut index = Vec::new();
+ writer.write(&mut PosWriter::new(&mut index)).unwrap();
+ let bytes_read = AtomicUsize::new(0);
+ let mut reader = VIndexReader::open(CountedInput(Cursor::new(index),
&bytes_read)).unwrap();
+ let metadata = reader.metadata();
+ let query = VectorSearch::new(vec![1.0, 0.0], 2,
"embedding".into()).unwrap();
+ let prepared = prepare_search(&metadata, &HashMap::new(), &query)
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ reader.search(&query.vector, prepared.params).unwrap().0,
+ [0, 0]
+ );
+ bytes_read.store(0, Ordering::Relaxed);
+ let params = prepared.params;
+ let hits = search_distinct_rows(&mut reader, &metadata, &query, rows
as u64, prepared)
+ .unwrap()
+ .unwrap();
+ assert_eq!(hits.len(), 2);
+ assert!(hits.contains_key(&0));
+ let capped_bytes = bytes_read.swap(0, Ordering::Relaxed);
+ let filter = serialize_row_id_filter(&(1..rows as
u64).collect()).unwrap();
+ reader
+ .search_with_roaring_filter(&query.vector, params, &filter)
+ .unwrap();
+ let uncapped_bytes = bytes_read.load(Ordering::Relaxed);
+ assert!(
+ capped_bytes < uncapped_bytes,
+ "read {capped_bytes} vs {uncapped_bytes} bytes"
+ );
+ }
+
#[test]
fn diskann_reader_enforces_configured_memory_budget_during_optimization() {
let header = DiskAnnHeader::for_layout(
diff --git a/docs/src/sql.md b/docs/src/sql.md
index c414573f..9917017f 100644
--- a/docs/src/sql.md
+++ b/docs/src/sql.md
@@ -2948,7 +2948,7 @@ SELECT * FROM vector_search('table_name', 'column_name',
'query_vector_json', li
|---|---|---|
| `table_name` | STRING | Table name, fully qualified (`catalog.db.table`) or
short form |
| `column_name` | STRING | The vector column to search |
-| `query_vector_json` | STRING | Query vector as a JSON array of floats |
+| `query_vector_json` | STRING | JSON vector, or a matrix of floats for an
embedding-list column |
| `limit` | INT | Maximum number of results (top-k) |
Example:
@@ -2989,6 +2989,29 @@ Automatic inner-product routing searches all centroids.
The layout is stored
in the index manifest and is available when searching Java-built indexes.
The current native DiskANN reader supports up to 1,024 dimensions.
+### MultiVector MaxSim
+
+On Data Evolution append tables, a range-sharded cosine index can search an
+`ARRAY<VECTOR<FLOAT, d>>` or `ARRAY<ARRAY<FLOAT>>` column. Give the second
type an
+explicit embedding dimension when building the index. Each row can contain a
+different number of embeddings. Null elements are ignored, and rows without
+embeddings have no score.
+
+```sql
+SELECT id
+FROM vector_search('paimon.my_db.documents', 'chunks', '[[1.0, 0.0], [0.0,
1.0]]', 10);
+
+CALL sys.vector_search('my_db.documents', 'chunks', '[[1.0, 0.0], [0.0,
1.0]]', 10, 'id');
+```
+
+For each query vector, MaxSim takes the best cosine similarity over a row's
+embeddings and sums the scores across the matrix. ANN retrieves distinct row
+candidates for each query vector and the union is reranked using the full
+embedding lists. The default matrix candidate multiplier is four. A single
+query vector uses its best matching embedding and a default multiplier of
+one. Set `refine_factor` to override the multiplier. The Rust and Python
+single-search builders expose `with_multi_vector` for a query matrix.
+
### Scalar Pre-Filters
Add a `WHERE` clause to restrict the rows returned by vector Top-K: