feat(rust): convert between serde structs and Arrow data (#4910)

Closes #1101.

Rust users currently have to build `RecordBatch`es by hand to write to a
table, and read results back as Arrow arrays. This adds an optional
`serde` feature, built on `serde_arrow` (`arrow-59`, matching our arrow
line), laid out like the `polars` feature:

- `lancedb::arrow::from_structs(&[T]) -> Result<RecordBatch>` derives
the schema from `T`. Strings, lists and binaries use the 32-bit offset
types (`Utf8`, `List`, `Binary`) rather than `serde_arrow`'s `Large*`
defaults.
- `lancedb::arrow::from_structs_with_schema(&[T], SchemaRef)` serializes
against an explicit schema and keeps its metadata.
- `lancedb::arrow::IntoStructs` adds `into_structs::<T>()` on
`SendableRecordBatchStream`, mirroring `IntoPolars`. `serde_arrow` must
be able to read every selected column, and `T`'s Serde rules then apply
(derived `Deserialize` ignores extra readable columns such as
`_distance`, while `QueryBase::select` can project only the needed
columns).

Both functions return a `RecordBatch`, which is already `Scannable`, so
`add` and `create_table` need no changes. A wrapper type implementing
`Scannable` would have to convert inside `schema()`, which can't return
an error.

One caveat, covered in the docs and the example: serde has no fixed-size
sequence type that maps to Arrow, so `Vec<f32>` traces to
`List<Float32>` and `[f32; N]` traces to a struct. Appending to an
existing table works because the write path casts to the table's
`FixedSizeList` column. Creating a table from a traced batch leaves the
vector column as a `List`, so it can't be searched;
`from_structs_with_schema` is the way to create tables with vectors.
Happy to add a vector-column shorthand instead if you'd prefer that API.

`serde_arrow` and its `marrow` dependency are MIT. The `arrow-59`
feature will need bumping with the workspace arrow version, the same as
the `polars` pin.

Testing:
- Unit tests in `arrow::serde_tests`: traced schema types, empty input,
metadata preserved, wrong vector dimension error, add + read-back round
trip including nested struct and `Option` fields, create + vector search
into structs with `_distance`, missing column error, `Select::columns`
projection (including non-UTC timestamp exclusion and
`#[serde(deny_unknown_fields)]`).
- Doctests for all three APIs, and `examples/serde.rs`.
- `cargo fmt --all -- --check`
- `cargo test -p lancedb --features serde --locked --lib serde_tests`
and `--doc arrow::`
This commit is contained in:
Divakant Pandey
2026-11-30 20:33:20 +08:00
committed by GitHub
parent 4632bce81b
commit 42415ae0ff
6 changed files with 617 additions and 0 deletions
Generated
+31
View File
@@ -6204,6 +6204,7 @@ dependencies = [
"rstest",
"semver",
"serde",
"serde_arrow",
"serde_json",
"serde_with",
"serial_test",
@@ -6674,6 +6675,21 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30"
[[package]]
name = "marrow"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "789b43b5511b6037f7230829f87eac922fcfa13568362a5aa2eccb1bc0b07cb0"
dependencies = [
"arrow-array",
"arrow-buffer",
"arrow-data",
"arrow-schema",
"bytemuck",
"half",
"serde",
]
[[package]]
name = "matchers"
version = "0.2.0"
@@ -10277,6 +10293,21 @@ dependencies = [
"typeid",
]
[[package]]
name = "serde_arrow"
version = "0.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eef6f03bec0418bbde0fa9c070a5fee5b793c9cc4a392613d37c1de7ee211db5"
dependencies = [
"arrow-array",
"arrow-schema",
"bytemuck",
"chrono",
"half",
"marrow",
"serde",
]
[[package]]
name = "serde_bytes"
version = "0.11.19"
+7
View File
@@ -97,6 +97,7 @@ webbrowser = { version = "1", optional = true }
uuid = { workspace = true, features = ["v5"] }
polars-arrow = { version = ">=0.37,<0.40.0", optional = true }
polars = { version = ">=0.37,<0.40.0", optional = true }
serde_arrow = { version = "0.15.1", features = ["arrow-59"], optional = true }
hf-hub = { workspace = true, optional = true, features = [
"rustls-tls",
"tokio",
@@ -203,6 +204,8 @@ s3-test = []
bedrock = ["dep:aws-sdk-bedrockruntime", "dep:aws-smithy-types"]
openai = ["dep:async-openai", "dep:reqwest"]
polars = ["dep:polars-arrow", "dep:polars"]
# Convert between Rust structs and Arrow data with serde.
serde = ["dep:serde_arrow"]
sentence-transformers = [
"dep:hf-hub",
"dep:candle-core",
@@ -236,6 +239,10 @@ name = "simple"
name = "polars"
required-features = ["polars"]
[[example]]
name = "serde"
required-features = ["serde"]
[[example]]
name = "full_text_search"
+82
View File
@@ -0,0 +1,82 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! This example demonstrates writing Rust structs into LanceDB and reading
//! query results back as structs, using the `serde` feature.
use std::sync::Arc;
use lancedb::arrow::arrow_schema::{DataType, Field, Schema};
use lancedb::arrow::{IntoStructs, from_structs, from_structs_with_schema};
use lancedb::query::{ExecutableQuery, QueryBase};
use lancedb::{Result, connect};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Doc {
id: i64,
text: String,
vector: Vec<f32>,
}
#[derive(Deserialize)]
struct Hit {
id: i64,
text: String,
_distance: f32,
}
#[tokio::main]
async fn main() -> Result<()> {
let db = connect("memory://").execute().await?;
// Declare the vector column as a FixedSizeList so the table can be searched.
// `from_structs` alone would store `Vec<f32>` as a variable-length list.
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("text", DataType::Utf8, false),
Field::new(
"vector",
DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 3),
false,
),
]));
let docs = vec![
Doc {
id: 1,
text: "apple".into(),
vector: vec![1.0, 0.0, 0.0],
},
Doc {
id: 2,
text: "banana".into(),
vector: vec![0.0, 1.0, 0.0],
},
];
let table = db
.create_table("docs", from_structs_with_schema(&docs, schema)?)
.execute()
.await?;
// Appending can use the schema traced from the struct; the data is cast to
// the table's schema on write.
let more = vec![Doc {
id: 3,
text: "cherry".into(),
vector: vec![0.0, 0.0, 1.0],
}];
table.add(from_structs(&more)?).execute().await?;
let hits: Vec<Hit> = table
.query()
.nearest_to(&[0.0f32, 0.9, 0.1])?
.limit(2)
.execute()
.await?
.into_structs()
.await?;
for hit in hits {
println!("{} {} (distance {:.3})", hit.id, hit.text, hit._distance);
}
Ok(())
}
+485
View File
@@ -233,6 +233,491 @@ impl IntoPolars for SendableRecordBatchStream {
}
}
#[cfg(feature = "serde")]
fn struct_tracing_options() -> serde_arrow::schema::TracingOptions {
// serde_arrow defaults to 64-bit offsets (LargeUtf8, LargeList, LargeBinary).
// Use the 32-bit types that the rest of LanceDB and pyarrow produce.
serde_arrow::schema::TracingOptions::default()
.sequence_as_large_list(false)
.strings_as_large_utf8(false)
.bytes_as_large_binary(false)
}
/// Convert a slice of serde-serializable records into a [`RecordBatch`].
///
/// The Arrow schema is derived from the type `T`, so it works for an empty
/// slice too. `Vec<T>` fields become `List` columns. Adding the batch to an
/// existing table casts them to the table's `FixedSizeList` vector columns,
/// but a table created from this batch has no vector column that can be
/// searched. Use [`from_structs_with_schema`] to create tables with vectors.
///
/// ```
/// use lancedb::arrow::from_structs;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct Doc {
/// id: i64,
/// text: String,
/// vector: Vec<f32>,
/// }
///
/// # async fn add(table: &lancedb::Table) -> lancedb::Result<()> {
/// let docs = vec![Doc { id: 1, text: "hello".into(), vector: vec![0.1, 0.2] }];
/// table.add(from_structs(&docs)?).execute().await?;
/// # Ok(())
/// # }
/// ```
///
/// [`RecordBatch`]: arrow_array::RecordBatch
#[cfg(feature = "serde")]
pub fn from_structs<T>(records: &[T]) -> Result<arrow_array::RecordBatch>
where
T: serde::Serialize + serde::de::DeserializeOwned,
{
use serde_arrow::schema::SchemaLike;
let fields = Vec::<arrow_schema::FieldRef>::from_type::<T>(struct_tracing_options())?;
Ok(serde_arrow::to_record_batch(&fields, &records)?)
}
/// Convert a slice of serde-serializable records into a [`RecordBatch`] with
/// the given schema.
///
/// Struct fields are matched to columns by name. Use this to control the Arrow
/// types, for example to declare a vector column as a `FixedSizeList` so a
/// table created from the batch can be searched.
///
/// ```
/// use std::sync::Arc;
///
/// use lancedb::arrow::arrow_schema::{DataType, Field, Schema};
/// use lancedb::arrow::from_structs_with_schema;
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Doc {
/// id: i64,
/// vector: Vec<f32>,
/// }
///
/// # async fn create(db: &lancedb::Connection) -> lancedb::Result<()> {
/// let schema = Arc::new(Schema::new(vec![
/// Field::new("id", DataType::Int64, false),
/// Field::new(
/// "vector",
/// DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2),
/// false,
/// ),
/// ]));
/// let docs = vec![Doc { id: 1, vector: vec![0.1, 0.2] }];
/// db.create_table("docs", from_structs_with_schema(&docs, schema)?)
/// .execute()
/// .await?;
/// # Ok(())
/// # }
/// ```
///
/// [`RecordBatch`]: arrow_array::RecordBatch
#[cfg(feature = "serde")]
pub fn from_structs_with_schema<T>(
records: &[T],
schema: arrow_schema::SchemaRef,
) -> Result<arrow_array::RecordBatch>
where
T: serde::Serialize,
{
let batch = serde_arrow::to_record_batch(schema.fields(), &records)?;
// serde_arrow only takes the fields, so put the schema metadata back.
Ok(arrow_array::RecordBatch::try_new(
schema,
batch.columns().to_vec(),
)?)
}
/// A trait for collecting the result of a LanceDB query into a `Vec` of
/// serde-deserializable records.
///
/// Columns are matched to struct fields by name. `serde_arrow` must be able to
/// read every selected column, and the target type's Serde rules then apply: a
/// derived `Deserialize` impl ignores extra readable columns such as
/// `_distance`, whereas `#[serde(deny_unknown_fields)]` rejects them, and an
/// unsupported Arrow column type fails before Serde can skip it. Use
/// [`QueryBase::select`] to project only the columns you need.
///
/// ```
/// use lancedb::arrow::IntoStructs;
/// use lancedb::query::{ExecutableQuery, QueryBase, Select};
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Hit {
/// id: i64,
/// _distance: f32,
/// }
///
/// # async fn search(table: &lancedb::Table) -> lancedb::Result<()> {
/// let hits: Vec<Hit> = table
/// .query()
/// .nearest_to(&[0.1f32, 0.2])?
/// .select(Select::columns(&["id"]))
/// .execute()
/// .await?
/// .into_structs()
/// .await?;
/// # Ok(())
/// # }
/// ```
///
/// [`QueryBase::select`]: crate::query::QueryBase::select
#[cfg(feature = "serde")]
pub trait IntoStructs {
fn into_structs<T>(self) -> impl std::future::Future<Output = Result<Vec<T>>> + Send
where
T: serde::de::DeserializeOwned + Send;
}
#[cfg(feature = "serde")]
impl IntoStructs for SendableRecordBatchStream {
async fn into_structs<T>(mut self) -> Result<Vec<T>>
where
T: serde::de::DeserializeOwned + Send,
{
let mut records = Vec::new();
while let Some(batch) = self.next().await {
records.extend(serde_arrow::from_record_batch::<Vec<T>>(&batch?)?);
}
Ok(records)
}
}
#[cfg(all(test, feature = "serde"))]
mod serde_tests {
use std::sync::Arc;
use arrow_array::{
FixedSizeListArray, Int64Array, RecordBatch, TimestampMicrosecondArray, types::Float32Type,
};
use arrow_schema::{DataType, Field, Schema, SchemaRef, TimeUnit};
use serde::{Deserialize, Serialize};
use super::{IntoStructs, from_structs, from_structs_with_schema};
use crate::query::{ExecutableQuery, QueryBase, Select};
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
struct Location {
x: f64,
y: f64,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
struct Record {
id: i64,
caption: String,
tag: Option<String>,
location: Location,
vector: Vec<f32>,
}
fn records() -> Vec<Record> {
(0..4)
.map(|i| Record {
id: i,
caption: format!("caption {i}"),
tag: (i % 2 == 0).then(|| format!("tag {i}")),
location: Location {
x: i as f64,
y: -(i as f64),
},
vector: vec![i as f32; 4],
})
.collect()
}
fn vector_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("caption", DataType::Utf8, false),
Field::new("tag", DataType::Utf8, true),
Field::new(
"location",
DataType::Struct(
vec![
Field::new("x", DataType::Float64, false),
Field::new("y", DataType::Float64, false),
]
.into(),
),
false,
),
Field::new(
"vector",
DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 4),
false,
),
]))
}
#[test]
fn test_from_structs_schema() {
let batch = from_structs(&records()).unwrap();
assert_eq!(batch.num_rows(), 4);
let schema = batch.schema();
assert_eq!(
schema.field_with_name("caption").unwrap().data_type(),
&DataType::Utf8
);
assert!(schema.field_with_name("tag").unwrap().is_nullable());
assert!(matches!(
schema.field_with_name("vector").unwrap().data_type(),
DataType::List(_)
));
}
#[test]
fn test_from_structs_empty() {
let batch = from_structs::<Record>(&[]).unwrap();
assert_eq!(batch.num_rows(), 0);
assert_eq!(batch.num_columns(), 5);
}
#[test]
fn test_from_structs_with_schema_keeps_metadata() {
let schema = Arc::new(
vector_schema()
.as_ref()
.clone()
.with_metadata([("key".to_string(), "value".to_string())].into()),
);
let batch = from_structs_with_schema(&records(), schema.clone()).unwrap();
assert_eq!(batch.schema(), schema);
}
#[test]
fn test_from_structs_with_schema_wrong_dimension() {
let mut bad = records();
bad[1].vector = vec![1.0];
let err = from_structs_with_schema(&bad, vector_schema()).unwrap_err();
assert!(err.to_string().contains("FixedSizeList"), "{err}");
}
#[tokio::test]
async fn test_add_and_read_back() {
let db = crate::connect("memory://").execute().await.unwrap();
let table = db
.create_empty_table("t", vector_schema())
.execute()
.await
.unwrap();
table
.add(from_structs(&records()).unwrap())
.execute()
.await
.unwrap();
let mut rows: Vec<Record> = table
.query()
.execute()
.await
.unwrap()
.into_structs()
.await
.unwrap();
rows.sort_by_key(|r| r.id);
assert_eq!(rows, records());
}
#[tokio::test]
async fn test_create_table_and_vector_search() {
#[derive(Deserialize)]
struct Hit {
id: i64,
_distance: f32,
}
let db = crate::connect("memory://").execute().await.unwrap();
let table = db
.create_table(
"t",
from_structs_with_schema(&records(), vector_schema()).unwrap(),
)
.execute()
.await
.unwrap();
let hits: Vec<Hit> = table
.query()
.nearest_to(&[2.0f32; 4])
.unwrap()
.limit(1)
.execute()
.await
.unwrap()
.into_structs()
.await
.unwrap();
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].id, 2);
assert_eq!(hits[0]._distance, 0.0);
}
#[tokio::test]
async fn test_into_structs_missing_column() {
#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct Missing {
id: i64,
not_a_column: String,
}
let db = crate::connect("memory://").execute().await.unwrap();
let table = db
.create_table(
"t",
from_structs_with_schema(&records(), vector_schema()).unwrap(),
)
.execute()
.await
.unwrap();
let result = table
.query()
.execute()
.await
.unwrap()
.into_structs::<Missing>()
.await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_into_structs_select_projection() {
#[derive(Deserialize, Debug, PartialEq)]
struct Id {
id: i64,
}
#[derive(Deserialize, Debug, PartialEq)]
#[serde(deny_unknown_fields)]
struct StrictId {
id: i64,
}
#[derive(Deserialize)]
struct Hit {
id: i64,
_distance: f32,
}
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new(
"created_at",
DataType::Timestamp(TimeUnit::Microsecond, Some("Asia/Shanghai".into())),
false,
),
Field::new(
"vector",
DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, true)), 2),
false,
),
]));
let batch = RecordBatch::try_new(
schema,
vec![
Arc::new(Int64Array::from(vec![1, 2])),
Arc::new(
TimestampMicrosecondArray::from(vec![
1_700_000_000_000_000,
1_700_000_001_000_000,
])
.with_timezone("Asia/Shanghai"),
),
Arc::new(
FixedSizeListArray::from_iter_primitive::<Float32Type, _, _>(
[
Some(vec![Some(1.0), Some(0.0)]),
Some(vec![Some(0.0), Some(1.0)]),
],
2,
),
),
],
)
.unwrap();
let db = crate::connect("memory://").execute().await.unwrap();
let table = db.create_table("t", batch).execute().await.unwrap();
// serde_arrow validates every selected column before Serde can skip unused fields.
let unprojected_err = table
.query()
.execute()
.await
.unwrap()
.into_structs::<Id>()
.await
.unwrap_err();
assert!(
unprojected_err.to_string().contains("Asia/Shanghai"),
"{unprojected_err}"
);
let mut ids: Vec<Id> = table
.query()
.select(Select::columns(&["id"]))
.execute()
.await
.unwrap()
.into_structs()
.await
.unwrap();
ids.sort_by_key(|row| row.id);
assert_eq!(ids, vec![Id { id: 1 }, Id { id: 2 }]);
// Once serde_arrow can read all selected columns, target Serde rules apply.
let deny_err = table
.query()
.select(Select::columns(&["id", "vector"]))
.execute()
.await
.unwrap()
.into_structs::<StrictId>()
.await
.unwrap_err();
assert!(deny_err.to_string().contains("vector"), "{deny_err}");
let mut strict_ids: Vec<StrictId> = table
.query()
.select(Select::columns(&["id"]))
.execute()
.await
.unwrap()
.into_structs()
.await
.unwrap();
strict_ids.sort_by_key(|row| row.id);
assert_eq!(strict_ids, vec![StrictId { id: 1 }, StrictId { id: 2 }]);
let hits: Vec<Hit> = table
.query()
.nearest_to(&[0.0f32, 1.0])
.unwrap()
.select(Select::columns(&["id"]))
.limit(1)
.execute()
.await
.unwrap()
.into_structs()
.await
.unwrap();
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].id, 2);
assert_eq!(hits[0]._distance, 0.0);
}
}
#[cfg(all(test, feature = "polars"))]
mod tests {
use super::SendableRecordBatchStream;
+10
View File
@@ -825,6 +825,16 @@ impl From<polars::prelude::PolarsError> for Error {
}
}
#[cfg(feature = "serde")]
impl From<serde_arrow::Error> for Error {
fn from(source: serde_arrow::Error) -> Self {
Self::Other {
message: format!("Error in serde Arrow integration: {source}"),
source: Some(Box::new(source)),
}
}
}
#[cfg(feature = "sentence-transformers")]
impl From<hf_hub::api::sync::ApiError> for Error {
fn from(source: hf_hub::api::sync::ApiError) -> Self {
+2
View File
@@ -50,6 +50,8 @@
//! the `metrics` facade for bridging metrics into OpenTelemetry or similar.
//! - `test-fixtures` - Expose shared golden data through `test_fixtures` for
//! downstream compatibility tests. Disabled by default.
//! - `serde` - Convert between Rust structs and Arrow data with `from_structs`,
//! `from_structs_with_schema` and `IntoStructs` in the [`arrow`] module.
//!
//! ### Quick Start
//!