mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
fix: register Lance SQL functions for RTE filters (#3794)
<!-- lance-gatekeeper-fix:v1 agent=d1262fd0aeb86548a3550f636fffe0cc generation=1 --> Embedded RTE queries parse SQL filters in a separate DataFusion context. Register Lance's SQL functions in that context so a filter such as `ST_Distance(...) <= radius` resolves as it does in an ordinary Embedded scan. The Rust regression checks an inclusive distance filter against rows in the base table and the active MemTable with the `geo` feature enabled. This builds on [Gatefixer's original contribution](https://github.com/lancedb/lancedb/commit/e459892bb5ee611daf53fe5e61d51aeb70e41dd5). --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
co-authored by
Xuanwo
parent
a46ed4754b
commit
8c9ba71add
@@ -424,11 +424,11 @@ fn base_scanner(
|
||||
let df_schema = schema.clone().to_dfschema().map_err(|error| {
|
||||
enrich_filter_error(error, &schema, "Failed to create DFSchema")
|
||||
})?;
|
||||
let expr = SessionContext::new()
|
||||
.parse_sql_expr(sql, &df_schema)
|
||||
.map_err(|error| {
|
||||
enrich_filter_error(error, &schema, "Failed to parse filter expression")
|
||||
})?;
|
||||
let ctx = SessionContext::new();
|
||||
lance_datafusion::udf::register_functions(&ctx);
|
||||
let expr = ctx.parse_sql_expr(sql, &df_schema).map_err(|error| {
|
||||
enrich_filter_error(error, &schema, "Failed to parse filter expression")
|
||||
})?;
|
||||
scanner.filter_expr(expr)
|
||||
}
|
||||
QueryFilter::Datafusion(expr) => scanner.filter_expr(expr.clone()),
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
#![cfg(feature = "geo")]
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use arrow_array::{Float64Array, Int32Array, RecordBatch, RecordBatchIterator};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use futures::TryStreamExt;
|
||||
use lancedb::query::{ExecutableQuery, Query, QueryBase, Select};
|
||||
use lancedb::table::RTEWriteSpec;
|
||||
|
||||
fn point_batch(ids: Vec<i32>, x: Vec<f64>, y: Vec<f64>) -> RecordBatch {
|
||||
let schema = Arc::new(Schema::new(vec![
|
||||
Field::new("id", DataType::Int32, false),
|
||||
Field::new("x", DataType::Float64, false),
|
||||
Field::new("y", DataType::Float64, false),
|
||||
]));
|
||||
RecordBatch::try_new(
|
||||
schema,
|
||||
vec![
|
||||
Arc::new(Int32Array::from(ids)),
|
||||
Arc::new(Float64Array::from(x)),
|
||||
Arc::new(Float64Array::from(y)),
|
||||
],
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn collect_ids(query: Query) -> lancedb::Result<Vec<i32>> {
|
||||
let batches: Vec<RecordBatch> = query
|
||||
.select(Select::columns(&["id"]))
|
||||
.execute()
|
||||
.await?
|
||||
.try_collect()
|
||||
.await?;
|
||||
let mut ids = Vec::new();
|
||||
for batch in batches {
|
||||
let column = batch
|
||||
.column(0)
|
||||
.as_any()
|
||||
.downcast_ref::<Int32Array>()
|
||||
.unwrap();
|
||||
ids.extend_from_slice(column.values());
|
||||
}
|
||||
ids.sort_unstable();
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn distance_filter_on_rte_base_and_active_memtable() -> lancedb::Result<()> {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = lancedb::connect(dir.path().to_str().unwrap())
|
||||
.execute()
|
||||
.await?;
|
||||
// Each source has a point inside the radius, one on it, and one outside it.
|
||||
let base = point_batch(vec![1, 2, 3], vec![0.0, 2.0, 3.0], vec![0.0, 0.0, 4.0]);
|
||||
let table = db.create_table("points", base).execute().await?;
|
||||
table.set_unenforced_primary_key(["id"]).await?;
|
||||
table.enable_rte(RTEWriteSpec::unsharded()).await?;
|
||||
|
||||
let active = point_batch(vec![4, 5, 6], vec![0.25, 0.0, 4.0], vec![0.25, 2.0, 3.0]);
|
||||
let mut merge = table.merge_insert(&["id"]);
|
||||
merge
|
||||
.use_rte(true)
|
||||
.when_matched_update_all(None)
|
||||
.when_not_matched_insert_all();
|
||||
let schema = active.schema();
|
||||
merge
|
||||
.execute(Box::new(RecordBatchIterator::new([Ok(active)], schema)))
|
||||
.await?;
|
||||
|
||||
let plan = table.query().use_rte(true).explain_plan(true).await?;
|
||||
assert!(
|
||||
plan.contains("MemTableDedupScanExec"),
|
||||
"expected the active MemTable in the RTE plan:\n{plan}"
|
||||
);
|
||||
assert_eq!(
|
||||
collect_ids(table.query().use_rte(true)).await?,
|
||||
[1, 2, 3, 4, 5, 6]
|
||||
);
|
||||
|
||||
let filter = "ST_Distance(ST_Point(x, y), ST_Point(0.0, 0.0)) <= 2.0";
|
||||
let base_ids = collect_ids(table.query().use_rte(false).only_if(filter)).await?;
|
||||
assert_eq!(base_ids, [1, 2]);
|
||||
let rte_ids = collect_ids(table.query().use_rte(true).only_if(filter)).await?;
|
||||
assert_eq!(rte_ids, [1, 2, 4, 5]);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user