diff --git a/docs/web/indexing/index.mdx b/docs/web/indexing/index.mdx
index 963f2f567..0c68576a3 100644
--- a/docs/web/indexing/index.mdx
+++ b/docs/web/indexing/index.mdx
@@ -22,7 +22,7 @@ patterns. LanceDB supports three main index families:
| `IVF` (Vector) | Large-scale vector search with configurable accuracy/speed trade-offs. | Inverted File Index: a partition-based approximate nearest neighbor algorithm that groups similar vectors into partitions for efficient search.
**Quantizations**: `None/Flat` `PQ` `SQ` `RQ`|
| `IVF_HNSW` (Vector) | Large-scale vector search requiring both high recall and efficient partitioning. Combines the scalability of IVF with the search quality of HNSW. | Hybrid index combining IVF partitioning with HNSW graphs in each partition. Provides improved search quality over pure IVF while maintaining scalability.
**Quantizations**: `None/Flat` `SQ` `PQ`|
| `FTS` (Full-text search) | String columns (e.g., title, description, content) requiring keyword-based search with BM25 ranking. | Full-text search index using BM25 ranking algorithm. Tokenizes text with configurable tokenization, stemming, stop word removal, and language-specific processing. |
-| `BTree` (Scalar) | Numeric, temporal, and string columns with mostly distinct values. Best for selective equality, inequality, and range predicates. | Sorted index storing sorted copies of scalar columns with block headers in a btree cache. Header entries map to blocks of rows (4096 rows per block) for efficient disk reads. |
+| `BTree` (Scalar) | Numeric, temporal, string, and binary columns with mostly distinct values. Best for selective equality, inequality, and range predicates. | Sorted index storing sorted copies of scalar columns with block headers in a btree cache. Header entries map to blocks of rows (4096 rows per block) for efficient disk reads. |
| `Bitmap` (Scalar) | Low-cardinality columns with few thousand or fewer distinct values. Accelerates equality and range filters. | Stores a bitmap for each distinct value in the column, with one bit per row indicating presence. Memory-efficient for low-cardinality data. |
| `LabelList` (Scalar) | List columns (e.g., tags, categories, keywords) requiring `array_has_all` or `array_has_any` filters. | Scalar index for `List` and `LargeList` columns of primitive values, using an underlying bitmap index structure to enable fast array membership lookups. |
| `FM` (Scalar) | String or binary columns that need raw substring search. | FM-Index over `Utf8`, `LargeUtf8`, `Binary`, or `LargeBinary` data for filters such as `contains(path, 'needle')`. Use FTS instead for tokenized word search and BM25 ranking. |
@@ -67,7 +67,7 @@ the index type based on the column's values:
| Index | Best for |
|-------|----------|
-| `BTREE` (default) | Numeric, string, temporal columns with mostly distinct values |
+| `BTREE` (default) | Numeric, string, binary, and temporal columns with mostly distinct values |
| `BITMAP` | Boolean and low-cardinality columns (< ~1,000 distinct values) |
| `LABEL_LIST` | `List` columns queried with `array_has_any` / `array_has_all` |
diff --git a/docs/web/indexing/scalar-index.mdx b/docs/web/indexing/scalar-index.mdx
index a28b33585..af9f2249d 100644
--- a/docs/web/indexing/scalar-index.mdx
+++ b/docs/web/indexing/scalar-index.mdx
@@ -33,7 +33,7 @@ with vector and full-text search.
LanceDB supports these scalar index types, among others:
-- `BTREE`: Stores column data in sorted order for binary search. Best for columns with many unique values.
+- `BTREE`: Stores column data in sorted order for binary search. Best for numeric, temporal, string, or binary columns with many unique values.
- `BITMAP`: Uses bitmaps to track value presence. Ideal for columns with few unique values (e.g., categories, tags).
- `LABEL_LIST`: Special index for `List` and `LargeList` columns of primitive values supporting `array_has_all` and `array_has_any` queries.
- `FM`: FM-Index over string or binary columns that accelerates substring search via `contains(col, 'needle')`.
@@ -53,7 +53,7 @@ Use scalar indexes with:
| Data Type | Filter | Index Type |
|:----------------------------------------------------------------|:------------------------------------------|:-------------|
-| Numeric, String, Temporal | `<`, `=`, `>`, `in`, `between`, `is null` | `BTREE` |
+| Numeric, String, Binary, Temporal | `<`, `=`, `>`, `in`, `between`, `is null` | `BTREE` |
| Boolean, numbers or strings with fewer than 1,000 unique values | `<`, `=`, `>`, `in`, `between`, `is null` | `BITMAP` |
| List of low cardinality of numbers or strings | `array_has_any`, `array_has_all` | `LABEL_LIST` |
| String or binary (`Utf8`, `LargeUtf8`, `Binary`, `LargeBinary`) | `contains(col, 'needle')` | `FM` |
diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py
index 2b5dd8ff2..3dd06a5ac 100644
--- a/python/python/lancedb/index.py
+++ b/python/python/lancedb/index.py
@@ -48,8 +48,8 @@ class BTree:
sizeof(Scalar) * 4096 bytes to find the correct row ids.
This index is good for scalar columns with mostly distinct values and does best
- when the query is highly selective. It works with numeric, temporal, and string
- columns.
+ when the query is highly selective. It works with numeric, temporal, string,
+ and binary columns.
The btree index does not currently have any parameters though parameters such as
the block size may be added in the future.
diff --git a/rust/lancedb/src/index.rs b/rust/lancedb/src/index.rs
index 30dcee3df..6be2821f6 100644
--- a/rust/lancedb/src/index.rs
+++ b/rust/lancedb/src/index.rs
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
+use arrow_schema::Field;
use chrono::{DateTime, Utc};
use lance::index::scalar::IndexDetails;
use scalar::FtsIndexBuilder;
@@ -11,6 +12,7 @@ use std::time::Duration;
use vector::IvfFlatIndexBuilder;
use crate::index::vector::IvfRqIndexBuilder;
+use crate::utils::{supported_vector_data_type, supports_btree_field};
use crate::{DistanceType, Error, Result, job::Job, table::BaseTable};
use self::{
@@ -29,13 +31,39 @@ pub mod scalar;
pub mod vector;
pub mod waiter;
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum AutoIndex {
+ IvfPq,
+ BTree,
+}
+
+impl AutoIndex {
+ pub(crate) fn resolve(field: &Field) -> Option {
+ if supported_vector_data_type(field.data_type()) {
+ Some(Self::IvfPq)
+ } else if supports_btree_field(field) {
+ Some(Self::BTree)
+ } else {
+ None
+ }
+ }
+
+ pub(crate) fn unsupported_message(field: &Field) -> String {
+ format!(
+ "there are no indices supported for the field `{}` with the data type {}",
+ field.name(),
+ field.data_type()
+ )
+ }
+}
+
/// Supported index types.
#[derive(Debug, Clone)]
pub enum Index {
Auto,
/// A `BTree` index is an sorted index on scalar columns.
/// This index is good for scalar columns with mostly distinct values and does best when
- /// the query is highly selective. It can apply to numeric, temporal, and string columns.
+ /// the query is highly selective. It can apply to numeric, temporal, string, and binary columns.
///
/// BTree index is useful to answer queries with
/// equality (`=`), inequality (`>`, `>=`, `<`, `<=`),and range queries.
@@ -598,7 +626,9 @@ pub struct IndexStatistics {
#[cfg(test)]
mod tests {
- use super::IndexType;
+ use super::{AutoIndex, Field, IndexType};
+ use arrow_schema::DataType;
+ use std::sync::Arc;
#[test]
fn builtin_scalar_index_type_names() {
@@ -625,4 +655,40 @@ mod tests {
}
}
}
+
+ #[test]
+ fn test_resolve_auto_index() {
+ let vector =
+ DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 16);
+ for (data_type, expected) in [
+ (DataType::Int32, Some(AutoIndex::BTree)),
+ (DataType::Utf8, Some(AutoIndex::BTree)),
+ (DataType::LargeUtf8, Some(AutoIndex::BTree)),
+ (DataType::Utf8View, Some(AutoIndex::BTree)),
+ (DataType::Binary, Some(AutoIndex::BTree)),
+ (DataType::LargeBinary, Some(AutoIndex::BTree)),
+ (DataType::Null, None),
+ (vector.clone(), Some(AutoIndex::IvfPq)),
+ (
+ DataType::List(Arc::new(Field::new("item", vector, true))),
+ Some(AutoIndex::IvfPq),
+ ),
+ (
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true))),
+ None,
+ ),
+ (
+ DataType::Struct(vec![Field::new("child", DataType::Int32, true)].into()),
+ None,
+ ),
+ ] {
+ let field = Field::new("value", data_type, true);
+ assert_eq!(
+ AutoIndex::resolve(&field),
+ expected,
+ "{}",
+ field.data_type()
+ );
+ }
+ }
}
diff --git a/rust/lancedb/src/index/scalar.rs b/rust/lancedb/src/index/scalar.rs
index 709f9cb9b..1a02c4930 100644
--- a/rust/lancedb/src/index/scalar.rs
+++ b/rust/lancedb/src/index/scalar.rs
@@ -4,7 +4,7 @@
//! Scalar indices are exact indices that are used to quickly satisfy a variety of filters
//! against a column of scalar values.
//!
-//! Scalar indices are currently supported on numeric, string, boolean, and temporal columns.
+//! Scalar indices are currently supported on numeric, string, binary, boolean, and temporal columns.
//!
//! A scalar index will help with queries with filters like `x > 10`, `x < 10`, `x = 10`,
//! etc. Scalar indices can also speed up prefiltering for vector searches. A single
@@ -23,7 +23,7 @@
/// the correct row ids.
///
/// This index is good for scalar columns with mostly distinct values and does best when
-/// the query is highly selective.
+/// the query is highly selective. BTree supports numeric, temporal, string, and binary columns.
///
/// The btree index does not currently have any parameters though parameters such as the
/// block size may be added in the future.
diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs
index 2f88d7f2f..1037fd701 100644
--- a/rust/lancedb/src/remote/table.rs
+++ b/rust/lancedb/src/remote/table.rs
@@ -24,7 +24,6 @@ use crate::blob::BlobFile;
use crate::data::scannable::{PeekedScannable, Scannable, estimate_write_partitions};
use crate::error::{HttpErrorSource, RemoteErrorMetadata};
use crate::expr::expr_to_sql_string;
-use crate::index::Index;
use crate::index::IndexStatistics;
use crate::index::scalar::{FtsQuery, Operator};
use crate::index::waiter::{MAX_WAIT, wait_for_index};
@@ -57,13 +56,12 @@ use crate::table::{AnyQuery, Filter, Predicate, PreprocessingOutput, TableStatis
use crate::utils::background_cache::BackgroundCache;
use crate::utils::{
MaxBatchLengthStream, TimeoutStream, public_fts_field_path_by_id, resolve_arrow_field_path,
- resolve_arrow_fts_field_path, supported_btree_data_type, supported_vector_data_type,
- validate_fts_field,
+ resolve_arrow_fts_field_path, validate_fts_field,
};
use crate::{DistanceType, Error};
use crate::{
error::Result,
- index::{IndexBuilder, IndexConfig},
+ index::{AutoIndex, Index, IndexBuilder, IndexConfig},
query::{AnalyzePlanDistributedMetrics, QueryExecutionOptions},
table::{
AddDataBuilder, BaseTable, OptimizeAction, OptimizeStats, TableDefinition, UpdateBuilder,
@@ -860,23 +858,19 @@ impl RemoteTable {
}
("FTS", Some(params))
}
- Index::Auto => {
- if supported_vector_data_type(field.data_type()) {
+ Index::Auto => match AutoIndex::resolve(&field) {
+ Some(AutoIndex::IvfPq) => {
body[METRIC_TYPE_KEY] =
serde_json::Value::String(DistanceType::L2.to_string().to_lowercase());
("IVF_PQ", None)
- } else if supported_btree_data_type(field.data_type()) {
- ("BTREE", None)
- } else {
+ }
+ Some(AutoIndex::BTree) => ("BTREE", None),
+ None => {
return Err(Error::NotSupported {
- message: format!(
- "there are no indices supported for the field `{}` with the data type {}",
- field.name(),
- field.data_type()
- ),
+ message: AutoIndex::unsupported_message(&field),
});
}
- }
+ },
Index::IvfHnswPq(_) => {
return Err(Error::NotSupported {
message: "IVF_HNSW_PQ is not supported in LanceDB Enterprise. Please use IVF_HNSW_SQ instead.".into(),
@@ -5607,7 +5601,13 @@ mod tests {
),
Field::new(
"payload",
- DataType::Struct(vec![Field::new("text", DataType::Utf8, false)].into()),
+ DataType::Struct(
+ vec![
+ Field::new("text", DataType::Utf8, false),
+ Field::new("bytes", DataType::Binary, false),
+ ]
+ .into(),
+ ),
false,
),
Field::new(
@@ -10100,6 +10100,10 @@ mod tests {
"index_type": "IVF_PQ",
"metric_type": "l2",
}),
+ json!({
+ "column": "payload.bytes",
+ "index_type": "BTREE",
+ }),
{
let mut body = serde_json::to_value(InvertedIndexParams::default()).unwrap();
body["column"] = "payload.text".into();
@@ -10189,6 +10193,11 @@ mod tests {
.execute()
.await
.unwrap();
+ table
+ .create_index(&["Payload.Bytes"], Index::Auto)
+ .execute()
+ .await
+ .unwrap();
table
.create_index(&["Payload.Text"], Index::FTS(Default::default()))
.execute()
diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs
index 1fda322fd..b34d4a55b 100644
--- a/rust/lancedb/src/table.rs
+++ b/rust/lancedb/src/table.rs
@@ -1795,9 +1795,8 @@ impl Table {
///
/// There are a variety of indices available. They are described more in
/// [`crate::index::Index`]. The simplest thing to do is to use `index::Index::Auto` which
- /// will attempt to create the most useful index based on the column type and column
- /// statistics. `BTree` index is created by default for numeric, temporal, and
- /// string columns.
+ /// selects `IvfPq` for vector columns and `BTree` for scalar columns supported by Lance's
+ /// BTree index, including numeric, temporal, string, and binary columns.
///
/// Once an index is created it will remain until the data is overwritten (e.g. an
/// add operation with mode overwrite) or the indexed column is dropped.
diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs
index 79d7ed198..28e19d292 100644
--- a/rust/lancedb/src/table/create_index.rs
+++ b/rust/lancedb/src/table/create_index.rs
@@ -14,7 +14,10 @@ use lance::index::vector::VectorIndexParams;
use lance::index::vector::utils::infer_vector_dim;
use lance_arrow::json::is_json_field;
use lance_index::IndexType;
-use lance_index::scalar::{BuiltinIndexType, ScalarIndexParams};
+use lance_index::scalar::{
+ BuiltinIndexType, ScalarIndexParams, bitmap::BitmapIndexPlugin, fmindex::FMIndexPlugin,
+ label_list::LabelListIndexPlugin,
+};
use lance_index::vector::bq::RQBuildParams;
use lance_index::vector::hnsw::builder::HnswBuildParams;
use lance_index::vector::ivf::IvfBuildParams;
@@ -25,12 +28,11 @@ use crate::error::{Error, Result};
/// Resolved column, index parameters and index type for one build.
pub(super) type PreparedIndex = (String, Box, IndexType);
-use crate::index::Index;
use crate::index::vector::{VectorIndex, suggested_num_sub_vectors};
+use crate::index::{AutoIndex, Index};
use crate::utils::{
- resolve_lance_fts_field_path, supported_bitmap_data_type, supported_btree_data_type,
- supported_fm_data_type, supported_label_list_data_type, supported_vector_data_type,
- supported_zonemap_data_type, validate_fts_field,
+ resolve_lance_fts_field_path, supported_vector_data_type, supports_btree_field,
+ supports_scalar_index, supports_zonemap_field, validate_fts_field,
};
use super::NativeTable;
@@ -156,8 +158,8 @@ impl NativeTable {
{
return Ok(None);
}
- let params = self.make_index_params(&field, opts.index.clone()).await?;
- let index_type = self.get_index_type_for_field(&field, &opts.index);
+ let index_type = Self::get_index_type_for_field(&field, &opts.index)?;
+ let params = Self::make_index_params(&field, opts.index.clone(), index_type)?;
Ok(Some((column, params, index_type)))
}
@@ -273,14 +275,14 @@ impl NativeTable {
}
// Convert LanceDB Index to Lance IndexParams
- pub(super) async fn make_index_params(
- &self,
+ fn make_index_params(
field: &Field,
index_opts: Index,
+ index_type: IndexType,
) -> Result> {
match index_opts {
Index::Auto => {
- if supported_vector_data_type(field.data_type()) {
+ if index_type == IndexType::Vector {
// Use IvfPq as the default for auto vector indices
let dim = Self::get_vector_dimension(field)?;
let ivf_params = lance_index::vector::ivf::IvfBuildParams::default();
@@ -294,26 +296,18 @@ impl NativeTable {
pq_params,
);
Ok(Box::new(lance_idx_params))
- } else if supported_btree_data_type(field.data_type()) {
+ } else {
Ok(Box::new(ScalarIndexParams::for_builtin(
BuiltinIndexType::BTree,
)))
- } else {
- Err(Error::InvalidInput {
- message: format!(
- "there are no indices supported for the field `{}` with the data type {}",
- field.name(),
- field.data_type()
- ),
- })?
}
}
- Index::BTree(_) => {
- Self::validate_index_type(field, "BTree", supported_btree_data_type)?;
- Ok(Box::new(ScalarIndexParams::for_builtin(
- BuiltinIndexType::BTree,
- )))
- }
+ Index::BTree(_) => Self::scalar_index_params(
+ field,
+ "BTree",
+ BuiltinIndexType::BTree,
+ supports_btree_field(field),
+ ),
Index::Bitmap(_) => {
if is_json_field(field) {
return Err(Error::Schema {
@@ -323,29 +317,31 @@ impl NativeTable {
),
});
}
- Self::validate_index_type(field, "Bitmap", supported_bitmap_data_type)?;
- Ok(Box::new(ScalarIndexParams::for_builtin(
+ Self::scalar_index_params(
+ field,
+ "Bitmap",
BuiltinIndexType::Bitmap,
- )))
- }
- Index::LabelList(_) => {
- Self::validate_index_type(field, "LabelList", supported_label_list_data_type)?;
- Ok(Box::new(ScalarIndexParams::for_builtin(
- BuiltinIndexType::LabelList,
- )))
- }
- Index::Fm(_) => {
- Self::validate_index_type(field, "FM", supported_fm_data_type)?;
- Ok(Box::new(ScalarIndexParams::for_builtin(
- BuiltinIndexType::Fm,
- )))
- }
- Index::ZoneMap(_) => {
- Self::validate_index_type(field, "ZoneMap", supported_zonemap_data_type)?;
- Ok(Box::new(ScalarIndexParams::for_builtin(
- BuiltinIndexType::ZoneMap,
- )))
+ supports_scalar_index(&BitmapIndexPlugin, field),
+ )
}
+ Index::LabelList(_) => Self::scalar_index_params(
+ field,
+ "LabelList",
+ BuiltinIndexType::LabelList,
+ supports_scalar_index(&LabelListIndexPlugin, field),
+ ),
+ Index::Fm(_) => Self::scalar_index_params(
+ field,
+ "FM",
+ BuiltinIndexType::Fm,
+ supports_scalar_index(&FMIndexPlugin, field),
+ ),
+ Index::ZoneMap(_) => Self::scalar_index_params(
+ field,
+ "ZoneMap",
+ BuiltinIndexType::ZoneMap,
+ supports_zonemap_field(field),
+ ),
Index::NGram(_) => Ok(Box::new(ScalarIndexParams::for_builtin(
BuiltinIndexType::NGram,
))),
@@ -520,19 +516,28 @@ impl NativeTable {
}
}
+ fn scalar_index_params(
+ field: &Field,
+ index_name: &str,
+ index_type: BuiltinIndexType,
+ supported: bool,
+ ) -> Result> {
+ Self::validate_index_type(field, index_name, |_| supported)?;
+ Ok(Box::new(ScalarIndexParams::for_builtin(index_type)))
+ }
+
// Helper method to get the correct IndexType based on the Index variant and field data type
- pub(super) fn get_index_type_for_field(&self, field: &Field, index: &Index) -> IndexType {
- match index {
- Index::Auto => {
- if supported_vector_data_type(field.data_type()) {
- IndexType::Vector
- } else if supported_btree_data_type(field.data_type()) {
- IndexType::BTree
- } else {
- // This should not happen since make_index_params would have failed
- IndexType::BTree
+ fn get_index_type_for_field(field: &Field, index: &Index) -> Result {
+ let index_type = match index {
+ Index::Auto => match AutoIndex::resolve(field) {
+ Some(AutoIndex::IvfPq) => IndexType::Vector,
+ Some(AutoIndex::BTree) => IndexType::BTree,
+ None => {
+ return Err(Error::InvalidInput {
+ message: AutoIndex::unsupported_message(field),
+ });
}
- }
+ },
Index::BTree(_) => IndexType::BTree,
Index::Bitmap(_) => IndexType::Bitmap,
Index::LabelList(_) => IndexType::LabelList,
@@ -550,7 +555,8 @@ impl NativeTable {
| Index::IvfHnswPq(_)
| Index::IvfHnswSq(_)
| Index::IvfHnswFlat(_) => IndexType::Vector,
- }
+ };
+ Ok(index_type)
}
}
@@ -564,8 +570,8 @@ mod tests {
use arrow_array::record_batch;
use arrow_array::{
Array, ArrayRef, BinaryArray, BooleanArray, FixedSizeListArray, Float32Array, Int32Array,
- LargeBinaryArray, LargeStringArray, ListArray, RecordBatch, StringArray, StructArray,
- UInt32Array, UInt64Array,
+ LargeBinaryArray, LargeStringArray, ListArray, NullArray, RecordBatch, StringArray,
+ StructArray, UInt32Array, UInt64Array,
};
use arrow_data::ArrayDataBuilder;
use arrow_schema::{DataType, Field, Schema};
@@ -1438,6 +1444,89 @@ mod tests {
assert_eq!(stats.distance_type, Some(crate::DistanceType::L2));
}
+ #[tokio::test]
+ async fn test_create_btree_on_binary() {
+ let conn = connect("memory://").execute().await.unwrap();
+ let batch = RecordBatch::try_from_iter([
+ (
+ "bytes",
+ Arc::new(BinaryArray::from(vec![b"aa".as_slice(), b"zz".as_slice()])) as ArrayRef,
+ ),
+ (
+ "large_bytes",
+ Arc::new(LargeBinaryArray::from(vec![
+ b"aa".as_slice(),
+ b"zz".as_slice(),
+ ])) as ArrayRef,
+ ),
+ (
+ "large_text",
+ Arc::new(LargeStringArray::from(vec!["aa", "zz"])) as ArrayRef,
+ ),
+ ])
+ .unwrap();
+ let table = conn
+ .create_table("binary_table", batch)
+ .execute()
+ .await
+ .unwrap();
+
+ for (column, filter) in [
+ ("bytes", "bytes = X'6161'"),
+ ("large_bytes", "large_bytes = X'6161'"),
+ ("large_text", "large_text = 'aa'"),
+ ] {
+ for index in [Index::BTree(Default::default()), Index::Auto] {
+ table
+ .create_index(&[column.to_uppercase()], index)
+ .execute()
+ .await
+ .unwrap();
+ let stats = table
+ .index_stats(&format!("{column}_idx"))
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(stats.index_type, crate::index::IndexType::BTree);
+ assert_eq!(stats.num_indexed_rows, 2);
+ }
+ assert_eq!(table.count_rows(Some(filter.to_string())).await.unwrap(), 1);
+ }
+ }
+
+ #[tokio::test]
+ async fn test_create_btree_and_zonemap_reject_null_type() {
+ let conn = connect("memory://").execute().await.unwrap();
+ let schema = Arc::new(Schema::new(vec![Field::new("value", DataType::Null, true)]));
+ let batch = RecordBatch::try_new(schema, vec![Arc::new(NullArray::new(2))]).unwrap();
+ let table = conn
+ .create_table("null_values", batch)
+ .execute()
+ .await
+ .unwrap();
+
+ for index in [
+ Index::BTree(Default::default()),
+ Index::ZoneMap(Default::default()),
+ Index::Auto,
+ ] {
+ let error = table
+ .create_index(&["value"], index)
+ .execute()
+ .await
+ .unwrap_err();
+ assert!(error.to_string().contains("data type Null"), "{error}");
+ }
+
+ assert_eq!(
+ table
+ .count_rows(Some("value IS NULL".into()))
+ .await
+ .unwrap(),
+ 2
+ );
+ }
+
#[tokio::test]
async fn test_create_scalar_index() {
let conn = connect("memory://").execute().await.unwrap();
diff --git a/rust/lancedb/src/utils/mod.rs b/rust/lancedb/src/utils/mod.rs
index 528457153..86eccb849 100644
--- a/rust/lancedb/src/utils/mod.rs
+++ b/rust/lancedb/src/utils/mod.rs
@@ -14,6 +14,11 @@ use lance::arrow::json::JsonDataType;
use lance::dataset::{ReadParams, WriteParams};
use lance::index::vector::utils::infer_vector_dim;
use lance::io::{ObjectStoreParams, WrappingObjectStore};
+use lance_index::scalar::{
+ InvertedIndexParams, bitmap::BitmapIndexPlugin, btree::BTreeIndexPlugin,
+ fmindex::FMIndexPlugin, inverted::InvertedIndexPlugin, label_list::LabelListIndexPlugin,
+ registry::BasicTrainer, zonemap::ZoneMapIndexPlugin,
+};
use std::pin::Pin;
use crate::error::{Error, Result};
@@ -533,59 +538,71 @@ pub(crate) fn resolve_arrow_fts_field_path(
}
pub fn supported_btree_data_type(dtype: &DataType) -> bool {
- dtype.is_integer()
- || dtype.is_floating()
- || matches!(
- dtype,
- DataType::Boolean
- | DataType::Utf8
- | DataType::LargeUtf8
- | DataType::Time32(_)
- | DataType::Time64(_)
- | DataType::Date32
- | DataType::Date64
- | DataType::Timestamp(_, _)
- | DataType::FixedSizeBinary(_)
- )
+ supports_btree_field(&Field::new("value", dtype.clone(), true))
}
+/// Whether a ZoneMap index can be trained on `dtype`.
+///
+/// Validation is delegated to the pinned Lance `ZoneMapIndexPlugin` trainer, whose
+/// request only parses params, so every non-`Null` type passes -- including `List`
+/// and `Struct` columns, where the index tracks just the parent null counts. `Null`
+/// is still rejected because these min/max indexes would lose `IS NULL` matches.
pub fn supported_zonemap_data_type(dtype: &DataType) -> bool {
- supported_btree_data_type(dtype)
- || matches!(
- dtype,
- DataType::LargeUtf8 | DataType::Binary | DataType::LargeBinary
- )
+ supports_zonemap_field(&Field::new("value", dtype.clone(), true))
}
pub fn supported_bitmap_data_type(dtype: &DataType) -> bool {
- dtype.is_integer()
- || matches!(
- dtype,
- DataType::Utf8
- | DataType::LargeUtf8
- | DataType::Binary
- | DataType::LargeBinary
- | DataType::Boolean
- )
+ supports_scalar_index(
+ &BitmapIndexPlugin,
+ &Field::new("value", dtype.clone(), true),
+ )
}
pub fn supported_label_list_data_type(dtype: &DataType) -> bool {
- match dtype {
- DataType::List(field) | DataType::LargeList(field) => {
- supported_bitmap_data_type(field.data_type())
- }
- DataType::FixedSizeList(field, _) => supported_bitmap_data_type(field.data_type()),
- _ => false,
- }
+ supports_scalar_index(
+ &LabelListIndexPlugin,
+ &Field::new("value", dtype.clone(), true),
+ )
}
pub fn supported_fts_data_type(dtype: &DataType) -> bool {
- supported_fts_data_type_impl(dtype, false)
+ supports_fts_field(&Field::new("value", dtype.clone(), true))
+}
+
+pub(crate) fn supports_btree_field(field: &Field) -> bool {
+ supports_min_max_index(&BTreeIndexPlugin, field)
+}
+
+pub(crate) fn supports_zonemap_field(field: &Field) -> bool {
+ supports_min_max_index(&ZoneMapIndexPlugin, field)
+}
+
+fn supports_min_max_index(plugin: &dyn BasicTrainer, field: &Field) -> bool {
+ // Lance accepts the Null type at training time, but these indexes lose IS NULL matches.
+ !field.data_type().is_null() && supports_scalar_index(plugin, field)
+}
+
+pub(crate) fn supports_scalar_index(plugin: &dyn BasicTrainer, field: &Field) -> bool {
+ plugin.new_training_request("{}", field).is_ok()
+}
+
+fn supports_fts_field(field: &Field) -> bool {
+ if field.data_type().is_binary() && !lance_arrow::json::is_json_field(field) {
+ return false;
+ }
+ // Use Lance's default format explicitly so the client environment cannot affect type validation.
+ let format_version = InvertedIndexParams::default()
+ .resolved_format_version()
+ .index_version();
+ let params = serde_json::json!({ "format_version": format_version });
+ InvertedIndexPlugin
+ .new_training_request(¶ms.to_string(), field)
+ .is_ok()
}
/// Validate FTS input without losing the logical type in field metadata.
pub(crate) fn validate_fts_field(field: &Field) -> Result<()> {
- if lance_arrow::json::is_json_field(field) || supported_fts_data_type(field.data_type()) {
+ if supports_fts_field(field) {
return Ok(());
}
let logical_type = field
@@ -603,23 +620,10 @@ pub(crate) fn validate_fts_field(field: &Field) -> Result<()> {
})
}
-fn supported_fts_data_type_impl(dtype: &DataType, in_list: bool) -> bool {
- match (dtype, in_list) {
- (DataType::Utf8 | DataType::LargeUtf8, _) => true,
- (DataType::List(field) | DataType::LargeList(field), false) => {
- supported_fts_data_type_impl(field.data_type(), true)
- }
- _ => false,
- }
-}
-
/// FM-Index accelerates substring (`contains`) search over raw bytes, so it
/// applies to string and binary columns.
pub fn supported_fm_data_type(dtype: &DataType) -> bool {
- matches!(
- dtype,
- DataType::Utf8 | DataType::LargeUtf8 | DataType::Binary | DataType::LargeBinary
- )
+ supports_scalar_index(&FMIndexPlugin, &Field::new("value", dtype.clone(), true))
}
pub fn supported_vector_data_type(dtype: &DataType) -> bool {
@@ -1161,6 +1165,56 @@ mod tests {
assert_eq!(string_to_datatype(string), Some(expected));
}
+ #[test]
+ fn test_supported_zonemap_data_type_accepts_every_non_null_type() {
+ // The delegated Lance trainer only parses params, so every non-`Null` type
+ // passes -- including `List` and `Struct` columns, where the index tracks
+ // just the parent null counts.
+ let struct_type = DataType::Struct(vec![Field::new("x", DataType::Int32, true)].into());
+ for dtype in [
+ DataType::Boolean,
+ DataType::Int32,
+ DataType::Float32,
+ DataType::Utf8,
+ DataType::LargeUtf8,
+ DataType::Binary,
+ DataType::LargeBinary,
+ DataType::List(Arc::new(Field::new("item", DataType::Int32, true))),
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Utf8, true))),
+ DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int32, true)), 3),
+ struct_type,
+ ] {
+ assert!(supported_zonemap_data_type(&dtype), "{dtype}");
+ }
+ assert!(!supported_zonemap_data_type(&DataType::Null));
+ }
+
+ #[test]
+ fn test_supported_label_list_data_type_rejects_fixed_size_list() {
+ // The delegated Lance trainer accepts `List` / `LargeList` with a non-nested
+ // item type and rejects everything else -- `FixedSizeList`, which the previous
+ // client-side policy allowed, no longer passes.
+ for dtype in [
+ DataType::List(Arc::new(Field::new("item", DataType::Int64, true))),
+ DataType::List(Arc::new(Field::new("item", DataType::Utf8, true))),
+ DataType::LargeList(Arc::new(Field::new("item", DataType::Utf8, true))),
+ ] {
+ assert!(supported_label_list_data_type(&dtype), "{dtype}");
+ }
+ for dtype in [
+ DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int32, true)), 3),
+ DataType::List(Arc::new(Field::new(
+ "item",
+ DataType::List(Arc::new(Field::new("inner", DataType::Int32, true))),
+ true,
+ ))),
+ DataType::Int32,
+ DataType::Utf8,
+ ] {
+ assert!(!supported_label_list_data_type(&dtype), "{dtype}");
+ }
+ }
+
fn sample_batch(num_rows: i32) -> RecordBatch {
let schema = Arc::new(Schema::new(vec![Field::new(
"col1",