Changesets · Branches · Tags · Compare
| Changeset | f167fea780f1fd6e62f8f76e9fa0086f2003d9a0a87b2e03f838a3fcbfb833ed |
|---|---|
| Author | Will Jones <willjones127@gmail.com> · 2024-09-27 09:00 -07:00 |
| Committer | GitHub <noreply@github.com> · 2024-09-27 09:00 -07:00 |
| Parents | 41c63cc36ae5 |
7 files changed
modified Cargo.toml +1 −0
| @@ -38,6 +38,7 @@ | ||
| 38 | 38 | arrow-cast = "52.2" |
| 39 | 39 | async-trait = "0" |
| 40 | 40 | chrono = "0.4.35" |
| 41 | +datafusion-common = "40.0" | |
| 41 | 42 | datafusion-physical-plan = "40.0" |
| 42 | 43 | half = { "version" = "=2.4.1", default-features = false, features = [ |
| 43 | 44 | "num-traits", |
modified rust/lancedb/Cargo.toml +1 −0
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | arrow-cast = { workspace = true } |
| 20 | 20 | arrow-ipc.workspace = true |
| 21 | 21 | chrono = { workspace = true } |
| 22 | +datafusion-common.workspace = true | |
| 22 | 23 | datafusion-physical-plan.workspace = true |
| 23 | 24 | object_store = { workspace = true } |
| 24 | 25 | snafu = { workspace = true } |
modified rust/lancedb/src/lib.rs +6 −0
| @@ -254,6 +254,12 @@ | ||
| 254 | 254 | Hamming, |
| 255 | 255 | } |
| 256 | 256 | |
| 257 | +impl Default for DistanceType { | |
| 258 | + fn default() -> Self { | |
| 259 | + Self::L2 | |
| 260 | + } | |
| 261 | +} | |
| 262 | + | |
| 257 | 263 | impl From<DistanceType> for LanceDistanceType { |
| 258 | 264 | fn from(value: DistanceType) -> Self { |
| 259 | 265 | match value { |
modified rust/lancedb/src/remote.rs +1 −0
| @@ -23,3 +23,4 @@ | ||
| 23 | 23 | pub mod util; |
| 24 | 24 | |
| 25 | 25 | 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 @@ | ||
| 1 | 1 | use std::sync::{Arc, Mutex}; |
| 2 | 2 | |
| 3 | -use crate::table::dataset::DatasetReadGuard; | |
| 3 | +use crate::index::Index; | |
| 4 | +use crate::query::Select; | |
| 4 | 5 | use crate::table::AddDataMode; |
| 6 | +use crate::utils::{supported_btree_data_type, supported_vector_data_type}; | |
| 5 | 7 | use crate::Error; |
| 6 | 8 | use arrow_array::RecordBatchReader; |
| 7 | -use arrow_schema::SchemaRef; | |
| 9 | +use arrow_ipc::reader::StreamReader; | |
| 10 | +use arrow_schema::{DataType, SchemaRef}; | |
| 8 | 11 | 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; | |
| 10 | 17 | use http::header::CONTENT_TYPE; |
| 11 | 18 | use http::StatusCode; |
| 12 | 19 | use lance::arrow::json::JsonSchema; |
| 13 | -use lance::dataset::scanner::{DatasetRecordBatchStream, Scanner}; | |
| 20 | +use lance::dataset::scanner::DatasetRecordBatchStream; | |
| 14 | 21 | use lance::dataset::{ColumnAlteration, NewColumnTransform}; |
| 22 | +use lance_datafusion::exec::OneShotExec; | |
| 15 | 23 | use serde::{Deserialize, Serialize}; |
| 16 | 24 | |
| 17 | 25 | use crate::{ |
| @@ -26,7 +34,7 @@ | ||
| 26 | 34 | }; |
| 27 | 35 | |
| 28 | 36 | use super::client::{HttpSend, RestfulLanceDbClient, Sender}; |
| 29 | -use super::ARROW_STREAM_CONTENT_TYPE; | |
| 37 | +use super::{ARROW_STREAM_CONTENT_TYPE, JSON_CONTENT_TYPE}; | |
| 30 | 38 | |
| 31 | 39 | #[derive(Debug)] |
| 32 | 40 | pub struct RemoteTable<S: HttpSend = Sender> { |
| @@ -85,6 +93,93 @@ | ||
| 85 | 93 | |
| 86 | 94 | self.client.check_response(response).await |
| 87 | 95 | } |
| 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) = ¶ms.filter { | |
| 142 | + body["filter"] = serde_json::Value::String(filter.clone()); | |
| 143 | + } | |
| 144 | + | |
| 145 | + match ¶ms.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) = ¶ms.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 | + } | |
| 88 | 183 | } |
| 89 | 184 | |
| 90 | 185 | #[derive(Deserialize)] |
| @@ -196,38 +291,78 @@ | ||
| 196 | 291 | |
| 197 | 292 | Ok(()) |
| 198 | 293 | } |
| 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 | + | |
| 209 | 295 | async fn create_plan( |
| 210 | 296 | &self, |
| 211 | - _query: &VectorQuery, | |
| 297 | + query: &VectorQuery, | |
| 212 | 298 | _options: QueryExecutionOptions, |
| 213 | 299 | ) -> 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))) | |
| 222 | 344 | } |
| 345 | + | |
| 223 | 346 | async fn plain_query( |
| 224 | 347 | &self, |
| 225 | - _query: &Query, | |
| 348 | + query: &Query, | |
| 226 | 349 | _options: QueryExecutionOptions, |
| 227 | 350 | ) -> 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)) | |
| 231 | 366 | } |
| 232 | 367 | async fn update(&self, update: UpdateBuilder) -> Result<u64> { |
| 233 | 368 | let request = self.client.post(&format!("/table/{}/update/", self.name)); |
| @@ -266,11 +401,79 @@ | ||
| 266 | 401 | self.check_table_response(response).await?; |
| 267 | 402 | Ok(()) |
| 268 | 403 | } |
| 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(()) | |
| 273 | 475 | } |
| 476 | + | |
| 274 | 477 | async fn merge_insert( |
| 275 | 478 | &self, |
| 276 | 479 | params: MergeInsertBuilder, |
| @@ -375,9 +578,14 @@ | ||
| 375 | 578 | use arrow_array::{Int32Array, RecordBatch, RecordBatchIterator}; |
| 376 | 579 | use arrow_schema::{DataType, Field, Schema}; |
| 377 | 580 | use futures::{future::BoxFuture, StreamExt, TryFutureExt}; |
| 581 | + use lance_index::scalar::FullTextSearchQuery; | |
| 378 | 582 | use reqwest::Body; |
| 379 | 583 | |
| 380 | - use crate::{Error, Table}; | |
| 584 | + use crate::{ | |
| 585 | + index::{vector::IvfPqIndexBuilder, Index}, | |
| 586 | + query::{ExecutableQuery, QueryBase}, | |
| 587 | + DistanceType, Error, Table, | |
| 588 | + }; | |
| 381 | 589 | |
| 382 | 590 | #[tokio::test] |
| 383 | 591 | async fn test_not_found() { |
| @@ -468,6 +676,10 @@ | ||
| 468 | 676 | let table = Table::new_with_handler("my_table", |request| { |
| 469 | 677 | assert_eq!(request.method(), "POST"); |
| 470 | 678 | 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 | + ); | |
| 471 | 683 | assert_eq!(request.body().unwrap().as_bytes().unwrap(), br#"{}"#); |
| 472 | 684 | |
| 473 | 685 | http::Response::builder().status(200).body("42").unwrap() |
| @@ -479,6 +691,10 @@ | ||
| 479 | 691 | let table = Table::new_with_handler("my_table", |request| { |
| 480 | 692 | assert_eq!(request.method(), "POST"); |
| 481 | 693 | 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 | + ); | |
| 482 | 698 | assert_eq!( |
| 483 | 699 | request.body().unwrap().as_bytes().unwrap(), |
| 484 | 700 | br#"{"filter":"a > 10"}"# |
| @@ -613,6 +829,10 @@ | ||
| 613 | 829 | let table = Table::new_with_handler("my_table", |request| { |
| 614 | 830 | assert_eq!(request.method(), "POST"); |
| 615 | 831 | assert_eq!(request.url().path(), "/table/my_table/update/"); |
| 832 | + assert_eq!( | |
| 833 | + request.headers().get("Content-Type").unwrap(), | |
| 834 | + JSON_CONTENT_TYPE | |
| 835 | + ); | |
| 616 | 836 | |
| 617 | 837 | if let Some(body) = request.body().unwrap().as_bytes() { |
| 618 | 838 | let body = std::str::from_utf8(body).unwrap(); |
| @@ -720,6 +940,10 @@ | ||
| 720 | 940 | let table = Table::new_with_handler("my_table", |request| { |
| 721 | 941 | assert_eq!(request.method(), "POST"); |
| 722 | 942 | assert_eq!(request.url().path(), "/table/my_table/delete/"); |
| 943 | + assert_eq!( | |
| 944 | + request.headers().get("Content-Type").unwrap(), | |
| 945 | + JSON_CONTENT_TYPE | |
| 946 | + ); | |
| 723 | 947 | |
| 724 | 948 | let body = request.body().unwrap().as_bytes().unwrap(); |
| 725 | 949 | let body: serde_json::Value = serde_json::from_slice(body).unwrap(); |
| @@ -731,4 +955,201 @@ | ||
| 731 | 955 | |
| 732 | 956 | table.delete("id in (1, 2, 3)").await.unwrap(); |
| 733 | 957 | } |
| 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 | + } | |
| 734 | 1155 | } |
modified rust/lancedb/src/table.rs +30 −88
| @@ -21,8 +21,9 @@ | ||
| 21 | 21 | use arrow::array::AsArray; |
| 22 | 22 | use arrow::datatypes::Float32Type; |
| 23 | 23 | use arrow_array::{RecordBatchIterator, RecordBatchReader}; |
| 24 | -use arrow_schema::{DataType, Field, Schema, SchemaRef}; | |
| 24 | +use arrow_schema::{Field, Schema, SchemaRef}; | |
| 25 | 25 | use async_trait::async_trait; |
| 26 | +use datafusion_physical_plan::display::DisplayableExecutionPlan; | |
| 26 | 27 | use datafusion_physical_plan::ExecutionPlan; |
| 27 | 28 | use lance::dataset::builder::DatasetBuilder; |
| 28 | 29 | use lance::dataset::cleanup::RemovalStats; |
| @@ -66,9 +67,13 @@ | ||
| 66 | 67 | use crate::query::{ |
| 67 | 68 | IntoQueryVector, Query, QueryExecutionOptions, Select, VectorQuery, DEFAULT_TOP_K, |
| 68 | 69 | }; |
| 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 | +}; | |
| 70 | 75 | |
| 71 | -use self::dataset::{DatasetConsistencyWrapper, DatasetReadGuard}; | |
| 76 | +use self::dataset::DatasetConsistencyWrapper; | |
| 72 | 77 | use self::merge::MergeInsertBuilder; |
| 73 | 78 | |
| 74 | 79 | pub(crate) mod dataset; |
| @@ -375,12 +380,6 @@ | ||
| 375 | 380 | async fn schema(&self) -> Result<SchemaRef>; |
| 376 | 381 | /// Count the number of rows in this table. |
| 377 | 382 | 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>; | |
| 384 | 383 | async fn create_plan( |
| 385 | 384 | &self, |
| 386 | 385 | query: &VectorQuery, |
| @@ -391,7 +390,12 @@ | ||
| 391 | 390 | query: &Query, |
| 392 | 391 | options: QueryExecutionOptions, |
| 393 | 392 | ) -> 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 | + } | |
| 395 | 399 | async fn add( |
| 396 | 400 | &self, |
| 397 | 401 | add: AddDataBuilder<NoData>, |
| @@ -1088,46 +1092,6 @@ | ||
| 1088 | 1092 | Ok(name.to_string()) |
| 1089 | 1093 | } |
| 1090 | 1094 | |
| 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 | - | |
| 1131 | 1095 | /// Creates a new Table |
| 1132 | 1096 | /// |
| 1133 | 1097 | /// # Arguments |
| @@ -1386,7 +1350,7 @@ | ||
| 1386 | 1350 | field: &Field, |
| 1387 | 1351 | replace: bool, |
| 1388 | 1352 | ) -> Result<()> { |
| 1389 | - if !Self::supported_vector_data_type(field.data_type()) { | |
| 1353 | + if !supported_vector_data_type(field.data_type()) { | |
| 1390 | 1354 | return Err(Error::InvalidInput { |
| 1391 | 1355 | message: format!( |
| 1392 | 1356 | "An IVF PQ index cannot be created on the column `{}` which has data type {}", |
| @@ -1439,7 +1403,7 @@ | ||
| 1439 | 1403 | field: &Field, |
| 1440 | 1404 | replace: bool, |
| 1441 | 1405 | ) -> Result<()> { |
| 1442 | - if !Self::supported_vector_data_type(field.data_type()) { | |
| 1406 | + if !supported_vector_data_type(field.data_type()) { | |
| 1443 | 1407 | return Err(Error::InvalidInput { |
| 1444 | 1408 | message: format!( |
| 1445 | 1409 | "An IVF HNSW PQ index cannot be created on the column `{}` which has data type {}", |
| @@ -1510,7 +1474,7 @@ | ||
| 1510 | 1474 | field: &Field, |
| 1511 | 1475 | replace: bool, |
| 1512 | 1476 | ) -> Result<()> { |
| 1513 | - if !Self::supported_vector_data_type(field.data_type()) { | |
| 1477 | + if !supported_vector_data_type(field.data_type()) { | |
| 1514 | 1478 | return Err(Error::InvalidInput { |
| 1515 | 1479 | message: format!( |
| 1516 | 1480 | "An IVF HNSW SQ index cannot be created on the column `{}` which has data type {}", |
| @@ -1563,10 +1527,10 @@ | ||
| 1563 | 1527 | } |
| 1564 | 1528 | |
| 1565 | 1529 | 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()) { | |
| 1567 | 1531 | self.create_ivf_pq_index(IvfPqIndexBuilder::default(), field, opts.replace) |
| 1568 | 1532 | .await |
| 1569 | - } else if Self::supported_btree_data_type(field.data_type()) { | |
| 1533 | + } else if supported_btree_data_type(field.data_type()) { | |
| 1570 | 1534 | self.create_btree_index(field, opts).await |
| 1571 | 1535 | } else { |
| 1572 | 1536 | Err(Error::InvalidInput { |
| @@ -1580,7 +1544,7 @@ | ||
| 1580 | 1544 | } |
| 1581 | 1545 | |
| 1582 | 1546 | 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()) { | |
| 1584 | 1548 | return Err(Error::Schema { |
| 1585 | 1549 | message: format!( |
| 1586 | 1550 | "A BTree index cannot be created on the field `{}` which has data type {}", |
| @@ -1607,7 +1571,7 @@ | ||
| 1607 | 1571 | } |
| 1608 | 1572 | |
| 1609 | 1573 | 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()) { | |
| 1611 | 1575 | return Err(Error::Schema { |
| 1612 | 1576 | message: format!( |
| 1613 | 1577 | "A Bitmap index cannot be created on the field `{}` which has data type {}", |
| @@ -1634,7 +1598,7 @@ | ||
| 1634 | 1598 | } |
| 1635 | 1599 | |
| 1636 | 1600 | 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()) { | |
| 1638 | 1602 | return Err(Error::Schema { |
| 1639 | 1603 | message: format!( |
| 1640 | 1604 | "A LabelList index cannot be created on the field `{}` which has data type {}", |
| @@ -1666,7 +1630,7 @@ | ||
| 1666 | 1630 | fts_opts: FtsIndexBuilder, |
| 1667 | 1631 | replace: bool, |
| 1668 | 1632 | ) -> Result<()> { |
| 1669 | - if !Self::supported_fts_data_type(field.data_type()) { | |
| 1633 | + if !supported_fts_data_type(field.data_type()) { | |
| 1670 | 1634 | return Err(Error::Schema { |
| 1671 | 1635 | message: format!( |
| 1672 | 1636 | "A FTS index cannot be created on the field `{}` which has data type {}", |
| @@ -1887,12 +1851,13 @@ | ||
| 1887 | 1851 | Ok(res.rows_updated) |
| 1888 | 1852 | } |
| 1889 | 1853 | |
| 1890 | - async fn build_plan( | |
| 1854 | + async fn create_plan( | |
| 1891 | 1855 | &self, |
| 1892 | - ds_ref: &DatasetReadGuard, | |
| 1893 | 1856 | 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 | + | |
| 1896 | 1861 | let mut scanner: Scanner = ds_ref.scan(); |
| 1897 | 1862 | |
| 1898 | 1863 | if let Some(query_vector) = query.query_vector.as_ref() { |
| @@ -1966,25 +1931,12 @@ | ||
| 1966 | 1931 | scanner.with_row_id(); |
| 1967 | 1932 | } |
| 1968 | 1933 | |
| 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 | + | |
| 1972 | 1936 | if query.base.fast_search { |
| 1973 | 1937 | scanner.fast_search(); |
| 1974 | 1938 | } |
| 1975 | 1939 | |
| 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 | - | |
| 1988 | 1940 | match &query.base.select { |
| 1989 | 1941 | Select::Columns(select) => { |
| 1990 | 1942 | scanner.project(select.as_slice())?; |
| @@ -2023,16 +1975,6 @@ | ||
| 2023 | 1975 | .await |
| 2024 | 1976 | } |
| 2025 | 1977 | |
| 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 | - | |
| 2036 | 1978 | async fn merge_insert( |
| 2037 | 1979 | &self, |
| 2038 | 1980 | params: MergeInsertBuilder, |
modified rust/lancedb/src/utils.rs +39 −1
| @@ -14,7 +14,7 @@ | ||
| 14 | 14 | |
| 15 | 15 | use std::sync::Arc; |
| 16 | 16 | |
| 17 | -use arrow_schema::Schema; | |
| 17 | +use arrow_schema::{DataType, Schema}; | |
| 18 | 18 | use lance::dataset::{ReadParams, WriteParams}; |
| 19 | 19 | use lance::io::{ObjectStoreParams, WrappingObjectStore}; |
| 20 | 20 | use lazy_static::lazy_static; |
| @@ -137,6 +137,44 @@ | ||
| 137 | 137 | } |
| 138 | 138 | } |
| 139 | 139 | |
| 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 | + | |
| 140 | 178 | #[cfg(test)] |
| 141 | 179 | mod tests { |
| 142 | 180 | use super::*; |