Elffuss BraidHub

kikocis/lancedb public

feat(rust): remote client `query` and `create_index` endpoints (#1663)

Support for `query` and `create_index`.

Closes [#2519](https://github.com/lancedb/sophon/issues/2519)
Changesetf167fea780f1fd6e62f8f76e9fa0086f2003d9a0a87b2e03f838a3fcbfb833ed
AuthorWill Jones <willjones127@gmail.com> · 2024-09-27 09:00 -07:00
CommitterGitHub <noreply@github.com> · 2024-09-27 09:00 -07:00
Parents41c63cc36ae5

Browse the files at this changeset

7 files changed

modified Cargo.toml +1 −0
@@ -38,6 +38,7 @@
3838 arrow-cast = "52.2"
3939 async-trait = "0"
4040 chrono = "0.4.35"
41+datafusion-common = "40.0"
4142 datafusion-physical-plan = "40.0"
4243 half = { "version" = "=2.4.1", default-features = false, features = [
4344 "num-traits",
modified rust/lancedb/Cargo.toml +1 −0
@@ -19,6 +19,7 @@
1919 arrow-cast = { workspace = true }
2020 arrow-ipc.workspace = true
2121 chrono = { workspace = true }
22+datafusion-common.workspace = true
2223 datafusion-physical-plan.workspace = true
2324 object_store = { workspace = true }
2425 snafu = { workspace = true }
modified rust/lancedb/src/lib.rs +6 −0
@@ -254,6 +254,12 @@
254254 Hamming,
255255 }
256256
257+impl Default for DistanceType {
258+ fn default() -> Self {
259+ Self::L2
260+ }
261+}
262+
257263 impl From<DistanceType> for LanceDistanceType {
258264 fn from(value: DistanceType) -> Self {
259265 match value {
modified rust/lancedb/src/remote.rs +1 −0
@@ -23,3 +23,4 @@
2323 pub mod util;
2424
2525 const ARROW_STREAM_CONTENT_TYPE: &str = "application/vnd.apache.arrow.stream";
26+const JSON_CONTENT_TYPE: &str = "application/json";
modified rust/lancedb/src/remote/table.rs +454 −33
@@ -1,17 +1,25 @@
11 use std::sync::{Arc, Mutex};
22
3-use crate::table::dataset::DatasetReadGuard;
3+use crate::index::Index;
4+use crate::query::Select;
45 use crate::table::AddDataMode;
6+use crate::utils::{supported_btree_data_type, supported_vector_data_type};
57 use crate::Error;
68 use arrow_array::RecordBatchReader;
7-use arrow_schema::SchemaRef;
9+use arrow_ipc::reader::StreamReader;
10+use arrow_schema::{DataType, SchemaRef};
811 use async_trait::async_trait;
9-use datafusion_physical_plan::ExecutionPlan;
12+use bytes::Buf;
13+use datafusion_common::DataFusionError;
14+use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
15+use datafusion_physical_plan::{ExecutionPlan, SendableRecordBatchStream};
16+use futures::TryStreamExt;
1017 use http::header::CONTENT_TYPE;
1118 use http::StatusCode;
1219 use lance::arrow::json::JsonSchema;
13-use lance::dataset::scanner::{DatasetRecordBatchStream, Scanner};
20+use lance::dataset::scanner::DatasetRecordBatchStream;
1421 use lance::dataset::{ColumnAlteration, NewColumnTransform};
22+use lance_datafusion::exec::OneShotExec;
1523 use serde::{Deserialize, Serialize};
1624
1725 use crate::{
@@ -26,7 +34,7 @@
2634 };
2735
2836 use super::client::{HttpSend, RestfulLanceDbClient, Sender};
29-use super::ARROW_STREAM_CONTENT_TYPE;
37+use super::{ARROW_STREAM_CONTENT_TYPE, JSON_CONTENT_TYPE};
3038
3139 #[derive(Debug)]
3240 pub struct RemoteTable<S: HttpSend = Sender> {
@@ -85,6 +93,93 @@
8593
8694 self.client.check_response(response).await
8795 }
96+
97+ async fn read_arrow_stream(
98+ &self,
99+ body: reqwest::Response,
100+ ) -> Result<SendableRecordBatchStream> {
101+ // Assert that the content type is correct
102+ let content_type = body
103+ .headers()
104+ .get(CONTENT_TYPE)
105+ .ok_or_else(|| Error::Http {
106+ message: "Missing content type".into(),
107+ })?
108+ .to_str()
109+ .map_err(|e| Error::Http {
110+ message: format!("Failed to parse content type: {}", e),
111+ })?;
112+ if content_type != ARROW_STREAM_CONTENT_TYPE {
113+ return Err(Error::Http {
114+ message: format!(
115+ "Expected content type {}, got {}",
116+ ARROW_STREAM_CONTENT_TYPE, content_type
117+ ),
118+ });
119+ }
120+
121+ // There isn't a way to actually stream this data yet. I have an upstream issue:
122+ // https://github.com/apache/arrow-rs/issues/6420
123+ let body = body.bytes().await?;
124+ let reader = StreamReader::try_new(body.reader(), None)?;
125+ let schema = reader.schema();
126+ let stream = futures::stream::iter(reader).map_err(DataFusionError::from);
127+ Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
128+ }
129+
130+ fn apply_query_params(body: &mut serde_json::Value, params: &Query) -> Result<()> {
131+ if params.offset.is_some() {
132+ return Err(Error::NotSupported {
133+ message: "Offset is not yet supported in LanceDB Cloud".into(),
134+ });
135+ }
136+
137+ if let Some(limit) = params.limit {
138+ body["k"] = serde_json::Value::Number(serde_json::Number::from(limit));
139+ }
140+
141+ if let Some(filter) = &params.filter {
142+ body["filter"] = serde_json::Value::String(filter.clone());
143+ }
144+
145+ match &params.select {
146+ Select::All => {}
147+ Select::Columns(columns) => {
148+ body["columns"] = serde_json::Value::Array(
149+ columns
150+ .iter()
151+ .map(|s| serde_json::Value::String(s.clone()))
152+ .collect(),
153+ );
154+ }
155+ Select::Dynamic(pairs) => {
156+ body["columns"] = serde_json::Value::Array(
157+ pairs
158+ .iter()
159+ .map(|(name, expr)| serde_json::json!([name, expr]))
160+ .collect(),
161+ );
162+ }
163+ }
164+
165+ if params.fast_search {
166+ body["fast_search"] = serde_json::Value::Bool(true);
167+ }
168+
169+ if let Some(full_text_search) = &params.full_text_search {
170+ if full_text_search.wand_factor.is_some() {
171+ return Err(Error::NotSupported {
172+ message: "Wand factor is not yet supported in LanceDB Cloud".into(),
173+ });
174+ }
175+ body["full_text_query"] = serde_json::json!({
176+ "columns": full_text_search.columns,
177+ "query": full_text_search.query,
178+ })
179+ }
180+
181+ Ok(())
182+ }
88183 }
89184
90185 #[derive(Deserialize)]
@@ -196,38 +291,78 @@
196291
197292 Ok(())
198293 }
199- async fn build_plan(
200- &self,
201- _ds_ref: &DatasetReadGuard,
202- _query: &VectorQuery,
203- _options: Option<QueryExecutionOptions>,
204- ) -> Result<Scanner> {
205- Err(Error::NotSupported {
206- message: "build_plan is not supported on LanceDB cloud.".into(),
207- })
208- }
294+
209295 async fn create_plan(
210296 &self,
211- _query: &VectorQuery,
297+ query: &VectorQuery,
212298 _options: QueryExecutionOptions,
213299 ) -> Result<Arc<dyn ExecutionPlan>> {
214- Err(Error::NotSupported {
215- message: "create_plan is not supported on LanceDB cloud.".into(),
216- })
217- }
218- async fn explain_plan(&self, _query: &VectorQuery, _verbose: bool) -> Result<String> {
219- Err(Error::NotSupported {
220- message: "explain_plan is not supported on LanceDB cloud.".into(),
221- })
300+ let request = self.client.post(&format!("/table/{}/query/", self.name));
301+
302+ let mut body = serde_json::Value::Object(Default::default());
303+ Self::apply_query_params(&mut body, &query.base)?;
304+
305+ body["prefilter"] = query.prefilter.into();
306+ body["distance_type"] = serde_json::json!(query.distance_type.unwrap_or_default());
307+ body["nprobes"] = query.nprobes.into();
308+ body["refine_factor"] = query.refine_factor.into();
309+
310+ if let Some(vector) = query.query_vector.as_ref() {
311+ let vector: Vec<f32> = match vector.data_type() {
312+ DataType::Float32 => vector
313+ .as_any()
314+ .downcast_ref::<arrow_array::Float32Array>()
315+ .unwrap()
316+ .values()
317+ .iter()
318+ .cloned()
319+ .collect(),
320+ _ => {
321+ return Err(Error::InvalidInput {
322+ message: "VectorQuery vector must be of type Float32".into(),
323+ })
324+ }
325+ };
326+ body["vector"] = serde_json::json!(vector);
327+ }
328+
329+ if let Some(vector_column) = query.column.as_ref() {
330+ body["vector_column"] = serde_json::Value::String(vector_column.clone());
331+ }
332+
333+ if !query.use_index {
334+ body["bypass_vector_index"] = serde_json::Value::Bool(true);
335+ }
336+
337+ let request = request.json(&body);
338+
339+ let response = self.client.send(request).await?;
340+
341+ let stream = self.read_arrow_stream(response).await?;
342+
343+ Ok(Arc::new(OneShotExec::new(stream)))
222344 }
345+
223346 async fn plain_query(
224347 &self,
225- _query: &Query,
348+ query: &Query,
226349 _options: QueryExecutionOptions,
227350 ) -> Result<DatasetRecordBatchStream> {
228- Err(Error::NotSupported {
229- message: "plain_query is not yet supported on LanceDB cloud.".into(),
230- })
351+ let request = self
352+ .client
353+ .post(&format!("/table/{}/query/", self.name))
354+ .header(CONTENT_TYPE, JSON_CONTENT_TYPE);
355+
356+ let mut body = serde_json::Value::Object(Default::default());
357+ Self::apply_query_params(&mut body, query)?;
358+
359+ let request = request.json(&body);
360+
361+ let response = self.client.send(request).await?;
362+
363+ let stream = self.read_arrow_stream(response).await?;
364+
365+ Ok(DatasetRecordBatchStream::new(stream))
231366 }
232367 async fn update(&self, update: UpdateBuilder) -> Result<u64> {
233368 let request = self.client.post(&format!("/table/{}/update/", self.name));
@@ -266,11 +401,79 @@
266401 self.check_table_response(response).await?;
267402 Ok(())
268403 }
269- async fn create_index(&self, _index: IndexBuilder) -> Result<()> {
270- Err(Error::NotSupported {
271- message: "create_index is not yet supported on LanceDB cloud.".into(),
272- })
404+
405+ async fn create_index(&self, mut index: IndexBuilder) -> Result<()> {
406+ let request = self
407+ .client
408+ .post(&format!("/table/{}/create_index/", self.name));
409+
410+ let column = match index.columns.len() {
411+ 0 => {
412+ return Err(Error::InvalidInput {
413+ message: "No columns specified".into(),
414+ })
415+ }
416+ 1 => index.columns.pop().unwrap(),
417+ _ => {
418+ return Err(Error::NotSupported {
419+ message: "Indices over multiple columns not yet supported".into(),
420+ })
421+ }
422+ };
423+ let mut body = serde_json::json!({
424+ "column": column
425+ });
426+
427+ let (index_type, distance_type) = match index.index {
428+ // TODO: Should we pass the actual index parameters? SaaS does not
429+ // yet support them.
430+ Index::IvfPq(index) => ("IVF_PQ", Some(index.distance_type)),
431+ Index::IvfHnswSq(index) => ("IVF_HNSW_SQ", Some(index.distance_type)),
432+ Index::BTree(_) => ("BTREE", None),
433+ Index::Bitmap(_) => ("BITMAP", None),
434+ Index::LabelList(_) => ("LABEL_LIST", None),
435+ Index::FTS(_) => ("FTS", None),
436+ Index::Auto => {
437+ let schema = self.schema().await?;
438+ let field = schema
439+ .field_with_name(&column)
440+ .map_err(|_| Error::InvalidInput {
441+ message: format!("Column {} not found in schema", column),
442+ })?;
443+ if supported_vector_data_type(field.data_type()) {
444+ ("IVF_PQ", None)
445+ } else if supported_btree_data_type(field.data_type()) {
446+ ("BTREE", None)
447+ } else {
448+ return Err(Error::NotSupported {
449+ message: format!(
450+ "there are no indices supported for the field `{}` with the data type {}",
451+ field.name(),
452+ field.data_type()
453+ ),
454+ });
455+ }
456+ }
457+ _ => {
458+ return Err(Error::NotSupported {
459+ message: "Index type not supported".into(),
460+ })
461+ }
462+ };
463+ body["index_type"] = serde_json::Value::String(index_type.into());
464+ if let Some(distance_type) = distance_type {
465+ body["distance_type"] = serde_json::Value::String(distance_type.to_string());
466+ }
467+
468+ let request = request.json(&body);
469+
470+ let response = self.client.send(request).await?;
471+
472+ self.check_table_response(response).await?;
473+
474+ Ok(())
273475 }
476+
274477 async fn merge_insert(
275478 &self,
276479 params: MergeInsertBuilder,
@@ -375,9 +578,14 @@
375578 use arrow_array::{Int32Array, RecordBatch, RecordBatchIterator};
376579 use arrow_schema::{DataType, Field, Schema};
377580 use futures::{future::BoxFuture, StreamExt, TryFutureExt};
581+ use lance_index::scalar::FullTextSearchQuery;
378582 use reqwest::Body;
379583
380- use crate::{Error, Table};
584+ use crate::{
585+ index::{vector::IvfPqIndexBuilder, Index},
586+ query::{ExecutableQuery, QueryBase},
587+ DistanceType, Error, Table,
588+ };
381589
382590 #[tokio::test]
383591 async fn test_not_found() {
@@ -468,6 +676,10 @@
468676 let table = Table::new_with_handler("my_table", |request| {
469677 assert_eq!(request.method(), "POST");
470678 assert_eq!(request.url().path(), "/table/my_table/count_rows/");
679+ assert_eq!(
680+ request.headers().get("Content-Type").unwrap(),
681+ JSON_CONTENT_TYPE
682+ );
471683 assert_eq!(request.body().unwrap().as_bytes().unwrap(), br#"{}"#);
472684
473685 http::Response::builder().status(200).body("42").unwrap()
@@ -479,6 +691,10 @@
479691 let table = Table::new_with_handler("my_table", |request| {
480692 assert_eq!(request.method(), "POST");
481693 assert_eq!(request.url().path(), "/table/my_table/count_rows/");
694+ assert_eq!(
695+ request.headers().get("Content-Type").unwrap(),
696+ JSON_CONTENT_TYPE
697+ );
482698 assert_eq!(
483699 request.body().unwrap().as_bytes().unwrap(),
484700 br#"{"filter":"a > 10"}"#
@@ -613,6 +829,10 @@
613829 let table = Table::new_with_handler("my_table", |request| {
614830 assert_eq!(request.method(), "POST");
615831 assert_eq!(request.url().path(), "/table/my_table/update/");
832+ assert_eq!(
833+ request.headers().get("Content-Type").unwrap(),
834+ JSON_CONTENT_TYPE
835+ );
616836
617837 if let Some(body) = request.body().unwrap().as_bytes() {
618838 let body = std::str::from_utf8(body).unwrap();
@@ -720,6 +940,10 @@
720940 let table = Table::new_with_handler("my_table", |request| {
721941 assert_eq!(request.method(), "POST");
722942 assert_eq!(request.url().path(), "/table/my_table/delete/");
943+ assert_eq!(
944+ request.headers().get("Content-Type").unwrap(),
945+ JSON_CONTENT_TYPE
946+ );
723947
724948 let body = request.body().unwrap().as_bytes().unwrap();
725949 let body: serde_json::Value = serde_json::from_slice(body).unwrap();
@@ -731,4 +955,201 @@
731955
732956 table.delete("id in (1, 2, 3)").await.unwrap();
733957 }
958+
959+ #[tokio::test]
960+ async fn test_query_vector_default_values() {
961+ let expected_data = RecordBatch::try_new(
962+ Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])),
963+ vec![Arc::new(Int32Array::from(vec![1, 2, 3]))],
964+ )
965+ .unwrap();
966+ let expected_data_ref = expected_data.clone();
967+
968+ let table = Table::new_with_handler("my_table", move |request| {
969+ assert_eq!(request.method(), "POST");
970+ assert_eq!(request.url().path(), "/table/my_table/query/");
971+ assert_eq!(
972+ request.headers().get("Content-Type").unwrap(),
973+ JSON_CONTENT_TYPE
974+ );
975+
976+ let body = request.body().unwrap().as_bytes().unwrap();
977+ let body: serde_json::Value = serde_json::from_slice(body).unwrap();
978+ let mut expected_body = serde_json::json!({
979+ "prefilter": true,
980+ "distance_type": "l2",
981+ "nprobes": 20,
982+ "refine_factor": null,
983+ });
984+ // Pass vector separately to make sure it matches f32 precision.
985+ expected_body["vector"] = vec![0.1f32, 0.2, 0.3].into();
986+ assert_eq!(body, expected_body);
987+
988+ let response_body = write_ipc_stream(&expected_data_ref);
989+ http::Response::builder()
990+ .status(200)
991+ .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE)
992+ .body(response_body)
993+ .unwrap()
994+ });
995+
996+ let data = table
997+ .query()
998+ .nearest_to(vec![0.1, 0.2, 0.3])
999+ .unwrap()
1000+ .execute()
1001+ .await;
1002+ let data = data.unwrap().collect::<Vec<_>>().await;
1003+ assert_eq!(data.len(), 1);
1004+ assert_eq!(data[0].as_ref().unwrap(), &expected_data);
1005+ }
1006+
1007+ #[tokio::test]
1008+ async fn test_query_vector_all_params() {
1009+ let table = Table::new_with_handler("my_table", |request| {
1010+ assert_eq!(request.method(), "POST");
1011+ assert_eq!(request.url().path(), "/table/my_table/query/");
1012+ assert_eq!(
1013+ request.headers().get("Content-Type").unwrap(),
1014+ JSON_CONTENT_TYPE
1015+ );
1016+
1017+ let body = request.body().unwrap().as_bytes().unwrap();
1018+ let body: serde_json::Value = serde_json::from_slice(body).unwrap();
1019+ let mut expected_body = serde_json::json!({
1020+ "vector_column": "my_vector",
1021+ "prefilter": false,
1022+ "k": 42,
1023+ "distance_type": "cosine",
1024+ "bypass_vector_index": true,
1025+ "columns": ["a", "b"],
1026+ "nprobes": 12,
1027+ "refine_factor": 2,
1028+ });
1029+ // Pass vector separately to make sure it matches f32 precision.
1030+ expected_body["vector"] = vec![0.1f32, 0.2, 0.3].into();
1031+ assert_eq!(body, expected_body);
1032+
1033+ let data = RecordBatch::try_new(
1034+ Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])),
1035+ vec![Arc::new(Int32Array::from(vec![1, 2, 3]))],
1036+ )
1037+ .unwrap();
1038+ let response_body = write_ipc_stream(&data);
1039+ http::Response::builder()
1040+ .status(200)
1041+ .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE)
1042+ .body(response_body)
1043+ .unwrap()
1044+ });
1045+
1046+ let _ = table
1047+ .query()
1048+ .limit(42)
1049+ .select(Select::columns(&["a", "b"]))
1050+ .nearest_to(vec![0.1, 0.2, 0.3])
1051+ .unwrap()
1052+ .column("my_vector")
1053+ .postfilter()
1054+ .distance_type(crate::DistanceType::Cosine)
1055+ .nprobes(12)
1056+ .refine_factor(2)
1057+ .bypass_vector_index()
1058+ .execute()
1059+ .await
1060+ .unwrap();
1061+ }
1062+
1063+ #[tokio::test]
1064+ async fn test_query_fts() {
1065+ let table = Table::new_with_handler("my_table", |request| {
1066+ assert_eq!(request.method(), "POST");
1067+ assert_eq!(request.url().path(), "/table/my_table/query/");
1068+ assert_eq!(
1069+ request.headers().get("Content-Type").unwrap(),
1070+ JSON_CONTENT_TYPE
1071+ );
1072+
1073+ let body = request.body().unwrap().as_bytes().unwrap();
1074+ let body: serde_json::Value = serde_json::from_slice(body).unwrap();
1075+ let expected_body = serde_json::json!({
1076+ "full_text_query": {
1077+ "columns": ["a", "b"],
1078+ "query": "hello world",
1079+ },
1080+ "k": 10,
1081+ });
1082+ assert_eq!(body, expected_body);
1083+
1084+ let data = RecordBatch::try_new(
1085+ Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])),
1086+ vec![Arc::new(Int32Array::from(vec![1, 2, 3]))],
1087+ )
1088+ .unwrap();
1089+ let response_body = write_ipc_stream(&data);
1090+ http::Response::builder()
1091+ .status(200)
1092+ .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE)
1093+ .body(response_body)
1094+ .unwrap()
1095+ });
1096+
1097+ let _ = table
1098+ .query()
1099+ .full_text_search(
1100+ FullTextSearchQuery::new("hello world".into())
1101+ .columns(Some(vec!["a".into(), "b".into()])),
1102+ )
1103+ .limit(10)
1104+ .execute()
1105+ .await
1106+ .unwrap();
1107+ }
1108+
1109+ #[tokio::test]
1110+ async fn test_create_index() {
1111+ let cases = [
1112+ ("IVF_PQ", Some("l2"), Index::IvfPq(Default::default())),
1113+ (
1114+ "IVF_PQ",
1115+ Some("cosine"),
1116+ Index::IvfPq(IvfPqIndexBuilder::default().distance_type(DistanceType::Cosine)),
1117+ ),
1118+ (
1119+ "IVF_HNSW_SQ",
1120+ Some("l2"),
1121+ Index::IvfHnswSq(Default::default()),
1122+ ),
1123+ // HNSW_PQ isn't yet supported on SaaS
1124+ ("BTREE", None, Index::BTree(Default::default())),
1125+ ("BITMAP", None, Index::Bitmap(Default::default())),
1126+ ("LABEL_LIST", None, Index::LabelList(Default::default())),
1127+ ("FTS", None, Index::FTS(Default::default())),
1128+ ];
1129+
1130+ for (index_type, distance_type, index) in cases {
1131+ let table = Table::new_with_handler("my_table", move |request| {
1132+ assert_eq!(request.method(), "POST");
1133+ assert_eq!(request.url().path(), "/table/my_table/create_index/");
1134+ assert_eq!(
1135+ request.headers().get("Content-Type").unwrap(),
1136+ JSON_CONTENT_TYPE
1137+ );
1138+ let body = request.body().unwrap().as_bytes().unwrap();
1139+ let body: serde_json::Value = serde_json::from_slice(body).unwrap();
1140+ let mut expected_body = serde_json::json!({
1141+ "column": "a",
1142+ "index_type": index_type,
1143+ });
1144+ if let Some(distance_type) = distance_type {
1145+ expected_body["distance_type"] = distance_type.into();
1146+ }
1147+ assert_eq!(body, expected_body);
1148+
1149+ http::Response::builder().status(200).body("{}").unwrap()
1150+ });
1151+
1152+ table.create_index(&["a"], index).execute().await.unwrap();
1153+ }
1154+ }
7341155 }
modified rust/lancedb/src/table.rs +30 −88
@@ -21,8 +21,9 @@
2121 use arrow::array::AsArray;
2222 use arrow::datatypes::Float32Type;
2323 use arrow_array::{RecordBatchIterator, RecordBatchReader};
24-use arrow_schema::{DataType, Field, Schema, SchemaRef};
24+use arrow_schema::{Field, Schema, SchemaRef};
2525 use async_trait::async_trait;
26+use datafusion_physical_plan::display::DisplayableExecutionPlan;
2627 use datafusion_physical_plan::ExecutionPlan;
2728 use lance::dataset::builder::DatasetBuilder;
2829 use lance::dataset::cleanup::RemovalStats;
@@ -66,9 +67,13 @@
6667 use crate::query::{
6768 IntoQueryVector, Query, QueryExecutionOptions, Select, VectorQuery, DEFAULT_TOP_K,
6869 };
69-use crate::utils::{default_vector_column, PatchReadParam, PatchWriteParam};
70+use crate::utils::{
71+ default_vector_column, supported_bitmap_data_type, supported_btree_data_type,
72+ supported_fts_data_type, supported_label_list_data_type, supported_vector_data_type,
73+ PatchReadParam, PatchWriteParam,
74+};
7075
71-use self::dataset::{DatasetConsistencyWrapper, DatasetReadGuard};
76+use self::dataset::DatasetConsistencyWrapper;
7277 use self::merge::MergeInsertBuilder;
7378
7479 pub(crate) mod dataset;
@@ -375,12 +380,6 @@
375380 async fn schema(&self) -> Result<SchemaRef>;
376381 /// Count the number of rows in this table.
377382 async fn count_rows(&self, filter: Option<String>) -> Result<usize>;
378- async fn build_plan(
379- &self,
380- ds_ref: &DatasetReadGuard,
381- query: &VectorQuery,
382- options: Option<QueryExecutionOptions>,
383- ) -> Result<Scanner>;
384383 async fn create_plan(
385384 &self,
386385 query: &VectorQuery,
@@ -391,7 +390,12 @@
391390 query: &Query,
392391 options: QueryExecutionOptions,
393392 ) -> Result<DatasetRecordBatchStream>;
394- async fn explain_plan(&self, query: &VectorQuery, verbose: bool) -> Result<String>;
393+ async fn explain_plan(&self, query: &VectorQuery, verbose: bool) -> Result<String> {
394+ let plan = self.create_plan(query, Default::default()).await?;
395+ let display = DisplayableExecutionPlan::new(plan.as_ref());
396+
397+ Ok(format!("{}", display.indent(verbose)))
398+ }
395399 async fn add(
396400 &self,
397401 add: AddDataBuilder<NoData>,
@@ -1088,46 +1092,6 @@
10881092 Ok(name.to_string())
10891093 }
10901094
1091- fn supported_btree_data_type(dtype: &DataType) -> bool {
1092- dtype.is_integer()
1093- || dtype.is_floating()
1094- || matches!(
1095- dtype,
1096- DataType::Boolean
1097- | DataType::Utf8
1098- | DataType::Time32(_)
1099- | DataType::Time64(_)
1100- | DataType::Date32
1101- | DataType::Date64
1102- | DataType::Timestamp(_, _)
1103- )
1104- }
1105-
1106- fn supported_bitmap_data_type(dtype: &DataType) -> bool {
1107- dtype.is_integer() || matches!(dtype, DataType::Utf8)
1108- }
1109-
1110- fn supported_label_list_data_type(dtype: &DataType) -> bool {
1111- match dtype {
1112- DataType::List(field) => Self::supported_bitmap_data_type(field.data_type()),
1113- DataType::FixedSizeList(field, _) => {
1114- Self::supported_bitmap_data_type(field.data_type())
1115- }
1116- _ => false,
1117- }
1118- }
1119-
1120- fn supported_fts_data_type(dtype: &DataType) -> bool {
1121- matches!(dtype, DataType::Utf8 | DataType::LargeUtf8)
1122- }
1123-
1124- fn supported_vector_data_type(dtype: &DataType) -> bool {
1125- match dtype {
1126- DataType::FixedSizeList(inner, _) => DataType::is_floating(inner.data_type()),
1127- _ => false,
1128- }
1129- }
1130-
11311095 /// Creates a new Table
11321096 ///
11331097 /// # Arguments
@@ -1386,7 +1350,7 @@
13861350 field: &Field,
13871351 replace: bool,
13881352 ) -> Result<()> {
1389- if !Self::supported_vector_data_type(field.data_type()) {
1353+ if !supported_vector_data_type(field.data_type()) {
13901354 return Err(Error::InvalidInput {
13911355 message: format!(
13921356 "An IVF PQ index cannot be created on the column `{}` which has data type {}",
@@ -1439,7 +1403,7 @@
14391403 field: &Field,
14401404 replace: bool,
14411405 ) -> Result<()> {
1442- if !Self::supported_vector_data_type(field.data_type()) {
1406+ if !supported_vector_data_type(field.data_type()) {
14431407 return Err(Error::InvalidInput {
14441408 message: format!(
14451409 "An IVF HNSW PQ index cannot be created on the column `{}` which has data type {}",
@@ -1510,7 +1474,7 @@
15101474 field: &Field,
15111475 replace: bool,
15121476 ) -> Result<()> {
1513- if !Self::supported_vector_data_type(field.data_type()) {
1477+ if !supported_vector_data_type(field.data_type()) {
15141478 return Err(Error::InvalidInput {
15151479 message: format!(
15161480 "An IVF HNSW SQ index cannot be created on the column `{}` which has data type {}",
@@ -1563,10 +1527,10 @@
15631527 }
15641528
15651529 async fn create_auto_index(&self, field: &Field, opts: IndexBuilder) -> Result<()> {
1566- if Self::supported_vector_data_type(field.data_type()) {
1530+ if supported_vector_data_type(field.data_type()) {
15671531 self.create_ivf_pq_index(IvfPqIndexBuilder::default(), field, opts.replace)
15681532 .await
1569- } else if Self::supported_btree_data_type(field.data_type()) {
1533+ } else if supported_btree_data_type(field.data_type()) {
15701534 self.create_btree_index(field, opts).await
15711535 } else {
15721536 Err(Error::InvalidInput {
@@ -1580,7 +1544,7 @@
15801544 }
15811545
15821546 async fn create_btree_index(&self, field: &Field, opts: IndexBuilder) -> Result<()> {
1583- if !Self::supported_btree_data_type(field.data_type()) {
1547+ if !supported_btree_data_type(field.data_type()) {
15841548 return Err(Error::Schema {
15851549 message: format!(
15861550 "A BTree index cannot be created on the field `{}` which has data type {}",
@@ -1607,7 +1571,7 @@
16071571 }
16081572
16091573 async fn create_bitmap_index(&self, field: &Field, opts: IndexBuilder) -> Result<()> {
1610- if !Self::supported_bitmap_data_type(field.data_type()) {
1574+ if !supported_bitmap_data_type(field.data_type()) {
16111575 return Err(Error::Schema {
16121576 message: format!(
16131577 "A Bitmap index cannot be created on the field `{}` which has data type {}",
@@ -1634,7 +1598,7 @@
16341598 }
16351599
16361600 async fn create_label_list_index(&self, field: &Field, opts: IndexBuilder) -> Result<()> {
1637- if !Self::supported_label_list_data_type(field.data_type()) {
1601+ if !supported_label_list_data_type(field.data_type()) {
16381602 return Err(Error::Schema {
16391603 message: format!(
16401604 "A LabelList index cannot be created on the field `{}` which has data type {}",
@@ -1666,7 +1630,7 @@
16661630 fts_opts: FtsIndexBuilder,
16671631 replace: bool,
16681632 ) -> Result<()> {
1669- if !Self::supported_fts_data_type(field.data_type()) {
1633+ if !supported_fts_data_type(field.data_type()) {
16701634 return Err(Error::Schema {
16711635 message: format!(
16721636 "A FTS index cannot be created on the field `{}` which has data type {}",
@@ -1887,12 +1851,13 @@
18871851 Ok(res.rows_updated)
18881852 }
18891853
1890- async fn build_plan(
1854+ async fn create_plan(
18911855 &self,
1892- ds_ref: &DatasetReadGuard,
18931856 query: &VectorQuery,
1894- options: Option<QueryExecutionOptions>,
1895- ) -> Result<Scanner> {
1857+ options: QueryExecutionOptions,
1858+ ) -> Result<Arc<dyn ExecutionPlan>> {
1859+ let ds_ref = self.dataset.get().await?;
1860+
18961861 let mut scanner: Scanner = ds_ref.scan();
18971862
18981863 if let Some(query_vector) = query.query_vector.as_ref() {
@@ -1966,25 +1931,12 @@
19661931 scanner.with_row_id();
19671932 }
19681933
1969- if let Some(opts) = options {
1970- scanner.batch_size(opts.max_batch_length as usize);
1971- }
1934+ scanner.batch_size(options.max_batch_length as usize);
1935+
19721936 if query.base.fast_search {
19731937 scanner.fast_search();
19741938 }
19751939
1976- Ok(scanner)
1977- }
1978-
1979- async fn create_plan(
1980- &self,
1981- query: &VectorQuery,
1982- options: QueryExecutionOptions,
1983- ) -> Result<Arc<dyn ExecutionPlan>> {
1984- let ds_ref = self.dataset.get().await?;
1985-
1986- let mut scanner = self.build_plan(&ds_ref, query, Some(options)).await?;
1987-
19881940 match &query.base.select {
19891941 Select::Columns(select) => {
19901942 scanner.project(select.as_slice())?;
@@ -2023,16 +1975,6 @@
20231975 .await
20241976 }
20251977
2026- async fn explain_plan(&self, query: &VectorQuery, verbose: bool) -> Result<String> {
2027- let ds_ref = self.dataset.get().await?;
2028-
2029- let scanner = self.build_plan(&ds_ref, query, None).await?;
2030-
2031- let plan = scanner.explain_plan(verbose).await?;
2032-
2033- Ok(plan)
2034- }
2035-
20361978 async fn merge_insert(
20371979 &self,
20381980 params: MergeInsertBuilder,
modified rust/lancedb/src/utils.rs +39 −1
@@ -14,7 +14,7 @@
1414
1515 use std::sync::Arc;
1616
17-use arrow_schema::Schema;
17+use arrow_schema::{DataType, Schema};
1818 use lance::dataset::{ReadParams, WriteParams};
1919 use lance::io::{ObjectStoreParams, WrappingObjectStore};
2020 use lazy_static::lazy_static;
@@ -137,6 +137,44 @@
137137 }
138138 }
139139
140+pub fn supported_btree_data_type(dtype: &DataType) -> bool {
141+ dtype.is_integer()
142+ || dtype.is_floating()
143+ || matches!(
144+ dtype,
145+ DataType::Boolean
146+ | DataType::Utf8
147+ | DataType::Time32(_)
148+ | DataType::Time64(_)
149+ | DataType::Date32
150+ | DataType::Date64
151+ | DataType::Timestamp(_, _)
152+ )
153+}
154+
155+pub fn supported_bitmap_data_type(dtype: &DataType) -> bool {
156+ dtype.is_integer() || matches!(dtype, DataType::Utf8)
157+}
158+
159+pub fn supported_label_list_data_type(dtype: &DataType) -> bool {
160+ match dtype {
161+ DataType::List(field) => supported_bitmap_data_type(field.data_type()),
162+ DataType::FixedSizeList(field, _) => supported_bitmap_data_type(field.data_type()),
163+ _ => false,
164+ }
165+}
166+
167+pub fn supported_fts_data_type(dtype: &DataType) -> bool {
168+ matches!(dtype, DataType::Utf8 | DataType::LargeUtf8)
169+}
170+
171+pub fn supported_vector_data_type(dtype: &DataType) -> bool {
172+ match dtype {
173+ DataType::FixedSizeList(inner, _) => DataType::is_floating(inner.data_type()),
174+ _ => false,
175+ }
176+}
177+
140178 #[cfg(test)]
141179 mod tests {
142180 use super::*;