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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions bindings/python/src/vector_search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ use paimon::table::{
VectorSearchBuilder,
};
use paimon_datafusion::runtime::runtime;
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyTuple};
use pyo3::types::PyDict;

use crate::error::to_py_err;
use crate::global_index_result::PyGlobalIndexResult;
Expand Down Expand Up @@ -292,12 +293,20 @@ impl PyVectorScanPlan {
vector_splits_to_python(py, self.inner.splits())
}

fn __reduce__(slf: &Bound<'_, Self>, py: Python<'_>) -> PyResult<(Py<PyAny>, Py<PyTuple>)> {
let plan = slf.borrow();
let args = (plan.splits(py)?, plan.snapshot())
.into_pyobject(py)?
.unbind();
Ok((slf.get_type().unbind().into_any(), args))
#[staticmethod]
fn _from_json(value: &str) -> PyResult<Self> {
let inner = serde_json::from_str(value).map_err(|error| {
PyValueError::new_err(format!("Invalid vector search plan: {error}"))
})?;
Ok(Self { inner })
}

fn __reduce__(slf: &Bound<'_, Self>) -> PyResult<(Py<PyAny>, (String,))> {
let value = serde_json::to_string(&slf.borrow().inner).map_err(|error| {
PyValueError::new_err(format!("Cannot serialize vector search plan: {error}"))
})?;
let restore = slf.get_type().getattr("_from_json")?.unbind();
Ok((restore, (value,)))
}
}

Expand Down
29 changes: 29 additions & 0 deletions bindings/python/tests/test_vector_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,35 @@ def test_scan_read_keeps_snapshot_and_is_reusable(table):
assert rows.column('id').to_pylist() == [1]


def test_centroid_bitmap_plan_keeps_scalar_coverage_when_pickled(table):
import pickle

table = table.copy({'vector-index.search-mode': 'fast',
'scalar-index.prefilter.search-mode': 'full'})
pt0 = {'method': 'equal', 'field': 'pt', 'literals': [0]}
pt1 = {'method': 'equal', 'field': 'pt', 'literals': [1]}
ivf = {'ivf-flat.dimension': '2', 'ivf-flat.nlist': '1', 'ivf-flat.metric': 'l2'}
(table.new_global_index_build_builder().with_index_column('embedding')
.with_index_type('ivf-flat').with_partition_filter(pt0).with_options({
**ivf, 'ivf-flat.sharding': 'centroid', 'ivf-flat.centroid.nlist': '2',
'extra_fields': '{"id":"bitmap"}',
}).execute())
(table.new_global_index_build_builder().with_index_column('embedding')
.with_index_type('ivf-flat').with_partition_filter(pt1).with_options(ivf).execute())
(table.new_global_index_build_builder().with_index_column('id')
.with_index_type('btree').with_partition_filter(pt1).execute())

builder = (_single(table).with_limit(1).with_option('centroid.nprobe', '1')
.with_filter({'method': 'equal', 'field': 'id', 'literals': [2]}))
plan = builder.new_vector_search_scan().scan()
reader = builder.new_vector_search_read()
assert len(reader.read_plan(plan)) == 0
assert len(reader.read_plan(pickle.loads(pickle.dumps(plan)))) == 0

explicit = type(plan)(plan.splits(), plan.snapshot())
assert len(reader.read_plan(explicit)) == 1


def test_batch_order_empty_results_and_scan_reuse(table):
queries = [[1, 0], [0, 1], [1, 0]]
builder = (table.new_batch_vector_search_builder().with_vector_column('embedding')
Expand Down
13 changes: 10 additions & 3 deletions crates/integrations/datafusion/src/procedures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ fn declared_parameters(proc_name: &str) -> Option<&'static [&'static str]> {
"index_type",
"partitions",
"options",
"extra_fields",
],
"drop_global_index" => &[
"table",
Expand Down Expand Up @@ -1399,9 +1400,15 @@ async fn proc_create_global_index(
builder
.with_index_column(index_column)
.with_index_type(index_type_arg);
if let Some(options) = args.get("options") {
builder.with_options(parse_key_value_options(options)?);
}
let mut options = args
.get("options")
.map(|value| parse_key_value_options(value))
.transpose()?
.unwrap_or_default();
if let Some(fields) = args.get("extra_fields") {
options.insert("extra_fields".into(), fields.clone());
}
builder.with_options(options);
if let Some(partitions) = args.get("partitions") {
builder
.with_partition_filter(parse_partitions(&table, partitions)?)
Expand Down
32 changes: 32 additions & 0 deletions crates/integrations/datafusion/tests/read_tables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2006,6 +2006,38 @@ mod vector_search_tests {
.await;
}

#[tokio::test]
async fn test_create_centroid_bitmap_prefilters_sql_top_k() {
let (ctx, _catalog, _tmp) = create_empty_vector_search_context().await;
for sql in [
"CREATE TABLE paimon.default.centroid_bitmap_sql \
(id INT, embedding FLOAT[], tenant INT, status INT) \
WITH ('bucket'='-1', 'row-tracking.enabled'='true', \
'data-evolution.enabled'='true', 'global-index.enabled'='true', \
'vector-index.post-filter.candidates-factor'='1')",
"INSERT INTO paimon.default.centroid_bitmap_sql (id, embedding, tenant, status) \
VALUES (0, [0.0, 0.0], 1, 0), (1, [1.0, 0.0], 2, 0), (2, [2.0, 0.0], 1, 3)",
"CALL sys.create_global_index(table => 'default.centroid_bitmap_sql', \
index_column => 'embedding', index_type => 'ivf-flat', \
options => 'ivf-flat.sharding=centroid,ivf-flat.centroid.nlist=1,\
ivf-flat.nlist=1,ivf-flat.dimension=2,ivf-flat.metric=l2', \
extra_fields => '{\"tenant\":\"bitmap\",\"status\":\"bitmap\"}')",
] {
ctx.sql(sql).await.unwrap().collect().await.unwrap();
}
let batches = ctx
.sql(
"SELECT id FROM vector_search('paimon.default.centroid_bitmap_sql', 'embedding', \
'[0.0, 0.0]', 1) WHERE tenant = 2 OR status = 3",
)
.await
.unwrap()
.collect()
.await
.unwrap();
assert_eq!(extract_ids_in_order(&batches), [1]);
}

/// `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.
Expand Down
Loading
Loading