Skip to content

Incremental engine for long horizon agents 🌟 Star if you like it!

docs(connectors): Python and Rust pages for BigQuery, Doris, FalkorDB and LanceDB (#2751)

LJ πŸ₯₯🌴6136e98cfe2e
diff --git a/docs/src/content/docs/connectors/bigquery.mdx b/docs/src/content/docs/connectors/bigquery.mdx
index dc5fee53..b14c06ae 100644
--- a/docs/src/content/docs/connectors/bigquery.mdx
+++ b/docs/src/content/docs/connectors/bigquery.mdx
@@ -4,6 +4,9 @@ toc_max_heading_level: 4
description: >
Write CocoIndex target rows into BigQuery tables with managed DDL, MERGE
upserts, deletes, and automatic mapping from Python row types.
+rust_description: >
+ Write CocoIndex target rows into BigQuery tables with managed DDL, MERGE
+ upserts, deletes, and automatic mapping from Rust row structs.
---
import LangTabs from '../../../components/LangTabs.astro';
@@ -24,11 +27,11 @@ from cocoindex.connectors import bigquery
use cocoindex::connectors::bigquery::{self, BigQueryConfig, BigQueryConnection, TableSchema};
```
-The Rust SDK needs the `bigquery` Cargo feature of the `cocoindex` crate. The Rust connector speaks the BigQuery v2 REST API directly.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
:::note[Install]
Install the optional BigQuery dependency before using this connector:
@@ -37,10 +40,30 @@ pip install cocoindex[bigquery]
```
:::
+</Lang>
+
+<Lang only="rust">
+
+:::note[Install]
+Enable the `bigquery` Cargo feature of the `cocoindex` crate. The connector speaks the BigQuery v2 REST API directly.
+:::
+
+</Lang>
+
## Connection setup
+<Lang only="python">
+
Create a `ContextKey[bigquery.ConnectionConfig]` to identify the BigQuery connection, then provide it in your lifespan:
+</Lang>
+
+<Lang only="rust">
+
+Declare a context key for a `BigQueryConnection` with `cocoindex::context_key!`, then provide the connection when you build the environment:
+
+</Lang>
+
:::note
The key name is load-bearing across runs. It is the stable identity CocoIndex uses to track managed rows. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.
:::
@@ -99,10 +122,20 @@ let app = cocoindex::Environment::builder()
</Fragment>
</LangTabs>
-If `credentials_path` is omitted, the Google client uses Application Default Credentials.
+If `credentials_path` is omitted, Application Default Credentials are used.
+
+<Lang only="python">
### ConnectionConfig
+</Lang>
+
+<Lang only="rust">
+
+### BigQueryConfig
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/connectors/bigquery.rs */}
<LangTabs>
<Fragment slot="python">
@@ -133,7 +166,7 @@ pub struct BigQueryConfig {
**Parameters:**
-- `project` - Optional Google Cloud project used by the BigQuery client.
+- `project` - Optional Google Cloud project that runs the query jobs.
- `credentials_path` - Optional path to a service account JSON key file. If omitted, Application Default Credentials are used.
- `location` - Optional BigQuery job location, for example `US` or `EU`.
@@ -189,13 +222,15 @@ pub struct BigQueryTableOptions {
}
```
-`declare_table_target` and `declare_table_target_with_options` take the same arguments and declare the table in the current component. `ManagedBy::User` is Python's `managed_by="user"`.
+`declare_table_target` and `declare_table_target_with_options` take the same arguments and declare the table in the current component.
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `db` - A `ContextKey[ConnectionConfig]` identifying the connection to use.
- `table_name` - Name of the table.
- `table_schema` - Schema definition including columns and primary key.
@@ -205,12 +240,27 @@ pub struct BigQueryTableOptions {
When `managed_by="system"`, CocoIndex creates the dataset and table if needed. Table changes use BigQuery DDL, and row changes use BigQuery `MERGE` for upserts.
+</Lang>
+
+<Lang only="rust">
+
+- `conn` - The context key of the `BigQueryConnection` to use.
+- `dataset` - BigQuery dataset name.
+- `table_name` - Name of the table.
+- `table_schema` - Schema definition including columns and primary key.
+- `options.project` - Optional project that owns the target table. If `None`, the connection's project is used. `None` and naming the connection's project explicitly are two different keys for the same table (see the caution below).
+- `options.managed_by` - Whether CocoIndex manages the table lifecycle (`ManagedBy::System`, the default) or assumes it exists (`ManagedBy::User`).
+
+With `ManagedBy::System`, CocoIndex creates the dataset and table if needed. Table changes use BigQuery DDL, and row changes use BigQuery `MERGE` for upserts.
+
+</Lang>
+
:::note
BigQuery primary key constraints are not enforced by BigQuery. CocoIndex still uses the primary key list to reconcile rows and generate `MERGE` and `DELETE` statements.
:::
:::caution[One table, one key]
-CocoIndex identifies a table by its key: the `db` key, `project`, `dataset` and `table_name`. `project=None` and `project="<client project>"` reach the same table through two different keys. Declare each table through one form only. Switching a table from one form to the other changes its key: CocoIndex then cleans up the table it tracked under the old key, which is the same table. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity).
+CocoIndex identifies a table by its key: the connection's context key, the project, `dataset` and `table_name`. <Lang only="python">`project=None` and `project="<client project>"`</Lang><Lang only="rust">`project: None` and `project: Some("<connection project>")`</Lang> reach the same table through two different keys. Declare each table through one form only. Switching a table from one form to the other changes its key: CocoIndex then cleans up the table it tracked under the old key, which is the same table. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity).
:::
### Rows
@@ -241,6 +291,8 @@ The row serializes to an object whose keys are column names; keys outside the sc
</Fragment>
</LangTabs>
+<Lang only="python">
+
**Parameters:**
- `row` - A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include all primary key columns.
@@ -249,6 +301,18 @@ The row serializes to an object whose keys are column names; keys outside the sc
Define the table structure using a Python class:
+</Lang>
+
+<Lang only="rust">
+
+Every primary-key column must be present in the row.
+
+## Table schema: from a Rust struct
+
+Define the table structure with a struct that derives `SchemaFields`:
+
+</Lang>
+
{/* Rust: examples/rust/bigquery_target/src/main.rs */}
<LangTabs>
<Fragment slot="python">
@@ -295,30 +359,61 @@ let schema = TableSchema::from_row::<BigQueryOrder>(["order_id"])?;
</Fragment>
</LangTabs>
+<Lang only="python">
+
Python types are automatically mapped to BigQuery column types:
-| Python Type | Rust Type | BigQuery Type |
-|-------------|-----------|---------------|
-| `bool` | `bool` | `BOOL` |
-| `int` | `i16`, `i32`, `i64` (and the unsigned widths) | `INT64` |
-| `float` | `f32`, `f64` | `FLOAT64` |
-| `decimal.Decimal` | `rust_decimal::Decimal` | `NUMERIC` |
-| `str` | `String` | `STRING` |
-| `bytes` | `Vec<u8>` | `BYTES` |
-| `uuid.UUID` | `uuid::Uuid` | `STRING` |
-| `datetime.date` | `chrono::NaiveDate` | `DATE` |
-| `datetime.time` | `chrono::NaiveTime` | `TIME` |
-| `datetime.datetime` | `chrono::DateTime`, `chrono::NaiveDateTime` | `TIMESTAMP` |
-| `datetime.timedelta` | `std::time::Duration` | `FLOAT64` |
-| `list`, `dict`, nested structs | other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `JSON` |
-| | `#[coco(vector)] Vec<f32>` | `ARRAY<FLOAT64>` |
-
-`JSON` values are JSON-serialized and written with `PARSE_JSON`. An `Option<T>` field is a nullable column; every other Rust field is `NOT NULL`.
+| Python Type | BigQuery Type |
+|-------------|---------------|
+| `bool` | `BOOL` |
+| `int` | `INT64` |
+| `float` | `FLOAT64` |
+| `decimal.Decimal` | `NUMERIC` |
+| `str` | `STRING` |
+| `bytes` | `BYTES` |
+| `uuid.UUID` | `STRING` |
+| `datetime.date` | `DATE` |
+| `datetime.time` | `TIME` |
+| `datetime.datetime` | `TIMESTAMP` |
+| `datetime.timedelta` | `FLOAT64` |
+| `list`, `dict`, nested structs | `JSON` |
+
+`JSON` values are JSON-serialized and written with `PARSE_JSON`.
### BigQueryType
Use `BigQueryType` to specify a custom BigQuery type and optional encoder:
+</Lang>
+
+<Lang only="rust">
+
+Rust field types are automatically mapped to BigQuery column types:
+
+| Rust Type | BigQuery Type |
+|-----------|---------------|
+| `bool` | `BOOL` |
+| `i16`, `i32`, `i64` (and the unsigned widths) | `INT64` |
+| `f32`, `f64` | `FLOAT64` |
+| `rust_decimal::Decimal` | `NUMERIC` |
+| `String` | `STRING` |
+| `Vec<u8>` | `BYTES` |
+| `uuid::Uuid` | `STRING` |
+| `chrono::NaiveDate` | `DATE` |
+| `chrono::NaiveTime` | `TIME` |
+| `chrono::DateTime`, `chrono::NaiveDateTime` | `TIMESTAMP` |
+| `std::time::Duration` | `FLOAT64` |
+| other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `JSON` |
+| `#[coco(vector)] Vec<f32>` | `ARRAY<FLOAT64>` |
+
+`JSON` values are JSON-serialized and written with `PARSE_JSON`. An `Option<T>` field is a nullable column; every other field is `NOT NULL`.
+
+### Custom column types
+
+Use `#[coco(type = "…")]` on a field to specify a custom BigQuery type:
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/tests/bigquery_target.rs; #[coco(type)] from rust/sdk/cocoindex_macros/src/lib.rs */}
<LangTabs>
<Fragment slot="python">
@@ -348,12 +443,20 @@ struct ProductRow {
}
```
-`#[coco(type = "…")]` sets the column type verbatim. The Rust SDK has no per-column `encoder`: a value is written as it serializes with serde. Explicit columns are also possible: `TableSchema::new([("id", ColumnDef::new("INT64").not_null()), ("payload", ColumnDef::new("JSON").parse_json())], ["id"])?`. A Rust `ColumnDef` is nullable unless `.not_null()` is called, and `.parse_json()` writes the value through `PARSE_JSON`.
+`#[coco(type = "…")]` sets the column type verbatim. Explicit columns are also possible: `TableSchema::new([("id", ColumnDef::new("INT64").not_null()), ("payload", ColumnDef::new("JSON").parse_json())], ["id"])?`. A `ColumnDef` is nullable unless `.not_null()` is called, and `.parse_json()` writes the value through `PARSE_JSON`.
</Fragment>
</LangTabs>
-You can also pass `column_overrides` when constructing the schema:
+<RustNote>
+There is no per-column `encoder`: a value is written as it serializes with serde.
+</RustNote>
+
+<Lang only="python">You can also pass `column_overrides` when constructing the schema:</Lang><Lang only="rust">You can also override one column of a derived schema with `with_column_type`, which replaces the column's type and its `parse_json` flag and keeps its derived nullability:</Lang>
+
+{/* Rust: rust/sdk/cocoindex/src/connectors/bigquery.rs (TableSchema::with_column_type and its test) */}
+<LangTabs>
+<Fragment slot="python">
```python
schema = await bigquery.TableSchema.from_class(
@@ -365,6 +468,17 @@ schema = await bigquery.TableSchema.from_class(
)
```
+</Fragment>
+<Fragment slot="rust">
+
+```rust
+let schema = TableSchema::from_row::<Row>(["id"])?
+ .with_column_type("payload", ColumnDef::new("JSON").parse_json())?;
+```
+
+</Fragment>
+</LangTabs>
+
## Example
{/* Rust: examples/rust/bigquery_target/src/main.rs */}
@@ -421,7 +535,7 @@ To name the project that owns the table, use `mount_table_target_with_options` w
</Fragment>
</LangTabs>
-See `examples/bigquery_target` for a runnable project, and `examples/rust/bigquery_target` for the Rust one.
+See <Lang only="python">`examples/bigquery_target`</Lang><Lang only="rust">`examples/rust/bigquery_target`</Lang> for a runnable project.
## Identifier handling
diff --git a/docs/src/content/docs/connectors/doris.mdx b/docs/src/content/docs/connectors/doris.mdx
index f3046c75..7d8406db 100644
--- a/docs/src/content/docs/connectors/doris.mdx
+++ b/docs/src/content/docs/connectors/doris.mdx
@@ -27,11 +27,11 @@ use cocoindex::connectors::doris::{
};
```
-The module is compiled with the `doris` Cargo feature of the `cocoindex` crate.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
:::note[Dependencies]
This connector requires additional dependencies. Install with:
@@ -41,10 +41,30 @@ pip install cocoindex[doris]
:::
+</Lang>
+
+<Lang only="rust">
+
+:::note[Dependencies]
+Enable the `doris` Cargo feature of the `cocoindex` crate.
+:::
+
+</Lang>
+
## Connection setup
+<Lang only="python">
+
### DorisConnectionConfig
+</Lang>
+
+<Lang only="rust">
+
+### DorisConfig
+
+</Lang>
+
Configure the connection to your Doris cluster:
{/* Rust: rust/sdk/cocoindex/tests/doris_target.rs */}
@@ -86,6 +106,8 @@ if let Ok(pw) = std::env::var("DORIS_PASSWORD") {
**Parameters:**
+<Lang only="python">
+
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `fe_host` | `str` | *(required)* | Frontend host address |
@@ -98,10 +120,35 @@ if let Ok(pw) = std::env::var("DORIS_PASSWORD") {
| `be_load_host` | `str \| None` | `None` | Override backend host for stream load (defaults to `fe_host`) |
| `batch_size` | `int` | `10000` | Max rows per stream load batch |
| `stream_load_timeout` | `int` | `600` | Timeout (seconds) for stream load |
+| `max_retries` | `int` | `3` | Retries of a failed stream load |
+| `retry_base_delay` | `float` | `1.0` | First retry delay (seconds) |
+| `retry_max_delay` | `float` | `30.0` | Longest retry delay (seconds) |
| `replication_num` | `int` | `1` | Replication factor for new tables |
| `buckets` | `int \| str` | `"auto"` | Bucket count for new tables |
-The Rust `DorisConfig` has the same fields with the same defaults (`buckets` is a `String`), plus `max_retries` (`3`), `retry_base_delay` (`1.0`) and `retry_max_delay` (`30.0`) seconds for Stream Load retries.
+</Lang>
+
+<Lang only="rust">
+
+| Field | Type | Default | Description |
+|-------|------|---------|-------------|
+| `fe_host` | `String` | *(required)* | Frontend host address |
+| `database` | `String` | *(required)* | Database name |
+| `fe_http_port` | `u16` | `8080` | Frontend HTTP port (for stream load) |
+| `query_port` | `u16` | `9030` | MySQL-compatible query port |
+| `username` | `String` | `"root"` | Username |
+| `password` | `String` | `""` | Password |
+| `enable_https` | `bool` | `false` | Use HTTPS for stream load |
+| `be_load_host` | `Option<String>` | `None` | Override backend host for stream load (defaults to `fe_host`) |
+| `batch_size` | `usize` | `10000` | Max rows per stream load batch |
+| `stream_load_timeout` | `u64` | `600` | Timeout (seconds) for stream load |
+| `max_retries` | `u32` | `3` | Retries of a failed stream load |
+| `retry_base_delay` | `f64` | `1.0` | First retry delay (seconds) |
+| `retry_max_delay` | `f64` | `30.0` | Longest retry delay (seconds) |
+| `replication_num` | `u32` | `1` | Replication factor for new tables |
+| `buckets` | `String` | `"auto"` | Bucket count for new tables |
+
+</Lang>
### connect
@@ -154,12 +201,22 @@ The `doris` connector provides target state APIs for writing rows to tables. Coc
#### Setting up a connection
+<Lang only="python">
+
Create a `ContextKey[doris.ManagedConnection]` to identify your connection, then provide it in your lifespan:
+</Lang>
+
+<Lang only="rust">
+
+Declare a context key for a `DorisConnection` with `cocoindex::context_key!`, then provide the connection when you build the environment:
+
+</Lang>
+
:::note
The key name is load-bearing across runs β€” it's the stable identity CocoIndex uses to track managed rows. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.
-CocoIndex tracks each table by the `ContextKey` and the table name. The `database` in `DorisConnectionConfig` is not part of that identity. If you change `database` under the same key, CocoIndex treats it as if you moved the tables there. It assumes that they already exist in the new database, so it does not create them, and it leaves the old database as it is. To write to a new, empty database, use a new `ContextKey`.
+CocoIndex tracks each table by the context key and the table name. The `database` in <Lang only="python">`DorisConnectionConfig`</Lang><Lang only="rust">`DorisConfig`</Lang> is not part of that identity. If you change `database` under the same key, CocoIndex treats it as if you moved the tables there. It assumes that they already exist in the new database, so it does not create them, and it leaves the old database as it is. To write to a new, empty database, use a new context key.
:::
{/* Rust: rust/sdk/cocoindex/tests/doris_target.rs */}
@@ -201,14 +258,14 @@ let app = Environment::builder()
.await?;
```
-`context_key!` declares the key. Its stable name is the identifier, or the `key = "…"` string when given. `provide_key(&DORIS_DB, conn)` provides the connection, in a `#[cocoindex::lifespan]` function or on `Environment::builder()` as here. The Rust connection's identity excludes the `database` in the same way.
+`context_key!` declares the key. Its stable name is the identifier, or the `key = "…"` string when given. `provide_key(&DORIS_DB, conn)` provides the connection, in a `#[cocoindex::lifespan]` function or on `Environment::builder()` as here.
</Fragment>
</LangTabs>
#### Tables (parent state)
-Declares a table as a target state. Returns a `DorisTableTarget` for declaring rows.
+Declares a table as a target state. Returns a <Lang only="python">`DorisTableTarget`</Lang><Lang only="rust">`TableTarget`</Lang> for declaring rows.
{/* Rust: rust/sdk/cocoindex/src/connectors/doris.rs */}
<LangTabs>
@@ -252,13 +309,15 @@ pub struct DorisTableOptions {
}
```
-The handle type is `TableTarget`. `managed_by`, `vector_indexes` and `inverted_indexes` go in `DorisTableOptions`. `declare_table_target` and `declare_table_target_with_options` take the same arguments and return a handle whose rows resolve when the current component commits.
+`managed_by`, `vector_indexes` and `inverted_indexes` go in `DorisTableOptions`. `declare_table_target` and `declare_table_target_with_options` take the same arguments and return a handle whose rows resolve when the current component commits.
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `db` β€” A `ContextKey[doris.ManagedConnection]` identifying the connection to use.
- `table_name` β€” Name of the table.
- `table_schema` β€” Schema definition including columns and primary key (see [Table schema](#table-schema-from-python-class)).
@@ -268,9 +327,34 @@ The handle type is `TableTarget`. `managed_by`, `vector_indexes` and `inverted_i
**Returns:** A pending `DorisTableTarget`. Use the convenience wrapper `await doris.mount_table_target(...)` to resolve.
+</Lang>
+
+<Lang only="rust">
+
+- `conn` β€” The context key of the `DorisConnection` to use.
+- `table_name` β€” Name of the table.
+- `table_schema` β€” Schema definition including columns and primary key (see [Table schema](#table-schema-from-a-rust-struct)).
+- `options.managed_by` β€” Whether CocoIndex manages the table lifecycle (`ManagedBy::System`, the default) or assumes it exists (`ManagedBy::User`).
+- `options.vector_indexes` β€” Vector index definitions (see [Vector indexes](#vector-indexes)).
+- `options.inverted_indexes` β€” Inverted index definitions (see [Inverted indexes](#inverted-indexes)).
+
+**Returns:** A `TableTarget`. It is `Clone` and serializes to its stable key, the table name, so it can be a `mount_each!` / `use_mount!` argument or a memoized function argument:
+
+{/* Rust: examples/rust/sec_edgar_analytics/src/main.rs */}
+```rust
+#[cocoindex::function]
+async fn process_facts(ctx: &Ctx, file: FileEntry, table: doris::TableTarget) -> Result<()> {
+ // ...
+}
+
+mount_each!("facts", facts, |file| process_facts(ctx, file, table)).await?;
+```
+
+</Lang>
+
#### Rows (child states)
-Once a `DorisTableTarget` is resolved, declare rows to be upserted:
+Once a <Lang only="python">`DorisTableTarget`</Lang><Lang only="rust">`TableTarget`</Lang> is resolved, declare rows to be upserted:
{/* Rust: rust/sdk/cocoindex/tests/doris_target.rs */}
<LangTabs>
@@ -303,12 +387,24 @@ target.declare_row(
**Parameters:**
-- `row` β€” A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include all primary key columns. In Rust, any `Serialize` value whose fields match the schema's columns, such as a row struct or a `serde_json::Value` object.
+- `row` β€” <Lang only="python">A row object (dict, dataclass, NamedTuple, or Pydantic model).</Lang><Lang only="rust">Any `Serialize` value whose fields match the schema's columns, such as a row struct or a `serde_json::Value` object.</Lang> Must include all primary key columns.
+
+<Lang only="python">
### Table schema: from Python class
Define the table structure using a Python class:
+</Lang>
+
+<Lang only="rust">
+
+### Table schema: from a Rust struct
+
+Define the table structure with a struct that derives `SchemaFields`:
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/connectors/doris.rs */}
<LangTabs>
<Fragment slot="python">
@@ -343,20 +439,24 @@ impl TableSchema {
}
```
-The Rust row type is a struct that derives `SchemaFields` (and `Serialize`). Python's `column_overrides` become builder calls on the derived schema: `with_vector_schema` or `with_vector_dim` for a vector column, `with_column_type` for a type override.
+The row type is a struct that derives `SchemaFields` (and `Serialize`). Per-column overrides are builder calls on the derived schema: `with_vector_schema` (from an embedder or other `VectorSchemaProvider`) or `with_vector_dim` for a vector column, `with_column_type` for a type override, which keeps the column's nullability and makes it a non-vector column.
</Fragment>
</LangTabs>
+<Lang only="python">
+
**Parameters:**
- `record_type` β€” A record type whose fields define table columns.
- `primary_key` β€” List of column names forming the primary key.
- `column_overrides` β€” Optional per-column overrides for type mapping or vector configuration.
+</Lang>
+
**Example:**
-{/* Rust: rust/sdk/cocoindex/tests/schema_from_row.rs, rust/sdk/SHOWCASE.md (verified against doris.rs) */}
+{/* Rust: rust/sdk/cocoindex/tests/schema_from_row.rs, examples/rust/sec_edgar_analytics/src/main.rs (with_vector_schema) */}
<LangTabs>
<Fragment slot="python">
@@ -395,29 +495,62 @@ let schema = doris::TableSchema::from_row::<DocEmbedding>(["id"])?
</Fragment>
</LangTabs>
-Python types are automatically mapped to Doris types:
-
-| Python Type | Rust Type | Doris Type |
-|-------------|-----------|------------|
-| `bool` | `bool` | `BOOLEAN` |
-| `int` | `i16`, `i32`, `i64` | `BIGINT` |
-| `float` | `f32`, `f64` | `DOUBLE` |
-| `str` | `String` | `STRING` (Rust: `TEXT`) |
-| `bytes` | `Vec<u8>` | `STRING` (base64) |
-| `uuid.UUID` | `Uuid` | `VARCHAR(36)` |
-| `datetime.datetime` | `DateTime`, `NaiveDateTime` | `DATETIME` (Rust: `DATETIME(6)`) |
-| `datetime.date` | `NaiveDate` | `DATE` |
-| `list`, `dict`, nested structs | other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `JSON` |
-| `NDArray` (with vector schema) | `Vec<f32>` with `#[coco(vector)]` | `ARRAY<FLOAT>` |
+<Lang only="python">
-The Rust mapping also covers `NaiveTime` (`VARCHAR(20)`), `Decimal` (`TEXT`) and `Duration` (`BIGINT`).
+Python types are automatically mapped to Doris types:
-`bytes` values are intentionally base64-encoded before writing to `STRING` so arbitrary binary data survives Doris's JSON Stream Load path.
+| Python Type | Doris Type |
+|-------------|------------|
+| `bool` | `BOOLEAN` |
+| `int` | `BIGINT` |
+| `float` | `DOUBLE` |
+| `decimal.Decimal` | `TEXT` |
+| `str` | `TEXT` |
+| `bytes` | `STRING` |
+| `uuid.UUID` | `VARCHAR(36)` |
+| `datetime.datetime` | `DATETIME(6)` |
+| `datetime.date` | `DATE` |
+| `datetime.time` | `VARCHAR(20)` |
+| `datetime.timedelta` | `BIGINT` (microseconds) |
+| `list`, `dict`, nested structs | `JSON` |
+| `NDArray` (with vector schema) | `ARRAY<FLOAT>` |
+
+`bytes` values are decoded as UTF-8 before writing to `STRING`; invalid UTF-8 sequences are replaced.
#### DorisType
Use `DorisType` to specify a custom Doris type:
+</Lang>
+
+<Lang only="rust">
+
+Rust field types are automatically mapped to Doris types:
+
+| Rust Type | Doris Type |
+|-----------|------------|
+| `bool` | `BOOLEAN` |
+| `i16`, `i32`, `i64` | `BIGINT` |
+| `f32`, `f64` | `DOUBLE` |
+| `Decimal` | `TEXT` |
+| `String` | `TEXT` |
+| `Vec<u8>` | `STRING` (base64) |
+| `Uuid` | `VARCHAR(36)` |
+| `DateTime`, `NaiveDateTime` | `DATETIME(6)` |
+| `NaiveDate` | `DATE` |
+| `NaiveTime` | `VARCHAR(20)` |
+| `Duration` | `BIGINT` |
+| other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `JSON` |
+| `Vec<f32>` with `#[coco(vector)]` | `ARRAY<FLOAT>` (`NOT NULL`) |
+
+`Vec<u8>` values are base64-encoded before writing to `STRING` so arbitrary binary data survives Doris's JSON Stream Load path.
+
+#### Custom column types
+
+Use `#[coco(type = "…")]` on a field to specify a custom Doris type:
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/row_schema.rs, rust/sdk/cocoindex/src/connectors/doris.rs (with_column_type) */}
<LangTabs>
<Fragment slot="python">
@@ -498,14 +631,14 @@ impl VectorIndexDef {
**Parameters:**
-| Parameter | Type | Default | Description |
-|-----------|------|---------|-------------|
-| `field_name` | `str` | *(required)* | Column to index |
-| `index_type` | `str` | `"HNSW"` | Index type: `"HNSW"` or `"IVF"` |
-| `metric_type` | `str` | `"l2_distance"` | Distance metric: `"l2_distance"` or `"cosine_distance"` |
-| `max_degree` | `int \| None` | `None` | HNSW max degree |
-| `ef_construction` | `int \| None` | `None` | HNSW construction parameter |
-| `nlist` | `int \| None` | `None` | IVF number of partitions |
+| Parameter | Default | Description |
+|-----------|---------|-------------|
+| `field_name` | *(required)* | Column to index |
+| `index_type` | `"HNSW"` | Index type: `"HNSW"` or `"IVF"` |
+| `metric_type` | `"l2_distance"` | Distance metric: `"l2_distance"`, `"inner_product"` or `"cosine_distance"` |
+| `max_degree` | `None` | HNSW max degree |
+| `ef_construction` | `None` | HNSW construction parameter |
+| `nlist` | `None` | IVF number of partitions |
### Inverted indexes
@@ -546,7 +679,7 @@ let target =
**Parameters:**
- `field_name` β€” Column to index.
-- `parser` β€” Optional tokenizer for full-text search (e.g., `"unicode"`, `"english"`, `"chinese"`). If `None`, the index supports exact matching only.
+- `parser` β€” Optional tokenizer for full-text search (e.g., `"unicode"`, `"english"`, `"chinese"`). Without one, the index supports exact matching only.
### Query helpers
@@ -618,6 +751,8 @@ let sql = doris::build_vector_search_query(
</Fragment>
</LangTabs>
+<Lang only="python">
+
#### connect_async
Create an async MySQL connection for running queries:
@@ -632,7 +767,19 @@ async def connect_async(
) -> Any # aiomysql connection
```
-The Rust SDK has no `connect_async`: `DorisConnection::pool()` returns the `sqlx::MySqlPool` the connection already holds, and queries run on it.
+</Lang>
+
+<Lang only="rust">
+
+#### Running queries
+
+`DorisConnection::pool()` returns the `sqlx::MySqlPool` the connection holds; run queries on it.
+
+</Lang>
+
+<RustNote>
+There is no `connect_async`: queries run on the pool of the `DorisConnection` itself.
+</RustNote>
### Example
@@ -747,7 +894,7 @@ app.run(move |ctx| async move {
.await?;
```
-There is no Rust example program for Doris yet; `rust/sdk/cocoindex/tests/doris_target.rs` is the end-to-end reference.
+`examples/rust/sec_edgar_analytics` is a runnable project: one Doris table with a vector index and an inverted index, fed per file through `mount_each!`. `rust/sdk/cocoindex/tests/doris_target.rs` is the end-to-end test.
</Fragment>
</LangTabs>
diff --git a/docs/src/content/docs/connectors/falkordb.mdx b/docs/src/content/docs/connectors/falkordb.mdx
index 3d8dda27..2e8a775c 100644
--- a/docs/src/content/docs/connectors/falkordb.mdx
+++ b/docs/src/content/docs/connectors/falkordb.mdx
@@ -25,11 +25,11 @@ from cocoindex.connectors import falkordb
use cocoindex::connectors::falkordb::{self, TableSchema};
```
-The Rust SDK needs the `falkordb` Cargo feature of the `cocoindex` crate.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
:::note[Dependencies]
This connector requires additional dependencies. Install with:
@@ -39,10 +39,30 @@ pip install cocoindex[falkordb]
:::
+</Lang>
+
+<Lang only="rust">
+
+:::note[Dependencies]
+Enable the `falkordb` Cargo feature of the `cocoindex` crate.
+:::
+
+</Lang>
+
## Connection setup
+<Lang only="python">
+
Create a `ConnectionFactory` and provide it via a `ContextKey`. The factory holds the FalkorDB URI plus the target graph name; it opens one connection-pooled client per event loop, on first use on that loop, shared by all tables and batches. Call `await factory.close()` at shutdown (in the lifespan, after `yield`) to close it.
+</Lang>
+
+<Lang only="rust">
+
+Connect a `falkordb::Graph` and provide it under a context key declared with `cocoindex::context_key!`. The graph holds the FalkorDB URI plus the target graph name, over one multiplexed Redis connection shared by all tables and batches.
+
+</Lang>
+
:::note
The key name is load-bearing across runs β€” it's the stable identity CocoIndex uses to track managed rows. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.
:::
@@ -101,7 +121,7 @@ async fn main() -> Result<()> {
### Multitenancy
-A single Redis instance can host many fully isolated graphs. Pair each graph with its own `ContextKey` and `ConnectionFactory(graph=...)`:
+A single Redis instance can host many fully isolated graphs. Pair each graph with its own <Lang only="python">`ContextKey` and `ConnectionFactory(graph=...)`</Lang><Lang only="rust">context key and `falkordb::Graph::connect(uri, graph)`</Lang>:
{/* Rust: examples/rust/meeting_notes_graph_falkordb/src/main.rs (two keys instead of one) */}
<LangTabs>
@@ -146,7 +166,7 @@ let app = Environment::builder()
</Fragment>
</LangTabs>
-Different `ContextKey`s with different graph names produce fully separate target-state trees β€” changes to one never spill into the other.
+Different context keys with different graph names produce fully separate target-state trees β€” changes to one never spill into the other.
## As target
@@ -154,17 +174,23 @@ The `falkordb` connector provides target state APIs for writing nodes to node ta
Each `graph.query` call against FalkorDB is its own atomic unit (FalkorDB does not expose multi-statement transactions); the connector orders writes within a batch as **node upserts β†’ relation upserts β†’ relation deletes β†’ node deletes** so dependent edges always see their endpoints.
+<Lang only="python">
+
:::note
The node and relationship APIs below replace the table and relation APIs (`mount_table_target`, `mount_relation_target`, …), which are deprecated. To move an existing table over, see [Deprecated: table and relation APIs](#deprecated-table-and-relation-apis).
:::
-The Rust SDK names its functions `mount_table_target` / `TableTarget` and `mount_relation_target` / `RelationTarget`. They are the Rust node and relationship APIs, not the deprecated Python ones: a node table and a relationship table live in separate key spaces, so a label and a relationship type may share a name, and a derived edge id has the length-prefixed form described under [Relationships](#relationships-child-states). The Rust SDK has no deprecated API.
+</Lang>
+
+<RustNote>
+The functions are named `mount_table_target` / `TableTarget` and `mount_relation_target` / `RelationTarget`. They are the node and relationship APIs, not the deprecated Python table and relation APIs of the same names: a node table and a relationship table live in separate key spaces, so a label and a relationship type may share a name, and a derived edge id has the length-prefixed form described under [Relationships](#relationships-child-states). There is no deprecated API.
+</RustNote>
### Declaring target states
#### Node tables (parent state)
-Declares a node label as a target state. Returns a `NodeTarget` for declaring nodes.
+Declares a node label as a target state. Returns a <Lang only="python">`NodeTarget`</Lang><Lang only="rust">`TableTarget`</Lang> for declaring nodes.
{/* Rust: rust/sdk/cocoindex/src/cypher_graph.rs (graph_target_api! macro) */}
<LangTabs>
@@ -201,13 +227,15 @@ pub fn declare_table_target_with_options(
) -> Result<TableTarget>
```
-The schema is required. It carries the primary key: `TableSchema::from_row::<Row>("id")?` derives the columns from a row struct, and `TableSchema::schemaless("id")?` declares no columns (Python's `table_schema=None`). `ManagedTargetOptions::user_managed()` is Python's `managed_by="user"`; the default is system-managed.
+`mount_table_target` and `mount_table_target_with_options` take the same arguments, are `async`, and return a handle whose records resolve immediately. The schema is required. It carries the primary key: `TableSchema::from_row::<Row>("id")?` derives the columns from a row struct, and `TableSchema::schemaless("id")?` declares no columns. `ManagedTargetOptions::user_managed()` makes the table user-managed; the default is system-managed.
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `db` β€” A `ContextKey[falkordb.ConnectionFactory]` for the FalkorDB connection.
- `table_name` β€” The Cypher node label (e.g. `"Document"`).
- `table_schema` β€” Optional schema definition (see [Table Schema](#table-schema-from-python-class)). FalkorDB does not enforce per-property types server-side, so the schema participates in CocoIndex's fingerprint (so two flows declaring the same label must agree) but no per-column DDL is emitted.
@@ -216,9 +244,22 @@ The schema is required. It carries the primary key: `TableSchema::from_row::<Row
**Returns:** A pending `NodeTarget`. Use `await falkordb.mount_node_target(KG_DB, ...)` to get a resolved target.
+</Lang>
+
+<Lang only="rust">
+
+- `graph` β€” The context key of the `falkordb::Graph`.
+- `table_name` β€” The Cypher node label (e.g. `"Meeting"`).
+- `schema` β€” Schema definition (see [Table schema](#table-schema-from-a-rust-struct)), which names the single primary-key property. FalkorDB does not enforce per-property types server-side, so the schema participates in CocoIndex's fingerprint (so two flows declaring the same label must agree) but no per-column DDL is emitted. Compound primary keys are not supported.
+- `options` β€” `ManagedTargetOptions::default()` (system-managed) or `ManagedTargetOptions::user_managed()`.
+
+**Returns:** A `TableTarget`. It is cheap to clone and serializes to its stable key, the graph's context key name and the label, so it can be a `mount_each!` / `use_mount!` argument or a memoized function argument.
+
+</Lang>
+
#### Nodes (child states)
-Once a `NodeTarget` is resolved, declare nodes to be upserted (translated to `MERGE (n:Label {pk: $key_0}) SET n += $props`):
+Once a <Lang only="python">`NodeTarget`</Lang><Lang only="rust">`TableTarget`</Lang> is resolved, declare nodes to be upserted (translated to `MERGE (n:Label {pk: $key_0}) SET n += $props`):
{/* Rust: rust/sdk/cocoindex/src/cypher_graph.rs (graph_target_api! macro) */}
<LangTabs>
@@ -249,15 +290,19 @@ The node's primary-key value is passed as `id` (a `&str`, `String`, `i64` or `u6
</Fragment>
</LangTabs>
+<Lang only="python">
+
**Parameters:**
- `row` β€” A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include the `primary_key` field declared above.
-`declare_row` is an alias for `declare_record`, for compatibility with Postgres and other RDBMS targets. The Rust `TableTarget` has `declare_record` only.
+`declare_row` is an alias for `declare_record`, for compatibility with Postgres and other RDBMS targets.
+
+</Lang>
#### Relationship tables (parent state)
-Declares a relationship type as a target state. Returns a `RelationshipTarget` for declaring edges.
+Declares a relationship type as a target state. Returns a <Lang only="python">`RelationshipTarget`</Lang><Lang only="rust">`RelationTarget`</Lang> for declaring edges.
{/* Rust: rust/sdk/cocoindex/src/cypher_graph.rs (graph_target_api! macro) */}
<LangTabs>
@@ -308,13 +353,15 @@ pub fn declare_relation_target_with_options(
) -> Result<RelationTarget>
```
-Without a schema the relationship is schemaless and keyed by its `id` property. A schema names the primary key: `TableSchema::from_row::<Edge>("edge_id")?` or `TableSchema::schemaless("edge_id")?`.
+Without a schema the relationship is schemaless and keyed by its `id` property. A schema names the primary key: `TableSchema::from_row::<Edge>("edge_id")?` or `TableSchema::schemaless("edge_id")?`. The `mount_relation_target`, `mount_relation_target_with_schema` and `mount_relation_target_with_options` variants take the same arguments and are `async`.
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `db` β€” A `ContextKey[falkordb.ConnectionFactory]` for the FalkorDB connection.
- `table_name` β€” The Cypher relationship type (e.g. `"MENTION"`). A node label and a relationship type may share a name.
- `from_table` β€” The node target whose nodes are the *source* endpoints of edges in this relationship. A `TableTarget` of the deprecated table API works too.
@@ -325,9 +372,24 @@ Without a schema the relationship is schemaless and keyed by its `id` property.
**Returns:** A pending `RelationshipTarget`. Use `await falkordb.mount_relationship_target(KG_DB, ...)` to get a resolved target.
+</Lang>
+
+<Lang only="rust">
+
+- `graph` β€” The context key of the `falkordb::Graph`.
+- `relation_name` β€” The Cypher relationship type (e.g. `"ATTENDED"`). A node label and a relationship type may share a name.
+- `from_table` β€” The node target whose nodes are the *source* endpoints of edges in this relationship.
+- `to_table` β€” The node target whose nodes are the *target* endpoints of edges in this relationship.
+- `schema` β€” Schema for the relationship's own properties (see [Table schema](#table-schema-from-a-rust-struct)). It names the primary-key property that uniquely identifies each edge.
+- `options` β€” `ManagedTargetOptions::default()` (system-managed) or `ManagedTargetOptions::user_managed()`.
+
+**Returns:** A `RelationTarget`. Like a `TableTarget`, it is cheap to clone and serializes to its stable key (the graph's context key name and the relationship type), so it can be a `mount_each!` / `use_mount!` or memoized function argument.
+
+</Lang>
+
#### Relationships (child states)
-Once a `RelationshipTarget` is resolved, declare edges. Each declaration MERGEs the source endpoint, the target endpoint, then the relationship.
+Once a <Lang only="python">`RelationshipTarget`</Lang><Lang only="rust">`RelationTarget`</Lang> is resolved, declare edges. Each declaration MERGEs the source endpoint, the target endpoint, then the relationship.
{/* Rust: rust/sdk/cocoindex/src/cypher_graph.rs (graph_target_api! macro) */}
<LangTabs>
@@ -372,15 +434,15 @@ pub fn RelationTarget::declare_relation_record<R: serde::Serialize>(
- `from_id` β€” The source node's primary-key value. The connector MERGEs `(s:FromLabel {pk: $from_id})` so endpoints are auto-created if absent.
- `to_id` β€” The target node's primary-key value. Same MERGE behavior.
-- `record` β€” Optional row object whose fields populate the relationship's properties. Its `primary_key` field, if present, is the edge's id.
+- `record` β€” <Lang only="python">Optional row object</Lang><Lang only="rust">A `Serialize` value (with `declare_relation_record`)</Lang> whose fields populate the relationship's properties. Its primary-key field, if present, is the edge's id.
-If `record` is omitted or has no primary key value, the connector derives the edge id from its endpoints: the source label, source id, target label and target id, each written as `<UTF-8 byte length>:<value>;`. For example, an edge from `Person` `"alice"` to `Task` `42` gets the id `6:Person;5:alice;4:Task;2:42;`. A string id that reads as an integer, or that starts with `s:`, is written with an `s:` prefix, so the ids `1` and `"1"` never share an edge. Endpoint ids must then be `int` or `str`; for other types, pass a `record` that carries the primary key.
+If `record` is omitted or has no primary key value, the connector derives the edge id from its endpoints: the source label, source id, target label and target id, each written as `<UTF-8 byte length>:<value>;`. For example, an edge from `Person` `"alice"` to `Task` `42` gets the id `6:Person;5:alice;4:Task;2:42;`. A string id that reads as an integer, or that starts with `s:`, is written with an `s:` prefix, so the ids `1` and `"1"` never share an edge. <Lang only="python">Endpoint ids must then be `int` or `str`; for other types, pass a `record` that carries the primary key.</Lang><Lang only="rust">Endpoint ids are strings or integers.</Lang>
-An edge id names one edge. When the endpoints of an edge with an explicit id change, the edge moves: the upsert deletes the relationship of this type with the same id between the old endpoints. To find it, every upsert looks the edge up by its primary key property. A system-managed relationship table has an index on it; for a `managed_by="user"` table, create one yourself.
+An edge id names one edge. When the endpoints of an edge with an explicit id change, the edge moves: the upsert deletes the relationship of this type with the same id between the old endpoints. To find it, every upsert looks the edge up by its primary key property. A system-managed relationship table has an index on it; for a user-managed table, create one yourself.
#### Vector indexes (attachment)
-Declares a vector index on a column of a node table. Vector indexes are an [attachment](../advanced_topics/custom_target_connector#implementing-attachment-providers) to a `NodeTarget`:
+Declares a vector index on a column of a node table. Vector indexes are an [attachment](../advanced_topics/custom_target_connector#implementing-attachment-providers) to a <Lang only="python">`NodeTarget`</Lang><Lang only="rust">`TableTarget`</Lang>:
{/* Rust: rust/sdk/cocoindex/src/cypher_graph.rs (graph_target_api! macro); usage in rust/sdk/cocoindex/tests/graph_vector_index.rs */}
<LangTabs>
@@ -426,11 +488,13 @@ table.declare_vector_index(&ctx, "embedding", 3, VectorMetric::Cosine)?;
table.declare_node_index(&ctx, &["name"])?;
```
-`VectorMetric::Cosine`, `VectorMetric::Euclidean` and `VectorMetric::InnerProduct` (Python's `"ip"`) are the FalkorDB metrics. The default declared name in Rust is `vec_{table}__{field}`, not `idx_{table}__{field}`; give the name with `declare_vector_index_named` to keep a declaration's identity across the two SDKs. `declare_node_index(ctx, &["name"])` declares a plain secondary index on the listed properties.
+`VectorMetric::Cosine`, `VectorMetric::Euclidean` and `VectorMetric::InnerProduct` are the FalkorDB metrics, translated to FalkorDB's `similarityFunction` option. `declare_vector_index` names the declaration `vec_{table}__{field}`; `declare_vector_index_named` takes the name. `declare_node_index(ctx, &["name"])` declares a plain secondary index on the listed properties.
</Fragment>
</LangTabs>
+<Lang only="python">
+
**Parameters:**
- `name` β€” Optional logical name for the index. Defaults to `f"idx_{table_name}__{field}"`.
@@ -438,16 +502,34 @@ table.declare_node_index(&ctx, &["name"])?;
- `metric` β€” Similarity metric: `"cosine"`, `"euclidean"`, or `"ip"` (inner product). Translated to FalkorDB's `similarityFunction` option.
- `dimension` β€” The vector's dimension. Required.
+</Lang>
+
+<RustNote>
+The default declared name is `vec_{table}__{field}`, where Python's is `idx_{table}__{field}`. To keep a declaration's identity when you move a pipeline between the two SDKs, give the name with `declare_vector_index_named`.
+</RustNote>
+
The connector emits `CREATE VECTOR INDEX FOR (e:Label) ON (e.field) OPTIONS {dimension: N, similarityFunction: '...'}`.
FalkorDB identifies a vector index by its label and field, not by `name`, so a field has at most one vector index. Renaming `name` keeps the index. Declaring a second name for the same field is an error.
Vectors are float32 only β€” wider vector dtypes are not supported.
+<Lang only="python">
+
### Table schema: from Python class
Build a `TableSchema` by introspecting a record type:
+</Lang>
+
+<Lang only="rust">
+
+### Table schema: from a Rust struct
+
+Build a `TableSchema` from a struct that derives `SchemaFields`:
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/cypher_graph.rs (TableSchema::from_row doc example); usage in rust/sdk/cocoindex/tests/graph_target.rs */}
<LangTabs>
<Fragment slot="python">
@@ -483,16 +565,18 @@ struct Person {
let schema = cocoindex::connectors::falkordb::TableSchema::from_row::<Person>("id")?;
```
-`primary_key` has no default in Rust and must name a field of the struct. An `Option<T>` field is a nullable column.
+`primary_key` has no default and must name a field of the struct. An `Option<T>` field is a nullable column.
</Fragment>
</LangTabs>
+<Lang only="python">
+
**Parameters:**
- `record_type` β€” A dataclass, NamedTuple, or Pydantic model.
- `primary_key` β€” Field name to use as the table's primary key. Defaults to `"id"`.
-- `column_overrides` β€” Optional dict mapping field names to `FalkorType` or `VectorSchemaProvider` to override the default Python-to-FalkorDB type mapping. In Rust, a `#[coco(..)]` attribute on the field does this (see below).
+- `column_overrides` β€” Optional dict mapping field names to `FalkorType` or `VectorSchemaProvider` to override the default Python-to-FalkorDB type mapping.
**Returns:** A `TableSchema[RowT]` populated from the class's fields.
@@ -512,8 +596,6 @@ let schema = cocoindex::connectors::falkordb::TableSchema::from_row::<Person>("i
| `numpy.ndarray` (with `VectorSchema` annotation) | `vector<float32, N>` | Encoded as `list[float]`. |
| `dict`, list, nested record, `Any` | `map` / `array` | Passed through native parameter binding. |
-The Rust SDK shares one type table between its Neo4j and FalkorDB connectors, and records the Cypher type names of the [Neo4j connector](./neo4j#default-python--neo4j-type-mapping) (`BOOLEAN`, `INTEGER`, `FLOAT`, `STRING`, `BYTES`, `DATE`, `LOCAL_TIME`, `ZONED_DATETIME`, `DURATION`, `LIST<FLOAT>` for `#[coco(vector)]`, `MAP` for collections and nested structs). The type is metadata only, so no DDL is emitted from it; a value is written as it serializes with serde.
-
#### FalkorType
Override the default mapping for a single column with `FalkorType`:
@@ -526,6 +608,20 @@ class FalkorType(NamedTuple):
Use with `typing.Annotated`:
+</Lang>
+
+<Lang only="rust">
+
+#### Default Rust β†’ FalkorDB type mapping
+
+The FalkorDB and [Neo4j](./neo4j) connectors share one type table, which records Cypher type names: `BOOLEAN`, `INTEGER`, `FLOAT`, `STRING`, `BYTES`, `DATE`, `LOCAL_TIME`, `ZONED_DATETIME`, `DURATION`, `LIST<FLOAT>` for `#[coco(vector)]`, and `MAP` for collections and nested structs. The type is metadata only, so no DDL is emitted from it; a value is written as it serializes with serde.
+
+#### Custom column types
+
+Override the default mapping for a single column with a field attribute:
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/tests/graph_target.rs (from_row_matches_explicit_schema) */}
<LangTabs>
<Fragment slot="python">
@@ -557,20 +653,47 @@ struct Row {
}
```
-`#[coco(type = "…")]` records the type string verbatim, `#[coco(json)]` records `MAP` for a field that would map to another type, and `#[coco(rename = "…")]` names the property. The Rust SDK has no per-column `encoder`: a value is written as it serializes with serde.
+`#[coco(type = "…")]` records the type string verbatim, `#[coco(json)]` records `MAP` for a field that would map to another type, and `#[coco(rename = "…")]` names the property.
</Fragment>
</LangTabs>
-The `falkor_type` string is metadata-only β€” it participates in the schema fingerprint (so two flows declaring the same table must agree) but no DDL is emitted from it.
+<Lang only="rust">
+
+To override a column for one schema only, call `with_column_type` on the derived schema. It replaces the column's type and keeps its nullability:
+
+{/* Rust: rust/sdk/cocoindex/tests/graph_target.rs (from_row_takes_column_type_overrides) */}
+```rust
+let schema = TableSchema::from_row::<Row>("id")?.with_column_type("location", "POINT")?;
+```
+
+</Lang>
+
+<RustNote>
+There is no per-column `encoder`: a value is written as it serializes with serde.
+</RustNote>
+
+The <Lang only="python">`falkor_type`</Lang><Lang only="rust">type</Lang> string is metadata-only β€” it participates in the schema fingerprint (so two flows declaring the same table must agree) but no DDL is emitted from it.
+
+<Lang only="python">
#### VectorSchemaProvider
-For NumPy `ndarray` columns, attach a `VectorSchema` annotation to specify dtype + dimension. See [VectorSchema](../common_resources/vector_schema) for details. In Rust, mark the field `#[coco(vector)]` (or `#[coco(vector = N)]`); the property is recorded as `LIST<FLOAT>`, and the dimension belongs to the vector index declaration, not the property.
+For NumPy `ndarray` columns, attach a `VectorSchema` annotation to specify dtype + dimension. See [VectorSchema](../common_resources/vector_schema) for details.
+
+</Lang>
+
+<Lang only="rust">
+
+#### Vector fields
+
+Mark a vector field `#[coco(vector)]` (or `#[coco(vector = N)]`). The property is recorded as `LIST<FLOAT>`, and the dimension belongs to the vector index declaration, not the property.
+
+</Lang>
### Table schema: explicit column definitions
-Build a `TableSchema` directly from a dict of column definitions when the row type is dynamic:
+Build a `TableSchema` directly from <Lang only="python">a dict of</Lang><Lang only="rust">a list of</Lang> column definitions when the row type is dynamic:
{/* Rust: rust/sdk/cocoindex/tests/graph_target.rs (from_row_matches_explicit_schema) */}
<LangTabs>
@@ -605,16 +728,27 @@ let schema = TableSchema::new(
)?;
```
-A Rust `ColumnDef` is `NOT NULL` unless `.nullable()` is called.
+A `ColumnDef` is `NOT NULL` unless `.nullable()` is called.
</Fragment>
</LangTabs>
`ColumnDef` fields:
-- `type` β€” The FalkorDB type string (metadata only; see table above). `cypher_type` in Rust.
-- `nullable` β€” Whether the column may be `None`. Defaults to `True` in Python and to `false` in Rust.
-- `encoder` β€” Optional `Callable[[Any], Any]` applied to non-`None` values before they're sent to FalkorDB. Not available in Rust.
+<Lang only="python">
+
+- `type` β€” The FalkorDB type string (metadata only; see table above).
+- `nullable` β€” Whether the column may be `None`. Defaults to `True`.
+- `encoder` β€” Optional `Callable[[Any], Any]` applied to non-`None` values before they're sent to FalkorDB.
+
+</Lang>
+
+<Lang only="rust">
+
+- `cypher_type` β€” The type string (metadata only; see above).
+- `nullable` β€” Whether the column may be null. Defaults to `false`; `.nullable()` sets it.
+
+</Lang>
### DDL: indexes and constraints
@@ -625,11 +759,11 @@ For each managed table, the connector creates the supporting Cypher index on the
It then attempts a uniqueness constraint via the `GRAPH.CONSTRAINT CREATE` Redis command (best-effort β€” failures are logged but do not abort).
-A system-managed table owns its label or relationship type, the way a Postgres table owns its rows. When the table is no longer declared, or on `cocoindex drop`, the connector destroys it: every node carrying the label is deleted (`DETACH DELETE`, so the relationships attached to those nodes go with them) or every relationship of the type is deleted, and then the constraint and index are dropped. A node table's vector indexes (every vector index on its label) are dropped with it. This includes nodes and relationships written under that label or type by anything other than CocoIndex β€” to share a label with data CocoIndex doesn't own, declare the table with `managed_by="user"`.
+A system-managed table owns its label or relationship type, the way a Postgres table owns its rows. When the table is no longer declared, or on `cocoindex drop`, the connector destroys it: every node carrying the label is deleted (`DETACH DELETE`, so the relationships attached to those nodes go with them) or every relationship of the type is deleted, and then the constraint and index are dropped. A node table's vector indexes (every vector index on its label) are dropped with it. This includes nodes and relationships written under that label or type by anything other than CocoIndex β€” to share a label with data CocoIndex doesn't own, declare the table <Lang only="python">with `managed_by="user"`</Lang><Lang only="rust">with `ManagedTargetOptions::user_managed()`</Lang>.
The same teardown happens when a table's identity changes β€” its primary key field, or a relationship table's endpoint tables or their primary keys: the table is destroyed and recreated, and the components that declared its records are reprocessed. Its vector indexes are dropped and created again. Attaching a schema or changing a property type does not rebuild the table; at most the records are re-upserted.
-When `managed_by="user"` is set, the connector skips DDL entirely (you're responsible for creating and dropping the index and constraint) and never bulk-deletes: when the table is no longer declared or the app is dropped, its nodes or relationships are left as-is (see [Destroy vs. Abandon](../programming_guide/target_state#how-cocoindex-syncs-target-states)). Record-level upserts and deletes still work while the table is declared. In Rust, pass `ManagedTargetOptions::user_managed()` to `mount_table_target_with_options` or `mount_relation_target_with_options`.
+When <Lang only="python">`managed_by="user"` is set</Lang><Lang only="rust">a table is user-managed</Lang>, the connector skips DDL entirely (you're responsible for creating and dropping the index and constraint) and never bulk-deletes: when the table is no longer declared or the app is dropped, its nodes or relationships are left as-is (see [Destroy vs. Abandon](../programming_guide/target_state#how-cocoindex-syncs-target-states)). Record-level upserts and deletes still work while the table is declared.<Lang only="rust"> Pass `ManagedTargetOptions::user_managed()` to `mount_table_target_with_options` or `mount_relation_target_with_options`.</Lang>
### Example: Node tables
@@ -871,11 +1005,11 @@ An edge with properties of its own is declared with `declare_relation_record`; o
</Fragment>
</LangTabs>
-The `Entity` table is declared up-front (via `mount_node_target`) so its index and constraint are reconciled before any `RELATIONSHIP` edge MERGEs entity endpoints. The relationship's three-MERGE pattern (source endpoint β†’ target endpoint β†’ edge) means missing endpoints are auto-created β€” but it's good practice to declare them explicitly so deletion-cascade behavior stays predictable.
+<Lang only="python">The `Entity` table is declared up-front (via `mount_node_target`) so its index and constraint are reconciled before any `RELATIONSHIP` edge MERGEs entity endpoints.</Lang><Lang only="rust">The `Person`, `Meeting` and `Task` tables are mounted up-front so their indexes and constraints are reconciled before any edge MERGEs their endpoints.</Lang> The relationship's three-MERGE pattern (source endpoint β†’ target endpoint β†’ edge) means missing endpoints are auto-created β€” but it's good practice to declare them explicitly so deletion-cascade behavior stays predictable.
-## Deprecated: table and relation APIs
+<Lang only="python">
-This section applies to the Python SDK only. The Rust SDK's `mount_table_target` and `mount_relation_target` are its current API, with the node and relationship semantics described above.
+## Deprecated: table and relation APIs
The table and relation APIs are deprecated. They emit a `DeprecationWarning` and otherwise work as before. Each has a replacement with the same parameters:
@@ -904,3 +1038,5 @@ Switching a table from the deprecated API to its replacement keeps its nodes, ed
Run the two steps as separate updates, in this order. Without step 1, removing a deprecated declaration destroys its table: every node of the label or edge of the type is deleted, possibly after the new table has written it.
You can switch tables one at a time: a new relationship table accepts node targets of both APIs.
+
+</Lang>
diff --git a/docs/src/content/docs/connectors/lancedb.mdx b/docs/src/content/docs/connectors/lancedb.mdx
index 0c5e1c29..ed1c4dcf 100644
--- a/docs/src/content/docs/connectors/lancedb.mdx
+++ b/docs/src/content/docs/connectors/lancedb.mdx
@@ -5,8 +5,12 @@ description: >
Write and upsert rows to LanceDB tables with automatic schema inference from
Python classes, vector columns via VectorSchemaProvider, and both
system-managed and user-managed table lifecycles.
+rust_description: >
+ Write and upsert rows to LanceDB tables with schemas derived from Rust structs,
+ vector columns via VectorSchemaProvider, and both system-managed and
+ user-managed table lifecycles.
---
-The `lancedb` connector provides utilities for writing rows to LanceDB tables, with automatic schema inference from Python classes and support for declaring vector and full-text search (FTS) indexes. CocoIndex manages the table lifecycle (creating, dropping, and evolving the schema) and keeps rows in sync via incremental upserts and deletions.
+The `lancedb` connector provides utilities for writing rows to LanceDB tables, with automatic schema inference from <Lang only="python">Python classes</Lang><Lang only="rust">Rust structs</Lang> and support for declaring vector and full-text search (FTS) indexes. CocoIndex manages the table lifecycle (creating, dropping, and evolving the schema) and keeps rows in sync via incremental upserts and deletions.
import LangTabs from '../../../components/LangTabs.astro';
@@ -25,11 +29,11 @@ from cocoindex.connectors import lancedb
use cocoindex::connectors::lancedb::{self, LanceDatabase, TableSchema};
```
-The module is compiled with the `lancedb` Cargo feature of the `cocoindex` crate.
-
</Fragment>
</LangTabs>
+<Lang only="python">
+
:::note[Dependencies]
This connector requires additional dependencies. Install with:
@@ -39,11 +43,31 @@ pip install cocoindex[lancedb]
:::
+</Lang>
+
+<Lang only="rust">
+
+:::note[Dependencies]
+The module is compiled with the `lancedb` Cargo feature of the `cocoindex` crate. It is built on the native [`lancedb`](https://docs.rs/lancedb) crate and Arrow.
+:::
+
+</Lang>
+
## Connection setup
+<Lang only="python">
+
LanceDB connections are created directly via the LanceDB library. CocoIndex exposes thin wrappers:
-{/* Rust: rust/sdk/cocoindex/src/connectors/lancedb.rs */}
+</Lang>
+
+<Lang only="rust">
+
+A `LanceDatabase` wraps a `lancedb::Connection`. It is cheap to clone: the connection is shared.
+
+</Lang>
+
+{/* Rust: rust/sdk/cocoindex/src/connectors/lancedb.rs (LanceDatabase, ConnectOptions) */}
<LangTabs>
<Fragment slot="python">
@@ -58,25 +82,49 @@ def connect(uri: str, **options: Any) -> lancedb.DBConnection
```rust
impl LanceDatabase {
pub async fn connect(uri: &str) -> Result<Self>
+ pub async fn connect_with_options(uri: &str, options: ConnectOptions) -> Result<Self>
+ pub fn state_id(&self) -> &str
pub fn connection(&self) -> &lancedb::Connection
}
-```
-`LanceDatabase::connect(uri)` opens (or creates) the database through the [`lancedb`](https://docs.rs/lancedb) crate; `connection()` returns the underlying `lancedb::Connection` for queries. The Rust SDK takes no `**options`.
+#[derive(Clone, Debug, Default)]
+pub struct ConnectOptions {
+ /// How long a table handle may serve reads from a stale version before it
+ /// checks for a newer one. `None` reads a table version once per handle;
+ /// `Duration::ZERO` checks on every read.
+ pub read_consistency_interval: Option<Duration>,
+ /// Object-store options (`aws_access_key_id`, `timeout`, ...) for a
+ /// cloud-storage URI.
+ pub storage_options: BTreeMap<String, String>,
+}
+```
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `uri` β€” LanceDB URI (local path like `"./lancedb_data"` or cloud URI like `"s3://bucket/path"`).
- `**options` β€” Additional options passed directly to `lancedb.connect_async()` / `lancedb.connect()`.
**Returns:** A LanceDB connection.
+</Lang>
+
+<Lang only="rust">
+
+- `uri` β€” LanceDB URI (local path like `"./lancedb_data"` or object-store URI like `"s3://bucket/path"`). The URI is also the database's `state_id()`, its stable identity; the options are not part of it, since they may carry credentials.
+- `options` β€” `connect_with_options` only: the read consistency interval and the object-store options. `ConnectOptions::default()` is the same as `connect(uri)`. LanceDB Cloud (`db://`) URIs are not supported.
+
+**Returns:** A `LanceDatabase`. `connection()` returns the underlying `lancedb::Connection`, for queries.
+
+</Lang>
+
**Example:**
-{/* Rust: examples/rust/code_embedding_lancedb/src/main.rs */}
+{/* Rust: examples/rust/code_embedding_lancedb/src/main.rs; rust/sdk/cocoindex/tests/lancedb_target.rs (lancedb_connect_with_options) */}
<LangTabs>
<Fragment slot="python">
@@ -89,6 +137,16 @@ conn = await lancedb.connect_async("./lancedb_data")
```rust
let db = LanceDatabase::connect(&lancedb_uri()).await?;
+
+// With options
+let db = LanceDatabase::connect_with_options(
+ uri,
+ lancedb::ConnectOptions {
+ read_consistency_interval: Some(std::time::Duration::ZERO),
+ storage_options: [("timeout".to_string(), "30s".to_string())].into(),
+ },
+)
+.await?;
```
</Fragment>
@@ -102,8 +160,18 @@ The `lancedb` connector provides target state APIs for writing rows to tables. C
#### Setting up a connection
+<Lang only="python">
+
Create a `ContextKey[lancedb.LanceAsyncConnection]` to identify your LanceDB connection, then provide it in your lifespan:
+</Lang>
+
+<Lang only="rust">
+
+Declare a context key for your `LanceDatabase`, then provide the connection to the environment:
+
+</Lang>
+
:::note
The key name is load-bearing across runs β€” it's the stable identity CocoIndex uses to track managed tables. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.
:::
@@ -149,7 +217,7 @@ let app = Environment::builder()
#### Tables (parent state)
-Declares a table as a target state. Returns a pending `TableTarget` for declaring rows.
+Declares a table as a target state. Returns a <Lang only="python">pending `TableTarget`</Lang><Lang only="rust">`LanceTableTarget` handle</Lang> for declaring rows.
{/* Rust: rust/sdk/cocoindex/src/connectors/lancedb.rs */}
<LangTabs>
@@ -176,12 +244,11 @@ pub async fn mount_table_target(
table_schema: TableSchema,
) -> Result<LanceTableTarget>
-pub async fn mount_table_target_with_options(
+pub fn declare_table_target(
ctx: &Ctx,
db: &ContextKey<LanceDatabase>,
table_name: impl Into<String>,
table_schema: TableSchema,
- options: ManagedTargetOptions,
) -> Result<LanceTableTarget>
pub fn table_target(
@@ -192,13 +259,15 @@ pub fn table_target(
) -> Result<TargetState<TableSpec>>
```
-The handle type is `LanceTableTarget`. `managed_by` is set with `ManagedTargetOptions::user_managed()` on the `_with_options` variants (`table_target_with_options`, `mount_table_target_with_options`). `declare_table_target` has the same arguments as `mount_table_target`, and `table_target` returns the raw `TargetState` for `mount_target` / `declare_target_state_with_child`.
+Each has a `_with_options` variant (`mount_table_target_with_options`, `declare_table_target_with_options`, `table_target_with_options`) that takes a trailing `options: ManagedTargetOptions`.
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `db` β€” A `ContextKey[LanceAsyncConnection]` identifying the connection to use.
- `table_name` β€” Name of the table.
- `table_schema` β€” Schema definition including columns and primary key (see [Table Schema](#table-schema-from-python-class)).
@@ -232,11 +301,69 @@ def table_target(
) -> coco.TargetState
```
+</Lang>
+
+<Lang only="rust">
+
+- `ctx` β€” The component's `Ctx`.
+- `db` β€” The `ContextKey<LanceDatabase>` identifying the connection to use.
+- `table_name` β€” Name of the table. It must start with an ASCII letter or `_` and contain only ASCII letters, digits and `_`.
+- `table_schema` β€” Schema definition including columns and primary key (see [Table Schema](#table-schema-from-a-rust-struct)).
+- `options` β€” `_with_options` variants only. `ManagedTargetOptions::default()` lets CocoIndex manage the table lifecycle; `ManagedTargetOptions::user_managed()` assumes the table exists and never creates or drops it.
+
+**Returns:** `mount_table_target` and `declare_table_target` return a `LanceTableTarget`, ready for declaring rows. `mount_table_target` is the usual choice; `declare_table_target` is a sync form for declaring the table and its rows in the same component. `table_target` returns the raw `TargetState` for `mount_target` / `declare_target_state_with_child`.
+
+A `LanceTableTarget` is `Clone` and `Serialize`. It can be an argument of `mount!`, `use_mount!`, `mount_each!` or a memoized function: it fingerprints by its stable key, the context key name and the table name. The schema and `managed_by` are not part of that identity.
+
+{/* Rust: rust/sdk/cocoindex/tests/lancedb_target.rs (lancedb_table_target_is_a_mount_argument_keyed_by_its_table) */}
+
+```rust
+#[cocoindex::function]
+async fn declare_row_in_component(
+ ctx: &Ctx,
+ id: i64,
+ table: lancedb::LanceTableTarget,
+) -> Result<()> {
+ table.declare_row(
+ ctx,
+ &Row {
+ id,
+ text: format!("doc{id}"),
+ embedding: vec![1.0, 0.0, 0.0],
+ },
+ )
+}
+
+let table = lancedb::mount_table_target(&ctx, &DB, table_name, schema()).await?;
+cocoindex::use_mount_each!(vec![("1".to_string(), 1_i64)], |id| {
+ declare_row_in_component(ctx, id, table.clone())
+})
+.await?;
+```
+
+</Lang>
+
+<Lang only="python">
+
CocoIndex automatically runs LanceDB `table.optimize()` when durable table and index statistics
cross internal maintenance thresholds, such as small fragments, deletion files, or unindexed
index tails. This is stats-driven rather than transaction-count-driven, so it works across
many short incremental runs as well as long-running updates.
+</Lang>
+
+<Lang only="rust">
+
+CocoIndex automatically runs LanceDB `table.optimize()` once every 50 applied row batches of a table
+target in a run. All row batches of a run write through one table handle, opened by the first batch
+and moved to the table's latest version before each later one.
+
+</Lang>
+
+<RustNote>
+Optimization is counted in row batches, not driven by table and index statistics as in Python. A run with fewer than 50 row batches does not optimize the table.
+</RustNote>
+
Table optimization compacts small fragments, cleans up deletion files, and reindexes new data so
the freshest rows are available through declared indexes; see LanceDB's
[compaction and cleanup](https://docs.lancedb.com/performance#compaction-and-cleanup) guidance.
@@ -250,7 +377,7 @@ updating the table.
#### Rows (child states)
-Once a `TableTarget` is resolved, declare rows to be upserted:
+Once <Lang only="python">a `TableTarget` is resolved</Lang><Lang only="rust">you have a `LanceTableTarget`</Lang>, declare rows to be upserted:
{/* Rust: examples/rust/text_embedding_lancedb/src/main.rs */}
<LangTabs>
@@ -280,11 +407,21 @@ table.declare_row(&ctx, row)?;
**Parameters:**
-- `row` β€” A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include all primary key columns. In Rust, any `Serialize` value that serializes to an object with the schema's columns; extra fields are dropped and missing ones become null.
+<Lang only="python">
+
+- `row` β€” A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include all primary key columns.
+
+</Lang>
+
+<Lang only="rust">
+
+- `row` β€” Any `Serialize` value that serializes to an object with the schema's columns. It must include all primary key columns. Extra fields are dropped and missing ones become null.
+
+</Lang>
#### Vector indexes (attachment)
-Declare a vector index on a vector column to accelerate similarity search. Vector indexes are an [attachment](../advanced_topics/custom_target_connector#implementing-attachment-providers) to a `TableTarget`:
+Declare a vector index on a vector column to accelerate similarity search. Vector indexes are an [attachment](../advanced_topics/custom_target_connector#implementing-attachment-providers) to a <Lang only="python">`TableTarget`</Lang><Lang only="rust">`LanceTableTarget`</Lang>:
{/* Rust: rust/sdk/cocoindex/src/connectors/lancedb.rs */}
<LangTabs>
@@ -334,17 +471,19 @@ pub struct VectorIndexOptions {
}
```
-Two names differ from Python: the HNSW index type is `"ivf_hnsw_pq"`, and the default index name is `<column>_idx`, not `column`.
-
</Fragment>
</LangTabs>
+<RustNote>
+Two names differ from Python: the HNSW index type is `"ivf_hnsw_pq"`, not `"hnsw_pq"`, and the default index name is `<column>_idx`, not the column name.
+</RustNote>
+
**Parameters:**
-- `name` β€” Logical index name (defaults to `column`).
+- `name` β€” Logical index name (defaults to <Lang only="python">`column`</Lang><Lang only="rust">`<column>_idx`</Lang>).
- `column` β€” Vector column to index.
- `metric` β€” Distance metric: `"cosine"` (default), `"l2"`, or `"dot"`.
-- `index_type` β€” Index algorithm: `"ivf_pq"` (IVF-PQ, default) or `"hnsw_pq"` (HNSW-PQ).
+- `index_type` β€” Index algorithm: `"ivf_pq"` (IVF-PQ, default) or <Lang only="python">`"hnsw_pq"`</Lang><Lang only="rust">`"ivf_hnsw_pq"`</Lang> (HNSW-PQ).
- `num_partitions` β€” *(IVF-PQ only)* Number of IVF partitions.
- `num_sub_vectors` β€” *(IVF-PQ / HNSW-PQ)* Number of PQ sub-vectors.
- `num_bits` β€” *(IVF-PQ / HNSW-PQ)* Number of bits per PQ code.
@@ -375,7 +514,7 @@ table.declare_vector_index(&ctx, "embedding", lancedb::VectorIndexOptions::defau
#### FTS indexes (attachment)
-Declare a full-text search (FTS) index on a text column to enable keyword and phrase search. Like vector indexes, FTS indexes are an [attachment](../advanced_topics/custom_target_connector#implementing-attachment-providers) to a `TableTarget`:
+Declare a full-text search (FTS) index on a text column to enable keyword and phrase search. Like vector indexes, FTS indexes are an [attachment](../advanced_topics/custom_target_connector#implementing-attachment-providers) to a <Lang only="python">`TableTarget`</Lang><Lang only="rust">`LanceTableTarget`</Lang>:
{/* Rust: rust/sdk/cocoindex/src/connectors/lancedb.rs */}
<LangTabs>
@@ -408,24 +547,26 @@ impl LanceTableTarget {
pub struct FtsIndexOptions {
/// Index name; defaults to `<column>_fts_idx`.
pub name: Option<String>,
- /// Record token positions (enables phrase queries). Defaults to `false`.
+ /// Record token positions (enables phrase queries). Defaults to `true`.
pub with_position: bool,
/// Stemming/stop-word language. `None` uses LanceDB's default (English).
pub language: Option<String>,
}
```
-Two defaults differ from Python: `with_position` is `false`, and the index name is `<column>_fts_idx`.
-
</Fragment>
</LangTabs>
+<RustNote>
+The default FTS index name is `<column>_fts_idx`, not the column name.
+</RustNote>
+
**Parameters:**
-- `name` β€” Logical index name (defaults to `column`).
+- `name` β€” Logical index name (defaults to <Lang only="python">`column`</Lang><Lang only="rust">`<column>_fts_idx`</Lang>).
- `column` β€” Text column to index.
-- `language` β€” Tokenizer language (e.g. `"English"`, `"Chinese"`).
-- `with_position` β€” Whether to store token positions (enables phrase queries). Defaults to `True`.
+- `language` β€” Tokenizer language (e.g. `"English"`, `"Chinese"`).<Lang only="rust"> `None` uses LanceDB's default, English.</Lang>
+- `with_position` β€” Whether to store token positions (enables phrase queries). Defaults to <Lang only="python">`True`</Lang><Lang only="rust">`true`</Lang>.
**Example:**
@@ -461,10 +602,22 @@ table.declare_fts_index(
Indexes are reconciled as part of the table's target state: changing a declaration replaces the index in place, removing a declaration drops the index, and dropping the table removes all its indexes.
:::
+<Lang only="python">
+
### Table schema: from Python class
Define the table structure using a Python class (dataclass, NamedTuple, or Pydantic model):
+</Lang>
+
+<Lang only="rust">
+
+### Table schema: from a Rust struct
+
+Define the table structure with a struct that derives `SchemaFields` (and `Serialize`):
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/connectors/lancedb.rs */}
<LangTabs>
<Fragment slot="python">
@@ -499,17 +652,30 @@ impl TableSchema {
}
```
-The Rust row type is a struct that derives `SchemaFields` (and `Serialize`). Python's `column_specs` become builder calls on the derived schema: `with_vector_schema` or `with_vector_dim` for a vector column, `with_column_type` for a type override.
+Per-column overrides are builder calls on the derived schema: `with_vector_schema` or `with_vector_dim` for a vector column, `with_column_type` for a type override. `with_column_type` keeps the column's nullability. Each returns an error for a column that is not in the schema.
</Fragment>
</LangTabs>
**Parameters:**
+<Lang only="python">
+
- `record_type` β€” A record type whose fields define table columns.
- `primary_key` β€” List of column names forming the primary key. A primary key column must have a string, binary, boolean, integer, `float32`, `float64` or decimal PyArrow type, and its name can't contain a backtick (`` ` ``). `TableSchema` raises a `ValueError` for any other primary key column.
- `column_specs` β€” Optional per-column overrides for type mapping or vector configuration.
+</Lang>
+
+<Lang only="rust">
+
+- `T` β€” The row struct whose fields define table columns.
+- `primary_key` β€” Column names forming the primary key. A primary key value must serialize to a string or an integer.
+
+Every column name must start with an ASCII letter or `_` and contain only ASCII letters, digits and `_`.
+
+</Lang>
+
**Example:**
{/* Rust: examples/rust/text_embedding_lancedb/src/main.rs */}
@@ -555,29 +721,62 @@ fn doc_embedding_schema() -> Result<TableSchema> {
</Fragment>
</LangTabs>
-Python types are automatically mapped to PyArrow types:
+<Lang only="python">
-| Python Type | Rust Type | PyArrow Type |
-|-------------|-----------|--------------|
-| `bool` | `bool` | `bool` |
-| `int` | `i64` (`i16`: `int16`, `i32`: `int32`) | `int64` |
-| `float` | `f64` (`f32`: `float32`) | `float64` |
-| `str` | `String`, `Uuid`, dates and times | `string` |
-| `bytes` | `Vec<u8>` | `binary` |
-| `list`, `dict`, nested structs | other `Vec<T>`, maps, nested structs, `Decimal`, `Duration`, `#[coco(json)]` | `string` (JSON encoded) |
-| `NDArray` (with vector schema) | `Vec<f32>` with `#[coco(vector)]` (`half` for `float16`) | `fixed_size_list<float>` |
+Python types are automatically mapped to PyArrow types:
-The Rust `ColumnType` enum names these: `Bool`, `Int16`, `Int32`, `Int64`, `Float32`, `Float64`, `Text`, `Binary`, `Json`, `Vector(dim)` and `HalfVector(dim)`. A `#[coco(type = "…")]` attribute is an error for LanceDB: use `with_column_type` with a `ColumnType`.
+| Python Type | PyArrow Type |
+|-------------|--------------|
+| `bool` | `bool` |
+| `int` | `int64` |
+| `float` | `float64` |
+| `str` | `string` |
+| `bytes` | `binary` |
+| `list`, `dict`, nested structs | `string` (JSON encoded) |
+| `NDArray` (with vector schema) | `fixed_size_list<float>` |
To override the default mapping, provide a `LanceType` or `VectorSchemaProvider` via:
- **Type annotation** β€” using `typing.Annotated` on the field
- **`column_specs`** β€” passing overrides when constructing `TableSchema`
+</Lang>
+
+<Lang only="rust">
+
+Rust field types are automatically mapped to Arrow types:
+
+| Rust Type | `ColumnType` | Arrow Type |
+|-----------|--------------|------------|
+| `bool` | `Bool` | `bool` |
+| `i16`, `i32`, `i64` | `Int16`, `Int32`, `Int64` | `int16`, `int32`, `int64` |
+| `f32`, `f64` | `Float32`, `Float64` | `float32`, `float64` |
+| `String`, `Uuid`, dates and times | `Text` | `string` |
+| `Vec<u8>` | `Binary` | `binary` |
+| other `Vec<T>`, maps, nested structs, `Decimal`, `Duration`, `#[coco(json)]` | `Json` | `string` (JSON encoded) |
+| `Vec<f32>` with `#[coco(vector)]` | `Vector(dim)` | `fixed_size_list<float32>` |
+| `Vec<f32>` with `#[coco(vector, half)]` | `HalfVector(dim)` | `fixed_size_list<float16>` |
+
+`ColumnType` also has `Int8`, `UInt8`, `UInt16`, `UInt32`, `UInt64` and `Float16`, for `with_column_type` and explicit columns. A `#[coco(type = "…")]` attribute is an error for LanceDB: use `with_column_type` with a `ColumnType`.
+
+</Lang>
+
+<Lang only="python">
+
#### LanceType
Use `LanceType` to specify a custom PyArrow type or encoder:
+</Lang>
+
+<Lang only="rust">
+
+#### Column type overrides
+
+Use `with_column_type` to store a column with another `ColumnType`:
+
+</Lang>
+
{/* Rust: rust/sdk/cocoindex/src/connectors/lancedb.rs (with_column_type) */}
<LangTabs>
<Fragment slot="python">
@@ -610,21 +809,45 @@ let schema = TableSchema::from_row::<MyRow>(["id"])?
.with_column_type("value", ColumnType::Float32)?;
```
-Or declare the field as `i32` / `f32` in the struct. Python's encoder has no counterpart: a Rust row is encoded by its `Serialize` impl, so put `#[serde(serialize_with = "…")]` on the field.
+Or declare the field as `i32` / `f32` in the struct.
</Fragment>
</LangTabs>
+<RustNote>
+There is no per-column encoder. A Rust row is encoded by its `Serialize` impl: to convert a value before it is written, put `#[serde(serialize_with = "…")]` on the field.
+</RustNote>
+
#### VectorSchemaProvider
+<Lang only="python">
+
For `NDArray` fields, a `VectorSchemaProvider` annotation specifies the vector dimension and dtype. The annotation accepts a `VectorSchemaProvider`, a `ContextKey`, or an explicit `VectorSchema`. See [Vector Schema](../common_resources/vector_schema#vectorschemaprovider) for details.
-In Rust, call `with_vector_schema("embedding", ctx.get_key(&EMBEDDER)?).await?` on the derived schema. It takes any `VectorSchemaProvider`: an embedder, or a `VectorSchema`. An `f16` provider selects a `float16` list.
+</Lang>
+
+<Lang only="rust">
+
+For a `#[coco(vector)]` field, `with_vector_schema` takes the vector dimension and element type from a `VectorSchemaProvider`: an embedder, or a `VectorSchema`. For an embedder held in the context, pass `ctx.get_key(&EMBEDDER)?`. An `f16` provider selects a `float16` list; `f32` and `f64` select `float32`. See [Vector Schema](../common_resources/vector_schema#vectorschemaprovider) for details.
+
+{/* Rust: rust/sdk/cocoindex/src/connectors/lancedb.rs (with_vector_schema doc comment) */}
+
+```rust
+let schema = TableSchema::from_row::<DocEmbedding>(["id"])?
+ .with_vector_schema("embedding", ctx.get_key(&EMBEDDER)?)
+ .await?;
+```
+
+</Lang>
### Table schema: explicit column definitions
Define columns directly using `ColumnDef`:
+{/* Rust: rust/sdk/cocoindex/src/connectors/lancedb.rs (TableSchema::new, ColumnDef) */}
+<LangTabs>
+<Fragment slot="python">
+
```python
def TableSchema.__init__(
self,
@@ -648,6 +871,28 @@ class ColumnDef(NamedTuple):
- `nullable` β€” Whether the column may contain null values.
- `encoder` β€” Optional function to convert values before writing them.
+</Fragment>
+<Fragment slot="rust">
+
+```rust
+impl TableSchema {
+ pub fn new(
+ columns: impl IntoIterator<Item = (impl Into<String>, ColumnDef)>,
+ primary_key: impl IntoIterator<Item = impl Into<String>>,
+ ) -> Result<Self>
+}
+
+impl ColumnDef {
+ pub fn new(col_type: ColumnType) -> Self
+ pub fn nullable(self) -> Self
+}
+```
+
+`ColumnDef::new(col_type)` is not nullable; `.nullable()` opts in. `TableSchema::new` returns an error for an empty primary key, a primary key column that is not in `columns`, or a duplicate column.
+
+</Fragment>
+</LangTabs>
+
**Example:**
{/* Rust: rust/sdk/cocoindex/tests/lancedb_target.rs */}
@@ -683,8 +928,6 @@ TableSchema::new(
)?
```
-`ColumnDef::new(col_type)` is not nullable; `.nullable()` opts in. The Rust `ColumnDef` has no encoder.
-
</Fragment>
</LangTabs>