Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
docs(connectors): Python and Rust pages for Neo4j, SurrealDB, Qdrant, Turbopuffer, OCI and zvec (#2748)
LJ π₯₯π΄305327fdf624
diff --git a/docs/src/content/docs/connectors/neo4j.mdx b/docs/src/content/docs/connectors/neo4j.mdxindex 89a87b53..5aeaffc1 100644--- a/docs/src/content/docs/connectors/neo4j.mdx+++ b/docs/src/content/docs/connectors/neo4j.mdx@@ -26,25 +26,39 @@ from cocoindex.connectors import neo4juse cocoindex::connectors::neo4j::{self, TableSchema};```-The Rust SDK needs the `neo4j` Cargo feature of the `cocoindex` crate.+The module is compiled with the `neo4j` Cargo feature of the `cocoindex` crate.</Fragment></LangTabs>:::note[Dependencies]+<Lang only="python">+This connector requires additional dependencies. Install with:```bashpip install cocoindex[neo4j]```+</Lang>+Targets Neo4j 5.18+. Vector-index DDL (`CREATE VECTOR INDEX β¦ OPTIONS { indexConfig: { β¦ } }`) shipped in 5.18 β older 5.x servers will reject the DDL the connector emits.:::## Connection setup+<Lang only="python">+Create a `ConnectionFactory` and provide it via a `ContextKey`. The factory holds the Bolt URI, optional auth, and the target database name; it opens one connection-pooled Neo4j async driver 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 `neo4j::Graph` and provide it under a context key. A `Graph` holds a connection pool and the name of the database its statements run on; all tables and batches share it.++</Lang>+:::noteThe 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.:::@@ -97,16 +111,20 @@ async fn main() -> Result<()> {}```-`neo4j::Graph::connect(uri, user, password, database)` opens a connection pool with basic authentication. For TLS or other driver settings, build a `neo4rs::Graph` yourself and wrap it with `neo4j::Graph::from_client(client, database)`. The example provides the graph in `main`; a `#[cocoindex::lifespan]` function can do the same with `builder.provide_key(&GRAPH, graph)`, and `builder.on_shutdown(..)` is the place for teardown. A `Graph` has no `close()` method.+`neo4j::Graph::connect(uri, user, password, database)` opens a connection pool with basic authentication; the user, password and database are required arguments. For TLS, a custom pool size or other driver settings, build a `neo4rs::Graph` with `neo4rs::ConfigBuilder` and wrap it with `neo4j::Graph::from_client(client, database)`. The example provides the graph in `main`; a `#[cocoindex::lifespan]` function can do the same with `builder.provide_key(&GRAPH, graph)`, and `builder.on_shutdown(..)` is the place for teardown. A `Graph` has no `close()` method.</Fragment></LangTabs>-`auth` is optional β omit it for unauthenticated dev instances. `database` defaults to `"neo4j"` (the default db that ships with every Neo4j 5 installation). The Rust `connect` takes the user, password and database as required arguments.+<Lang only="python">++`auth` is optional β omit it for unauthenticated dev instances. `database` defaults to `"neo4j"` (the default db that ships with every Neo4j 5 installation).++</Lang>### Multitenancy-A single Neo4j cluster can host many isolated databases. Pair each database with its own `ContextKey` and `ConnectionFactory(database=...)`:+A single Neo4j cluster can host many isolated databases. Pair each database with its own context key and <Lang only="python">`ConnectionFactory(database=...)`</Lang><Lang only="rust">`neo4j::Graph`</Lang>:{/* Rust: examples/rust/meeting_notes_graph_neo4j/src/main.rs (two keys instead of one) */}<LangTabs>@@ -152,25 +170,37 @@ let app = Environment::builder()</Fragment></LangTabs>-Different `ContextKey`s with different database names produce fully separate target-state trees β changes to one never spill into the other.+Different context keys with different database names produce fully separate target-state trees β changes to one never spill into the other.## As targetThe `neo4j` connector provides target state APIs for writing nodes to node tables and edges to relationship tables. CocoIndex tracks what records should exist and automatically handles upserts and deletions.-Each apply batch is wrapped in a single Neo4j transaction (`tx.commit()` on success, rollback on exception), so partial writes never leak into the database. Within a batch, writes are ordered as **node upserts β relation upserts β relation deletes β node deletes** so dependent edges always see their endpoints. A batch that fails with a transient error (typically a deadlock between concurrent batches merging edges onto the same nodes) is rolled back and retried with backoff before the failure is reported.+The record writes of all tables of one database are applied together, in batches. Within a batch, writes are ordered as **node upserts β relation upserts β relation deletes β node deletes** so dependent edges always see their endpoints. A batch is applied in Neo4j transactions of at most 1,000 record writes each, one after the other. A transaction that fails rolls back, and the components of the batch are retried; earlier transactions of the batch stay committed, which is safe because the writes are idempotent (`MERGE`). A transaction that fails with a transient error (typically a deadlock between concurrent writers merging edges onto the same nodes) is retried with backoff, up to 8 attempts, before the failure is reported. A transaction that goes over the server's transaction memory limit is split in two instead.++<Lang only="rust">++Within a transaction, the records of one statement shape (the node upserts of one label, the edge upserts of one relationship type and endpoint labels, and so on) are written by one `UNWIND $rows AS row β¦` statement.++</Lang>++<Lang only="python">:::noteThe 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 Rust functions keep the names `mount_table_target` / `TableTarget` and `mount_relation_target` / `RelationTarget`. They have the semantics of Python's node and relationship APIs (`mount_node_target`, `mount_relationship_target`), not of Python's deprecated table and relation APIs: 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.+</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>@@ -207,13 +237,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.+`declare_table_target` declares the table in the current component; its records resolve when the component commits. `mount_table_target` and `mount_table_target_with_options` take the same arguments, are `async`, and return a target whose records can be declared at once.</Fragment></LangTabs>**Parameters:**+<Lang only="python">+- `db` β A `ContextKey[neo4j.ConnectionFactory]` for the Neo4j connection.- `table_name` β The Cypher node label (e.g. `"Document"`). It must not contain `__` or end with `_`: constraint and index names join the label to a property name with `__`, so such a label could share a name with another table's.- `table_schema` β Optional schema definition (see [Table Schema](#table-schema-from-python-class)). The schema participates in CocoIndex's fingerprint (so two flows declaring the same label must agree); per-property type DDL is not emitted in v1.@@ -222,10 +254,33 @@ The schema is required. It carries the primary key: `TableSchema::from_row::<Row**Returns:** A pending `NodeTarget`. Use `await neo4j.mount_node_target(KG_DB, ...)` to get a resolved target.+</Lang>++<Lang only="rust">++- `graph` β The context key of the `neo4j::Graph`.+- `table_name` β The Cypher node label (e.g. `"Meeting"`). It must not contain `__` or end with `_`: constraint and index names join the label to a property name with `__`, so such a label could share a name with another table's.+- `schema` β The table schema (see [Table schema: from a row struct](#table-schema-from-a-row-struct)). It names the single primary-key property; compound primary keys are not supported. `TableSchema::from_row::<Row>("id")?` derives the columns from a row struct, and `TableSchema::schemaless("id")?` declares no columns. The schema participates in CocoIndex's fingerprint (so two flows declaring the same label must agree); no per-property type DDL is emitted.+- `options` β `ManagedTargetOptions::user_managed()` assumes the table exists; the default (`ManagedTargetOptions::default()`) lets CocoIndex manage its lifecycle.++**Returns:** A `TableTarget`. A `TableTarget` serializes to its stable key (the graph's context key and the label), so it can be an argument of `mount!`, `use_mount!`, `mount_each!` and memoized functions.++</Lang>+#### Nodes (child states)+<Lang only="python">+Once a `NodeTarget` is resolved, declare nodes to be upserted (translated to `MERGE (n:Label {pk: $key_0}) SET n += $props`):+</Lang>++<Lang only="rust">++Once a `TableTarget` is resolved, declare nodes to be upserted (translated to `UNWIND $rows AS row MERGE (n:Label {pk: row.key}) SET n += row.props`):++</Lang>+{/* Rust: rust/sdk/cocoindex/src/cypher_graph.rs (graph_target_api! macro) */}<LangTabs><Fragment slot="python">@@ -255,15 +310,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>@@ -314,13 +373,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")?`. Each function has an `async` `mount_relation_target*` twin with the same arguments, whose edges can be declared at once.</Fragment></LangTabs>**Parameters:**+<Lang only="python">+- `db` β A `ContextKey[neo4j.ConnectionFactory]` for the Neo4j connection.- `table_name` β The Cypher relationship type (e.g. `"MENTION"`). Same naming rule as a node label: no `__`, no trailing `_`. 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.@@ -331,9 +392,24 @@ Without a schema the relationship is schemaless and keyed by its `id` property.**Returns:** A pending `RelationshipTarget`. Use `await neo4j.mount_relationship_target(KG_DB, ...)` to get a resolved target.+</Lang>++<Lang only="rust">++- `graph` β The context key of the `neo4j::Graph`.+- `relation_name` β The Cypher relationship type (e.g. `"ATTENDED"`). Same naming rule as a node label: no `__`, no trailing `_`. A node label and a relationship type may share a name.+- `from_table` β The node table whose nodes are the *source* endpoints of edges in this relationship.+- `to_table` β The node table whose nodes are the *target* endpoints of edges in this relationship.+- `schema` β The schema for the relationship's own properties; its primary key uniquely identifies each edge. Without it, the edges are keyed by the `id` property.+- `options` β `ManagedTargetOptions::user_managed()` assumes the relationship type exists; the default lets CocoIndex manage its lifecycle.++**Returns:** A `RelationTarget`, which serializes to its stable key like a `TableTarget`.++</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>@@ -378,15 +454,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 whose fields populate the relationship's properties.</Lang><Lang only="rust">The row whose fields populate the relationship's properties (`declare_relation_record` only).</Lang> 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 <Lang only="python">`record` is omitted</Lang><Lang only="rust">the edge is declared with `declare_relation`</Lang> or the record 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>-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_target.rs */}<LangTabs>@@ -438,9 +514,9 @@ people.declare_vector_index_named(ctx, "person_embedding", "embedding", 3, Vecto**Parameters:**-- `name` β Optional logical name for the index. Defaults to `f"vec_{table_name}__{field}"`.+- `name` β <Lang only="python">Optional logical name for the index. Defaults to `f"vec_{table_name}__{field}"`.</Lang><Lang only="rust">Logical name for the index (`declare_vector_index_named` only). Defaults to `vec_{table_name}__{field}`.</Lang>- `field` β The node property holding the vector.-- `metric` β Similarity metric: `"cosine"` or `"euclidean"`. Translated to Neo4j's `vector.similarity_function` option.+- `metric` β Similarity metric: <Lang only="python">`"cosine"` or `"euclidean"`</Lang><Lang only="rust">`VectorMetric::Cosine` or `VectorMetric::Euclidean`</Lang>. Translated to Neo4j's `vector.similarity_function` option.- `dimension` β The vector's dimension. Required.The connector emits:@@ -458,10 +534,22 @@ The Neo4j index is named after the label and field, not after `name`, so a fieldVectors are float32 only.+<Lang only="python">+### Table schema: from Python classBuild a `TableSchema` by introspecting a record type:+</Lang>++<Lang only="rust">++### Table schema: from a row struct++Build a `TableSchema` from a row struct:++</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">@@ -497,38 +585,94 @@ struct Person {let schema = cocoindex::connectors::neo4j::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 `Neo4jType` or `VectorSchemaProvider` to override the default Python-to-Neo4j type mapping. In Rust, a `#[coco(..)]` attribute on the field does this (see below).+- `column_overrides` β Optional dict mapping field names to `Neo4jType` or `VectorSchemaProvider` to override the default Python-to-Neo4j type mapping.**Returns:** A `TableSchema[RowT]` populated from the class's fields.+</Lang>++<Lang only="rust">++To override the type of one column, put a `#[coco(..)]` attribute on the field (see [Column type overrides](#column-type-overrides)), or call `with_column_type` on the derived schema:++{/* 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")?;+```++`with_column_type(field, cypher_type)` replaces the recorded Cypher type of one column and keeps its nullability. It fails if the schema has no column named `field`.++</Lang>++<Lang only="python">+#### Default Python β Neo4j type mapping+</Lang>++<Lang only="rust">++{/* Keeps the old anchor: falkordb.mdx links /docs/rust/connectors/neo4j/#default-python--neo4j-type-mapping. */}+<span id="default-python--neo4j-type-mapping"></span>++#### Default Rust β Neo4j type mapping++</Lang>+Most types pass through native Bolt encoding β no per-value transform applied:-| Python type | Rust type | Neo4j type | Notes |-|---|---|---|---|-| `bool` | `bool` | `BOOLEAN` | |-| `int`, NumPy integer scalars | `i16`, `i32`, `i64` (and the unsigned widths) | `INTEGER` | |-| `float`, NumPy float scalars | `f32`, `f64` | `FLOAT` | |-| `decimal.Decimal` | `rust_decimal::Decimal` | `STRING` | Encoded via `str()` β Neo4j has no decimal type. |-| `str` | `String` | `STRING` | |-| `bytes` | `Vec<u8>` | `BYTES` | Native Bolt type β no encoder. |-| `uuid.UUID` | `uuid::Uuid` | `STRING` | Encoded via `str()`. |-| `datetime.date` | `chrono::NaiveDate` | `DATE` | Native Bolt type. |-| `datetime.datetime` | `chrono::DateTime`, `chrono::NaiveDateTime` | `ZONED_DATETIME` | Native Bolt type. |-| `datetime.time` | `chrono::NaiveTime` | `LOCAL_TIME` | Native Bolt type. |-| `datetime.timedelta` | `std::time::Duration` | `DURATION` | Native Bolt type. |-| `numpy.ndarray` (with `VectorSchema` annotation) | `#[coco(vector)] Vec<f32>` | `LIST<FLOAT>` | Encoded via `tolist()`; paired with vector-index DDL. |-| `dict`, list, nested record, `Any` | other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `MAP` / `LIST<ANY>` | Passed through native parameter binding. In Rust the recorded type is `MAP`. |+<Lang only="python">++| Python type | Neo4j type | Notes |+|---|---|---|+| `bool` | `BOOLEAN` | |+| `int`, NumPy integer scalars | `INTEGER` | |+| `float`, NumPy float scalars | `FLOAT` | |+| `decimal.Decimal` | `STRING` | Encoded via `str()` β Neo4j has no decimal type. |+| `str` | `STRING` | |+| `bytes` | `BYTES` | Native Bolt type β no encoder. |+| `uuid.UUID` | `STRING` | Encoded via `str()`. |+| `datetime.date` | `DATE` | Native Bolt type. |+| `datetime.datetime` | `ZONED_DATETIME` | Native Bolt type. |+| `datetime.time` | `LOCAL_TIME` | Native Bolt type. |+| `datetime.timedelta` | `DURATION` | Native Bolt type. |+| `numpy.ndarray` (with `VectorSchema` annotation) | `LIST<FLOAT>` | Encoded via `tolist()`; paired with vector-index DDL. |+| `dict`, list, nested record, `Any` | `MAP` / `LIST<ANY>` | Passed through native parameter binding. |++</Lang>++<Lang only="rust">++| Rust type | Neo4j type | Notes |+|---|---|---|+| `bool` | `BOOLEAN` | |+| `i16`, `i32`, `i64` (and the unsigned widths) | `INTEGER` | |+| `f32`, `f64` | `FLOAT` | |+| `rust_decimal::Decimal` | `STRING` | Written as a string β Neo4j has no decimal type. |+| `String` | `STRING` | |+| `Vec<u8>` | `BYTES` | Native Bolt type β no encoder. |+| `uuid::Uuid` | `STRING` | Written as a string. |+| `chrono::NaiveDate` | `DATE` | Native Bolt type. |+| `chrono::DateTime`, `chrono::NaiveDateTime` | `ZONED_DATETIME` | Native Bolt type. |+| `chrono::NaiveTime` | `LOCAL_TIME` | Native Bolt type. |+| `std::time::Duration` | `DURATION` | Native Bolt type. |+| `#[coco(vector)] Vec<f32>` | `LIST<FLOAT>` | Paired with vector-index DDL. |+| other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `MAP` | Passed through native parameter binding. |++</Lang>++<Lang only="python">#### Neo4jType@@ -542,6 +686,16 @@ class Neo4jType(NamedTuple):Use with `typing.Annotated`:+</Lang>++<Lang only="rust">++#### Column type overrides++Override the default mapping for a single column with a `#[coco(..)]` field attribute:++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/graph_target.rs (from_row_matches_explicit_schema) */}<LangTabs><Fragment slot="python">@@ -573,20 +727,36 @@ 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. A value is written as it serializes with serde.++<RustNote>+There is no per-column `encoder`: to change how a value is written, change how its field serializes (for example with `#[serde(serialize_with = "β¦")]`).+</RustNote></Fragment></LangTabs>-The `neo4j_type` string is metadata-only β it participates in the schema fingerprint (so two flows declaring the same table must agree) but no per-property type DDL is emitted from it.+The <Lang only="python">`neo4j_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 per-property type 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>`; 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> column definitions when the row type is dynamic:{/* Rust: rust/sdk/cocoindex/tests/graph_target.rs (from_row_matches_explicit_schema) */}<LangTabs>@@ -621,16 +791,20 @@ let schema = TableSchema::new()?;```-A Rust `ColumnDef` is `NOT NULL` unless `.nullable()` is called.+`ColumnDef::new(cypher_type)` takes the Neo4j type string (metadata only; see the table above). A column is `NOT NULL` unless `.nullable()` is called.</Fragment></LangTabs>+<Lang only="python">+`ColumnDef` fields:-- `type` β The Neo4j 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 Neo4j. Not available in Rust.+- `type` β The Neo4j 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 Neo4j.++</Lang>### DDL: indexes and constraints@@ -648,11 +822,11 @@ For each managed table, the connector creates supporting Cypher artifacts on firFOR ()-[r:`<RelType>`]-() ON (r.`<pk>`)```-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 or index is dropped. A node table's vector indexes (the `coco_vec_<Label>__<field>` indexes 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 or index is dropped. A node table's vector indexes (the `coco_vec_<Label>__<field>` indexes 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 schema) 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 schema) 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@@ -896,11 +1070,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 uniqueness constraint is 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 uniqueness constraint is reconciled before any `RELATIONSHIP` edge MERGEs entity endpoints.</Lang><Lang only="rust">The `Person` and `Task` tables are declared up-front (via `mount_table_target`) so their uniqueness 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 APIsThe table and relation APIs are deprecated. They emit a `DeprecationWarning` and otherwise work as before. Each has a replacement with the same parameters:@@ -930,3 +1104,5 @@ Switching a table from the deprecated API to its replacement keeps its nodes, edRun 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/oci_object_storage.mdx b/docs/src/content/docs/connectors/oci_object_storage.mdxindex 14e24203..1e1fba17 100644--- a/docs/src/content/docs/connectors/oci_object_storage.mdx+++ b/docs/src/content/docs/connectors/oci_object_storage.mdx@@ -25,11 +25,13 @@ from cocoindex.connectors import oci_object_storageuse cocoindex::connectors::oci_object_storage::{self, ListOptions, OciClient, OciFile};```-The Rust SDK needs the `oci_object_storage` Cargo feature of the `cocoindex` crate. The Rust connector signs REST requests itself; it does not use the OCI SDK.+The module is compiled with the `oci_object_storage` Cargo feature of the `cocoindex` crate. Oracle has no official Rust SDK, so the connector calls the Object Storage REST API directly and signs each request itself.</Fragment></LangTabs>+<Lang only="python">+:::note[Installation]This connector requires the `oci` SDK. Install with:@@ -44,16 +46,48 @@ pip install cocoindex[kafka]```:::+</Lang>++<Lang only="rust">++:::note[Installation]+Enable the `oci_object_storage` feature of the `cocoindex` crate. For live mode over OCI Streaming, also enable the `kafka` feature:++```toml title="Cargo.toml"+[dependencies]+cocoindex = { git = "https://github.com/cocoindex-io/cocoindex", features = [+ "oci_object_storage",+ "kafka",+] }+```+:::++</Lang>+## As sourceThe connector provides three ways to read from OCI Object Storage:+<Lang only="python">+- `list_objects()` β List and iterate over objects in a bucket (with optional prefix and filtering)- `get_object()` β Fetch a single object by its name- `read()` β Read object content directly without first fetching metadataAll require an `oci.object_storage.ObjectStorageClient`, which you create and manage yourself. The OCI SDK is synchronous; this connector wraps SDK calls with `asyncio.to_thread`, so the public API remains async.+</Lang>++<Lang only="rust">++- `list_objects()` β List the objects in a bucket (with optional prefix and filtering); `list_objects_live()` adds live mode+- `OciClient::get_object()` β Fetch a single object's metadata by its name+- `OciClient::read()` β Read the content of an object++All take an `OciClient`, which you create and provide yourself.++</Lang>+{/* Rust: examples/rust/oci_object_storage_embedding/src/main.rs; rust/sdk/cocoindex/src/connectors/oci_object_storage.rs (OciClient, OciConfig) */}<LangTabs><Fragment slot="python">@@ -81,7 +115,17 @@ let app = Environment::builder().await?;```-`OciClient::connect()` reads an API-key profile from `~/.oci/config` (or `OCI_CONFIG_FILE`), profile `DEFAULT` (or `OCI_PROFILE` / `OCI_CLI_PROFILE`). `OciClient::from_config(OciConfig { tenancy, user, fingerprint, key_file, region, pass_phrase })?` takes the profile's values directly; `OciConfig::from_file(path, profile)?` parses one. The Rust client supports API-key principals only, with an unencrypted private key: instance principals and encrypted keys have no Rust counterpart. An `OciClient` is `Clone` and has no `close()`.+`OciClient::connect()` reads an API-key profile from `~/.oci/config` (or `OCI_CONFIG_FILE`), profile `DEFAULT` (or `OCI_PROFILE` / `OCI_CLI_PROFILE`). `OciClient::from_config(OciConfig { tenancy, user, fingerprint, key_file, region, pass_phrase })?` takes the profile's values directly; `OciConfig::from_file(path, profile)?` parses one. The private key is a PKCS#8 or PKCS#1 PEM; a profile with a `pass_phrase` opens an encrypted PKCS#8 key, as `oci setup config` writes one. A key in the legacy OpenSSL encryption (`Proc-Type: 4,ENCRYPTED`) is rejected: re-encode it with `openssl pkcs8 -topk8`.++To run as the compute instance itself (an instance principal), build the client with `OciClient::from_instance_principal()`:++```rust+let oci = OciClient::from_instance_principal().await?;+```++It exchanges the instance's certificate from the metadata service for a session token and renews the token as it expires. The instance must be in a dynamic group with a policy that lets it read the bucket. `from_instance_principal_with_options(InstancePrincipalOptions { metadata_base_url, federation_endpoint })` sets the two endpoints explicitly; `OCI_METADATA_BASE_URL` also overrides the metadata endpoint.++An `OciClient` is `Clone` and has no `close()`. Its stable identity (`state_id()`) comes from the region, never from the credentials.</Fragment></LangTabs>@@ -136,6 +180,8 @@ The walker is not an iterator: `list()` returns every matching object, and `item</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `client` β An `oci.object_storage.ObjectStorageClient`.@@ -148,10 +194,37 @@ The walker is not an iterator: `list()` returns every matching object, and `item**Returns:** An `OCIWalker` that can be used with `async for` loops.+</Lang>++<Lang only="rust">++**Parameters:**++- `client` β An `OciClient`.+- `namespace` β The OCI Object Storage namespace.+- `bucket` β The bucket name.+- `options.prefix` β Only list objects whose name starts with this prefix. The prefix is stripped from the relative paths of the returned files.+- `options.path_matcher` β Optional filter for files. Patterns are matched against the relative path (after prefix stripping). See [PatternFilePathMatcher](../common_resources/data_types#patternfilepathmatcher).+- `options.max_file_size` β Skip objects larger than this size in bytes.++**Returns:** An `OciWalker`.++</Lang>+### Iterating files+<Lang only="python">+`list_objects()` returns an `OCIWalker` that yields `OCIFile` objects (implementing the [`FileLike`](../common_resources/data_types#filelike) base class):+</Lang>++<Lang only="rust">++`OciWalker::list()` returns `OciFile` values, which implement the [`FileLike`](../common_resources/data_types#filelike) trait:++</Lang>+{/* Rust: examples/rust/oci_object_storage_embedding/src/main.rs */}<LangTabs><Fragment slot="python">@@ -201,7 +274,7 @@ See [`FileLike`](../common_resources/data_types#filelike) for details on the fil### Keyed iteration with `items()`-`OCIWalker.items()` yields `(str, OCIFile)` pairs, useful for associating each file with a stable string key: the object name relative to the prefix, exactly as stored. Keys are not normalized, so `a//b.txt` and `a/b.txt` are two items. Live events use the same keys:+<Lang only="python">`OCIWalker.items()` yields `(str, OCIFile)` pairs</Lang><Lang only="rust">`OciWalker::items()` returns `(String, OciFile)` pairs</Lang>, useful for associating each file with a stable string key: the object name relative to the prefix, exactly as stored. Keys are not normalized, so `a//b.txt` and `a/b.txt` are two items. Live events use the same keys:{/* Rust: examples/rust/oci_object_storage_embedding/src/main.rs */}<LangTabs>@@ -349,6 +422,8 @@ pub async fn OciClient::get_object_uri(&self, uri: &str) -> Result<OciFile></Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `client` β An `oci.object_storage.ObjectStorageClient`.@@ -358,6 +433,14 @@ pub async fn OciClient::get_object_uri(&self, uri: &str) -> Result<OciFile>**Returns:** An `OCIFile` (FileLike) for the specified object, with its metadata pre-populated.+</Lang>++<Lang only="rust">++**Returns:** An `OciFile` for the specified object, with its metadata from a `HEAD` request. Its relative path is the full object name.++</Lang>+**Example:**{/* Rust: rust/sdk/cocoindex/src/connectors/oci_object_storage.rs */}@@ -414,6 +497,8 @@ The Rust client reads an `OciFile`, not a name: get the file with `get_object` f</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `client` β An `oci.object_storage.ObjectStorageClient`.@@ -424,6 +509,8 @@ The Rust client reads an `OciFile`, not a name: get the file with `get_object` f**Returns:** The object content as bytes.+</Lang>+**Example:**{/* Rust: rust/sdk/cocoindex/src/connectors/oci_object_storage.rs */}@@ -445,8 +532,20 @@ let data = client.read(&f).await?;</Fragment></LangTabs>+<Lang only="python">+### OCIFilePath+</Lang>++<Lang only="rust">++### OciFilePath++</Lang>++<Lang only="python">+Each file returned by the connector has an `OCIFilePath` β a [`FilePath`](../common_resources/data_types#filepath) specialized for OCI Object Storage:- **Relative path** (`file.file_path.path`) β The object name relative to the walker prefix (or the full name if no prefix was used).@@ -460,12 +559,40 @@ For example, with `prefix="data/"` and an object named `"data/docs/readme.md"`:A derived path (`parent`, `/`, `with_name()`, `with_suffix()`) resolves to the object name of the new path in the same folder: `file.file_path.with_suffix(".txt").resolve()` β `"data/docs/readme.txt"`.-The Rust `OciFilePath` (`file.file_path()`) has `namespace()`, `bucket()`, `path()` (the relative name, a `&str`) and `resolve()` (the full object name). It has no derived-path methods. `OciFile` has the public fields `size`, `modified_secs` and `etag`, plus `key()`, `read()`, `read_size(n)` and `read_text()`; it implements `FileLike` and `MemoInput`.+</Lang>++<Lang only="rust">++Each file returned by the connector has an `OciFilePath` (`file.file_path()`):++- **Relative path** (`path()`, a `&str`) β The object name relative to the walker prefix (or the full name if no prefix was used).+- **Resolved path** (`resolve()`) β The full OCI object name.+- **Namespace and bucket** β `namespace()`, `bucket()`.++For example, with prefix `"data/"` and an object named `"data/docs/readme.md"`, `path()` is `"docs/readme.md"` and `resolve()` is `"data/docs/readme.md"`.++</Lang>++<RustNote>+`OciFilePath` has no derived-path methods (`parent`, `/`, `with_name()`, `with_suffix()`). `OciFile` has the public fields `size`, `modified_secs` and `etag`, plus `key()`, `read()`, `read_size(n)` and `read_text()`; it implements `FileLike` and `MemoInput`.+</RustNote>++<Lang only="python">### OCIFile.exists()`OCIFile` provides an async `exists()` method that probes whether the object currently exists in OCI:+</Lang>++<Lang only="rust">++### OciFile::exists()++`OciFile::exists()` probes whether the object currently exists in OCI, with a `HEAD` request:++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/oci_object_storage.rs (OciFile::exists) */}<LangTabs><Fragment slot="python">@@ -491,15 +618,37 @@ if oci_file.exists().await? {</Fragment></LangTabs>+<Lang only="python">+Call `exists()` first and branch on the result; on a `True` verdict, subsequent `size()` / `read()` calls reuse the cached metadata without re-probing.+</Lang>++<Lang only="rust">++Call `exists()` first and branch on the result, instead of letting `read()` fail on a `404`. The verdict is kept for the lifetime of the `OciFile`: fetch the object again for a fresh probe.++</Lang>+### Live bucket watching+<Lang only="python">+When `live_stream` is provided, `items()` returns a [`LiveMapView`](../advanced_topics/live_component#livemapfeed-and-livemapview) instead of a plain `AsyncIterable`. Combined with [`mount_each()`](../programming_guide/processing_component#mount_each), this enables automatic incremental bucket watching β newly created, updated, and deleted objects are processed without a full rescan.The typical setup uses **OCI Streaming**. Configure an [OCI Events Rule](https://docs.oracle.com/en-us/iaas/Content/Events/Concepts/eventsoverview.htm) that forwards Object Storage events (`createobject`, `updateobject`, `deleteobject`) to an OCI Streaming stream, then consume that stream as a `LiveStream[bytes]` via the Kafka connector β see [`topic_as_stream()` and `payloads()`](./kafka#as-a-live-stream) for the consumer / stream setup β and pass it as `live_stream`:-{/* Rust: rust/sdk/cocoindex/tests/oci_live.rs */}+</Lang>++<Lang only="rust">++`list_objects_live()` returns an `OciLiveWalker`, a [`LiveMapFeed`](../advanced_topics/live_component#livemapfeed-and-livemapview) of `OciFile`s. Combined with `ctx.mount_each_live`, this enables automatic incremental bucket watching β newly created, updated, and deleted objects are processed without a full rescan.++The typical setup uses **OCI Streaming**. Configure an [OCI Events Rule](https://docs.oracle.com/en-us/iaas/Content/Events/Concepts/eventsoverview.htm) that forwards Object Storage events (`createobject`, `updateobject`, `deleteobject`) to an OCI Streaming stream, then consume that stream as a `LiveStream<Vec<u8>>` via the Kafka connector β see [`topic_as_stream()` and `payloads()`](./kafka#as-a-live-stream) for the consumer / stream setup β and pass it as `events`:++</Lang>++{/* Rust: rust/sdk/SHOWCASE.md (OCI live view), rust/sdk/cocoindex/tests/oci_live.rs */}<LangTabs><Fragment slot="python">@@ -526,8 +675,19 @@ await coco.mount_each(process_file, walker.items(), target)<Fragment slot="rust">```rust+use cocoindex::connectors::kafka;use cocoindex::connectors::oci_object_storage::{ListOptions, OciFile, list_objects_live};+let consumer = kafka::KafkaConsumer::connect_with_options(+ &["<oci-streaming-bootstrap-host>:9092"],+ kafka::KafkaConsumerOptions {+ consumer_group: Some("my-group".to_string()),+ ..Default::default()+ },+)+.await?;+let events = kafka::topic_as_stream(&consumer, ["object-storage-events"]).payloads();+let feed = list_objects_live(&client,"my-namespace",@@ -545,7 +705,9 @@ ctx.mount_each_live(&"objects", feed, move |_ctx, file: OciFile| {.await```-`list_objects_live(client, namespace, bucket, options, events)` returns an `OciLiveWalker`, a `LiveMapFeed<String, OciFile>` for `ctx.mount_each_live`. `events` is any `futures::Stream<Item = Vec<u8>>` of raw OCI event JSON payloads, one event per item; the Rust SDK has no `payloads()` adapter from the Kafka connector, so you wire the stream to your event delivery yourself. Each event is confirmed with a `HEAD` of the object: a present object is an update, a `404` a delete. `OciLiveWalker::logic_version(version)` opts into skipping the startup scan on a rerun whose recorded version matches; bump it whenever the processing logic changes.+`events` is any `LiveStream<Vec<u8>>` of raw OCI event JSON payloads, one event per item, such as the Kafka connector's `topic_as_stream(..).payloads()`. Each event is confirmed with a `HEAD` of the object: a present object is an update, a `404` a delete. The walker acknowledges each event to the stream once the object it names has synced (at once when the event is filtered out), so a consumer group's committed offset never passes an unprocessed event.++`OciLiveWalker::logic_version(version)` opts into skipping the startup scan on a rerun whose recorded version matches, and relies on the durable stream to replay the backlog. Bump the version whenever the processing logic changes.</Fragment></LangTabs>diff --git a/docs/src/content/docs/connectors/qdrant.mdx b/docs/src/content/docs/connectors/qdrant.mdxindex 5663c6ec..7c919692 100644--- a/docs/src/content/docs/connectors/qdrant.mdx+++ b/docs/src/content/docs/connectors/qdrant.mdx@@ -5,11 +5,15 @@ description: >Write points to Qdrant collections with single or named dense vectors, sparsevectors, multi-vector support, and schemaless payloads β configured viaQdrantVectorDef and QdrantSparseVectorDef.+rust_description: >+ Write points to Qdrant collections with single or named dense vectors, sparse+ vectors, multi-vector support, and schemaless JSON payloads β configured via+ CollectionSchema, QdrantVectorDef and QdrantSparseVectorDef.----The `qdrant` connector provides utilities for writing points to Qdrant vector databases, with support for single vectors, named dense vectors, sparse vectors, and multi-vector configurations.-import LangTabs from '../../../components/LangTabs.astro';+The `qdrant` connector provides utilities for writing points to Qdrant vector databases, with support for single vectors, named dense vectors, sparse vectors, and multi-vector configurations.+{/* Rust: examples/rust/text_embedding_qdrant/src/main.rs */}<LangTabs><Fragment slot="python">@@ -27,11 +31,11 @@ use cocoindex::connectors::qdrant::{};```-The module is compiled with the `qdrant` Cargo feature of the `cocoindex` crate. The `qdrant-client` crate compiles protobufs, so a `protoc` binary must be on `PATH` (or named by `PROTOC`) to build.-</Fragment></LangTabs>+<Lang only="python">+:::note[Dependencies]This connector requires additional dependencies. Install with:@@ -41,10 +45,30 @@ pip install cocoindex[qdrant]:::+</Lang>++<Lang only="rust">++:::note[Dependencies]+The module is compiled with the `qdrant` Cargo feature of the `cocoindex` crate. The `qdrant-client` crate compiles protobufs, so a `protoc` binary must be on `PATH` (or named by `PROTOC`) to build.+:::++</Lang>+## Connection setup+<Lang only="python">+`create_client()` creates a Qdrant client connection with optional gRPC support.+</Lang>++<Lang only="rust">++`QdrantConnection` holds a shared `qdrant_client::Qdrant` client, which speaks gRPC. It is cheap to clone.++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/qdrant.rs */}<LangTabs><Fragment slot="python">@@ -74,6 +98,8 @@ impl QdrantConnection {</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `url` β Qdrant server URL (e.g., `"http://localhost:6333"`).@@ -82,6 +108,8 @@ impl QdrantConnection {**Returns:** A Qdrant client instance.+</Lang>+**Example:**{/* Rust: rust/sdk/cocoindex/tests/qdrant_target.rs, rust/sdk/cocoindex/src/connectors/qdrant.rs (from_client doctest) */}@@ -117,7 +145,7 @@ The `qdrant` connector provides target state APIs for writing points to collecti#### Setting up a connection-Create a `ContextKey[QdrantClient]` to identify your Qdrant client, then provide it in your lifespan:+Create a <Lang only="python">`ContextKey[QdrantClient]`</Lang><Lang only="rust">`ContextKey<QdrantConnection>`</Lang> to identify your Qdrant connection, then provide it in your lifespan::::noteThe key name is load-bearing across runs β it's the stable identity CocoIndex uses to track managed collections. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.@@ -215,6 +243,8 @@ pub async fn mount_collection_target_with_options(**Parameters:**+<Lang only="python">+- `db` β A `ContextKey[QdrantClient]` identifying the Qdrant client to use.- `collection_name` β Name of the collection.- `schema` β Schema definition specifying vector configurations (see [Collection Schema](#collection-schema)).@@ -222,10 +252,32 @@ pub async fn mount_collection_target_with_options(**Returns:** A pending `CollectionTarget`. Use the convenience wrapper `await qdrant.mount_collection_target(QDRANT_DB, collection_name, schema)` to resolve.+</Lang>++<Lang only="rust">++- `ctx` β The current component's `Ctx`.+- `conn` β A `ContextKey<QdrantConnection>` identifying the Qdrant connection to use.+- `collection_name` β Name of the collection.+- `schema` β Schema definition specifying vector configurations (see [Collection Schema](#collection-schema)).+- `options` β `ManagedTargetOptions`; `ManagedTargetOptions::user_managed()` assumes the collection exists instead of creating and dropping it.++</Lang>+#### Points (child states)+<Lang only="python">+Once a `CollectionTarget` is resolved, declare points to be upserted using `qdrant.PointStruct`, which is an alias of `qdrant_client.http.models.PointStruct`:+</Lang>++<Lang only="rust">++Once a `CollectionTarget` is resolved, declare points to be upserted with one of its `declare_*point` methods:++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/qdrant.rs */}<LangTabs><Fragment slot="python">@@ -276,11 +328,13 @@ impl CollectionTarget {}```-The Rust SDK has no `PointStruct`: the id, the vector and the payload are separate arguments, and the shape of the vector picks the method. The payload is a `serde_json::Map<String, Value>`.+The id, the vector and the payload are separate arguments, and the shape of the vector picks the method. The payload is a `serde_json::Map<String, Value>`. Each method checks the point against the collection schema and the id rules (see [Point IDs](#point-ids)) when it is called, and returns an error for a mismatch.</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `point` β A `qdrant.PointStruct` (alias of `qdrant_client.http.models.PointStruct`) containing:@@ -288,6 +342,8 @@ The Rust SDK has no `PointStruct`: the id, the vector and the payload are separa- `vector` β Vector data (single vector or dict of named vectors)- `payload` β Optional metadata as a JSON-serializable dict+</Lang>+### Collection schemaDefine vector configurations for a collection using `CollectionSchema`. Unlike row-oriented databases, Qdrant uses a point-oriented model where each point has schemaless payload and one or more vectors with predefined dimensions.@@ -341,11 +397,17 @@ impl CollectionSchema {}```-The Rust schema has one constructor per shape instead of one `create` with a union argument. `from_row` turns each `#[coco(vector)]` field of a row struct into a named dense vector; the other fields stay payload.+`from_row` turns each `#[coco(vector)]` field of a row struct into a named dense vector; the other fields stay payload. `with_vector_dim` sets the dimension of one such field, for a field whose size the struct does not fix.</Fragment></LangTabs>+<RustNote>+The Rust schema has one constructor per shape instead of one `create` with a union argument.+</RustNote>++<Lang only="python">+**Parameters:**- `vectors` β Either:@@ -354,6 +416,14 @@ The Rust schema has one constructor per shape instead of one `create` with a uniDense and sparse vectors share one namespace in Qdrant (the server rejects duplicate names across the two kinds), so both live in the same dict β a name collision is impossible to express. Sparse vectors are always named.+</Lang>++<Lang only="rust">++Dense and sparse vectors share one namespace in Qdrant (the server rejects duplicate names across the two kinds), so `CollectionSchema::named` takes both in one list of `(name, QdrantNamedVectorDef)` entries and returns an error for a name that appears twice. Sparse vectors are always named.++</Lang>+#### QdrantVectorDefSpecifies vector configuration including dimension, distance metric, and multi-vector settings:@@ -400,12 +470,22 @@ pub enum MultivectorComparator { MaxSim }</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `schema` β A `VectorSchemaProvider` or `MultiVectorSchemaProvider` that defines vector dimensions- `distance` β Distance metric for similarity search (default: `"cosine"`)- `multivector_comparator` β Comparator for multi-vector fields (only applies to `MultiVectorSchemaProvider`)+</Lang>++<Lang only="rust">++The constructor picks the shape: `new` and `f32` for a dense vector, `multivector` for a multi-vector field. `from_vector_provider` and `from_multivector_provider` take the dimension from a provider, typically the embedder. `multivector_comparator` is `MaxSim`, the only comparator.++</Lang>+#### QdrantSparseVectorDefSpecifies a named sparse vector configuration:@@ -433,7 +513,7 @@ pub enum SparseModifier { Idf }</Fragment></LangTabs>-Sparse vectors use Qdrant's native sparse-vector storage and dot-product scoring. The optional `modifier="idf"` enables Qdrant's IDF modifier for sparse vectors.+Sparse vectors use Qdrant's native sparse-vector storage and dot-product scoring. The optional <Lang only="python">`modifier="idf"`</Lang><Lang only="rust">`modifier: Some(SparseModifier::Idf)`</Lang> enables Qdrant's IDF modifier for sparse vectors.#### Single (unnamed) vector@@ -528,7 +608,8 @@ point = qdrant.PointStruct(```rustuse cocoindex::connectors::qdrant::{- CollectionSchema, Distance, QdrantNamedVectorDef, QdrantVectorDef,+ CollectionSchema, Distance, QdrantNamedVectorDef, QdrantSparseVectorDef,+ QdrantVectorDef,};let schema = CollectionSchema::named([@@ -589,6 +670,8 @@ target.declare_named_vectors_point(For hybrid retrieval, declare a named dense vector and a named sparse vector in the same collection:+<Lang only="python">+```pythonfrom qdrant_client.http import models as qdrant_modelsfrom cocoindex.resources.schema import VectorSchema@@ -607,6 +690,14 @@ schema = await qdrant.CollectionSchema.create(Points put both vector types in `PointStruct.vector`. The sparse vector is a native Qdrant `SparseVector`, not payload:+</Lang>++<Lang only="rust">++Points put both vectors in the named-vector list. The sparse vector is a native Qdrant sparse vector, not payload:++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/qdrant_target.rs */}<LangTabs><Fragment slot="python">@@ -659,9 +750,17 @@ for (id, dense, indices, values, text) in points {#### VectorSchemaProvider+<Lang only="python">+The `schema` field of `QdrantVectorDef` accepts a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), a `ContextKey`, or an explicit `VectorSchema` to specify the vector dimension and dtype. See [Vector Schema](../common_resources/vector_schema#vectorschemaprovider) for details.-In Rust, `QdrantVectorDef::new(VectorSchema::f32(384), distance)` takes an explicit schema and `QdrantVectorDef::from_vector_provider(&embedder, distance).await?` takes a provider. An `f16` schema is stored as Qdrant's `Float16` datatype.+</Lang>++<Lang only="rust">++`QdrantVectorDef::new(VectorSchema::f32(384), distance)` takes an explicit schema and `QdrantVectorDef::from_vector_provider(&embedder, distance).await?` takes a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider). An `f16` schema is stored as Qdrant's `Float16` datatype. See [Vector Schema](../common_resources/vector_schema#vectorschemaprovider) for details.++</Lang>#### Multi-vector support@@ -707,17 +806,39 @@ target.declare_multivector_point(&ctx, p.id, p.vectors.clone(), payload)?;### Distance metrics+<Lang only="python">+The `distance` parameter in `QdrantVectorDef` specifies the similarity metric:- `"cosine"` β Cosine similarity (default, normalized dot product)- `"dot"` β Dot product similarity- `"euclid"` β Euclidean distance (L2)-In Rust these are the `Distance::Cosine`, `Distance::Dot` and `Distance::Euclid` variants. Every Rust constructor takes the distance explicitly; there is no default.+</Lang>++<Lang only="rust">++The `Distance` argument specifies the similarity metric:++- `Distance::Cosine` β Cosine similarity (normalized dot product)+- `Distance::Dot` β Dot product similarity+- `Distance::Euclid` β Euclidean distance (L2)++</Lang>++<RustNote>+Every Rust constructor takes the distance explicitly; there is no default.+</RustNote>### Example: single vector-For Rust, the single-vector shape is `CollectionSchema::new(size, Distance::Cosine)` with `declare_point`, shown under [Single (unnamed) vector](#single-unnamed-vector). The end-to-end Rust example, `examples/rust/text_embedding_qdrant`, uses a named vector derived from a row struct; see [Example: named vectors](#example-named-vectors).+<Lang only="rust">++The single-vector shape is `CollectionSchema::new(size, Distance::Cosine)` with `declare_point`, shown under [Single (unnamed) vector](#single-unnamed-vector). The end-to-end example, `examples/rust/text_embedding_qdrant`, uses a named vector derived from a row struct; see [Example: named vectors](#example-named-vectors).++</Lang>++<Lang only="python">```pythonfrom qdrant_client import QdrantClient@@ -774,6 +895,8 @@ async def app_main() -> None:)```+</Lang>+### Example: named vectors{/* Rust: examples/rust/text_embedding_qdrant/src/main.rs */}@@ -898,7 +1021,13 @@ See `examples/rust/text_embedding_qdrant` for the full program.### Example: dense + sparse hybrid vectors-For Rust, see the snippet under [Dense + sparse vectors](#dense--sparse-vectors): `CollectionSchema::named` with a `QdrantSparseVectorDef`, and `declare_named_vectors_point` with `NamedPointVector::Sparse`.+<Lang only="rust">++See the snippet under [Dense + sparse vectors](#dense--sparse-vectors): `CollectionSchema::named` with a `QdrantSparseVectorDef`, and `declare_named_vectors_point` with `NamedPointVector::Sparse`.++</Lang>++<Lang only="python">```pythonfrom qdrant_client.http import models as qdrant_models@@ -936,30 +1065,61 @@ async def app_main() -> None:collection.declare_point(point)```+</Lang>+## Point IDsQdrant only accepts two point ID types β this is enforced by the Qdrant server itself (see [Qdrant's Point IDs documentation](https://qdrant.tech/documentation/manage-data/points/#point-ids)):+<Lang only="python">+- `int` β unsigned 64-bit integers (`0 <= id < 2**64`)- `str` β UUID strings, in any standard textual form (hyphenated, 32-character hex, or URN)`uuid.UUID` instances are also accepted and converted to strings. `declare_point` validates the ID eagerly and raises `ValueError` for anything else, rather than letting the write fail later at the Qdrant server.-In Rust, the id argument is `impl Into<QdrantPointId>`: a `u64` becomes `QdrantPointId::Num`, and a `String` or `&str` becomes `QdrantPointId::Uuid`.+</Lang>++<Lang only="rust">++- unsigned 64-bit integers β a `u64` id becomes `QdrantPointId::Num`+- UUIDs β a `uuid::Uuid`, `String` or `&str` id becomes `QdrantPointId::Uuid`; a string may be in any textual form Qdrant accepts (hyphenated, upper case, 32-character hex, URN or braced)++The id argument of each `declare_*point` method is `impl Into<QdrantPointId>`. The method validates the ID when it is called and returns an error for a string that is not a UUID, rather than letting the write fail later at the Qdrant server.++</Lang>Qdrant stores every textual form of one UUID as the same point. CocoIndex therefore tracks a UUID point ID in its canonical form (hyphenated, lower case). If you declare two forms of one UUID in the same run, the second declaration fails as a duplicate.To derive a stable point ID from an arbitrary string key (e.g. a document path or chunk key), use a deterministic UUID:+{/* Rust: rust/sdk/cocoindex/src/connectors/qdrant.rs (POINT_ID_RULE) */}+<LangTabs>+<Fragment slot="python">+```pythonimport uuidpoint_id = str(uuid.uuid5(uuid.NAMESPACE_URL, f"doc/{chunk_key}"))```+</Fragment>+<Fragment slot="rust">++```rust+let point_id = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_URL, format!("doc/{chunk_key}").as_bytes());+```++The `uuid` crate needs its `v5` feature for `Uuid::new_v5`.++</Fragment>+</LangTabs>+## Payloads-Point payloads are schemaless JSON objects. Any JSON-serializable Python data structure can be used. In Rust, the payload is a `serde_json::Map<String, Value>`, for example `json!({...}).as_object().unwrap().clone()`:+<Lang only="python">++Point payloads are schemaless JSON objects. Any JSON-serializable Python data structure can be used:```pythonpayload = {@@ -976,9 +1136,31 @@ payload = {}```+</Lang>++<Lang only="rust">++Point payloads are schemaless JSON objects: a `serde_json::Map<String, Value>`. The `json!` macro builds one:++{/* Rust: examples/rust/text_embedding_qdrant/src/main.rs */}++```rust+let payload = json!({+ "filename": p.filename,+ "chunk_start": p.chunk_start,+ "chunk_end": p.chunk_end,+ "text": p.text,+})+.as_object()+.unwrap()+.clone();+```++</Lang>+## Vector search-The connector focuses on writing points to Qdrant. For vector search, use the Qdrant client directly:+The connector focuses on writing points to Qdrant. For vector search, use the Qdrant client directly<Lang only="rust"> or the connector's search helpers</Lang>:{/* Rust: examples/rust/text_embedding_qdrant/src/main.rs, rust/sdk/cocoindex/tests/qdrant_target.rs */}<LangTabs>@@ -1022,11 +1204,13 @@ for hit in hits {}```-The Rust SDK has search helpers: `vector_search`, `named_vector_search`, `multivector_search` and `named_multivector_search`, each returning `Vec<QdrantHit>` with a `score` and a `payload`. For any other query, such as a hybrid query with prefetch and fusion, use `conn.client()`, the underlying `qdrant_client::Qdrant`.+The connector has search helpers: `vector_search`, `named_vector_search`, `multivector_search` and `named_multivector_search`, each returning `Vec<QdrantHit>` with a `score` and a `payload`. For any other query, such as a hybrid query with prefetch and fusion, use `conn.client()`, the underlying `qdrant_client::Qdrant`.</Fragment></LangTabs>+<Lang only="python">+For named vectors:```python@@ -1063,3 +1247,5 @@ results = client.query_points(with_payload=True,)```++</Lang>diff --git a/docs/src/content/docs/connectors/surrealdb.mdx b/docs/src/content/docs/connectors/surrealdb.mdxindex 22850428..c007f6b1 100644--- a/docs/src/content/docs/connectors/surrealdb.mdx+++ b/docs/src/content/docs/connectors/surrealdb.mdx@@ -25,11 +25,13 @@ from cocoindex.connectors import surrealdbuse cocoindex::connectors::surrealdb::{self, ColumnDef, Graph, TableSchema, VectorIndexOptions};```-The Rust SDK needs the `surrealdb` Cargo feature of the `cocoindex` crate.+The module is compiled with the `surrealdb` Cargo feature of the `cocoindex` crate.</Fragment></LangTabs>+<Lang only="python">+:::note[Dependencies]This connector requires additional dependencies. Install with:@@ -39,10 +41,22 @@ pip install cocoindex[surrealdb]:::+</Lang>+## Connection setup+<Lang only="python">+Create a `ConnectionFactory` and provide it via a `ContextKey`. It holds connection parameters and opens one authenticated connection per event 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 `surrealdb::Graph` and provide it under a context key. A `Graph` holds one authenticated WebSocket connection to a namespace and database, shared by all tables and batches.++</Lang>+:::noteThe 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.:::@@ -100,19 +114,93 @@ async fn main() -> Result<()> {</Fragment></LangTabs>+<Lang only="rust">++To sign in as another kind of user, use `Graph::connect_with_credentials(url, ns, db, credentials)`:++{/* Rust: rust/sdk/cocoindex/tests/surrealdb_target.rs (surrealdb_connects_with_a_database_user_when_available) */}+```rust+let graph = Graph::connect_with_credentials(+ &url,+ &ns,+ &db_name,+ surrealdb::Credentials::Database {+ username: "writer".to_string(),+ password: "writer-pass".to_string(),+ },+)+.await?;+```++`surrealdb::Credentials` has one variant per sign-in:++- `Root { username, password }` β a root user (what `Graph::connect` uses).+- `Namespace { username, password }` β a user of the connection's namespace.+- `Database { username, password }` β a user of the connection's database.+- `Record { access, params }` β a record user, through the access method `access` of the connection's database, with the `params` (a `serde_json::Value`) that method expects.+- `None` β no sign-in, for a server started without authentication.++The graph's stable identity is the context key's name; the credentials are not part of any stored state. `graph.client()` returns the underlying `surrealdb::Surreal` client, for queries of your own.++</Lang>+## As targetThe `surrealdb` connector provides target state APIs for writing records to normal tables and relation tables. CocoIndex tracks what records should exist and automatically handles upserts and deletions.+<Lang only="python">+Writes are sent as typed parameters (`datetime`, `date`, `Decimal`, `UUID`, `bytes`, `timedelta`, lists and dicts arrive as native SurrealDB types, not strings).-**Transactions and errors.** The changes of each table are applied in chunks of at most 500 actions, each chunk one transaction (`Transaction conflict` errors are retried with backoff). Atomicity is per chunk, not across tables. Any statement error rolls the chunk back and raises, so the update fails and the affected components are retried on the next run.+</Lang>-**Record IDs** may be a string, an integer, or a tuple/list, which becomes an array ID (`person:['sap', '0001']`). Relation endpoints (`from_id`, `to_id`) take the same forms. In Rust a record id is any `IntoRecordId` value: an integer, a `String` or a `&str`; array ids have no Rust counterpart.+<Lang only="rust">++Writes are sent as typed parameters, never inlined in the statement: top-level values of `datetime`, `uuid`, `decimal`, `duration` and `bytes` columns arrive as native SurrealDB types, not strings, and a top-level `None` is sent as `NONE`.++</Lang>++**Transactions and errors.** The changes of each table are applied in chunks of at most 500 actions, each chunk one transaction and one round trip (`Transaction conflict` errors are retried with backoff, five attempts in all). Atomicity is per chunk, not across tables. Any statement error rolls the chunk back and raises, so the update fails and the affected components are retried on the next run.++<Lang only="python">++**Record IDs** may be a string, an integer, or a tuple/list, which becomes an array ID (`person:['sap', '0001']`). Relation endpoints (`from_id`, `to_id`) take the same forms.++</Lang>++<Lang only="rust">++**Record IDs** are any `IntoRecordId` value: an integer (`i8` through `i64`, `u8` through `u64`, `isize`, `usize`), a `String` or a `&str`. Relation endpoints (`from_id`, `to_id`) take the same forms.++</Lang>++<RustNote>+Array record IDs (`person:['sap', '0001']`) are not supported: `IntoRecordId` has no tuple or list form.+</RustNote>++<Lang only="python">**Ownership.** `declare_record` writes with `UPSERT ... MERGE`, never `CONTENT`: fields written by other owners survive, and fields you stop declaring are unset. Use `declare_fields` when a pipeline contributes only some fields of a record that another pipeline owns. Relation records are single-owner and are replaced whole.-**DDL.** Table and field definitions use `OVERWRITE`, so they are idempotent. With `managed_by="user"` CocoIndex never runs DDL on tables (indexes declared with `declare_vector_index` are still created).+</Lang>++<Lang only="rust">++**Ownership.** `declare_record` writes with `UPSERT ... SET`, one assignment per field, never `CONTENT`: fields written by other owners survive, and fields you stop declaring are unset. Each declared field's value is replaced whole, nested objects included. Field names must be identifiers (ASCII letters, digits and `_`). Use `declare_fields` when a pipeline contributes only some fields of a record that another pipeline owns. Relation records are single-owner and are replaced whole.++</Lang>++<RustNote>+Python writes a record with `UPSERT ... MERGE`, which merges nested objects. Rust writes `SET`, one assignment per field, so a nested key a row stops declaring is removed with the rest of the old value.+</RustNote>++<Lang only="rust">++**Server version.** A relation record that changes is replaced with `DELETE` and then `RELATE` in one transaction. SurrealDB 3.2.4 rejects this with "already exists"; use SurrealDB 3.3.5 or later when relation records change.++</Lang>++**DDL.** Table and field definitions use `OVERWRITE`, so they are idempotent. <Lang only="python">With `managed_by="user"`</Lang><Lang only="rust">For a user-managed table (`ManagedTargetOptions::user_managed()`)</Lang> CocoIndex never runs DDL on tables (indexes declared with `declare_vector_index` are still created).### Declaring target states@@ -153,13 +241,15 @@ pub fn declare_table_target_with_schema_and_options() -> Result<TableTarget>```-`declare_table_target` declares a schemaless, system-managed table. The `mount_*` forms (`mount_table_target`, `mount_table_target_with_schema`, `mount_table_target_with_options`, `mount_table_target_with_schema_and_options`) are `async` and return a resolved target. `ManagedTargetOptions::user_managed()` is Python's `managed_by="user"`.+`declare_table_target` declares a schemaless, system-managed table in the current component; its records resolve when the component commits. The `mount_*` forms (`mount_table_target`, `mount_table_target_with_schema`, `mount_table_target_with_options`, `mount_table_target_with_schema_and_options`) are `async` and return a target whose records can be declared at once.</Fragment></LangTabs>**Parameters:**+<Lang only="python">+- `db` β A `ContextKey[surrealdb.ConnectionFactory]` for the SurrealDB connection.- `table_name` β Name of the table.- `table_schema` β Optional schema definition (see [Table Schema](#table-schema-from-python-class)). When provided, the table is `SCHEMAFULL`; when omitted, the table is `SCHEMALESS`.@@ -167,6 +257,19 @@ pub fn declare_table_target_with_schema_and_options(**Returns:** A pending `TableTarget`. Use `await surrealdb.mount_table_target(SURREAL_DB, ...)` to get a resolved target.+</Lang>++<Lang only="rust">++- `graph` β The context key of the `surrealdb::Graph`.+- `table_name` β Name of the table.+- `table_schema` β Optional schema definition (see [Table schema: from a row struct](#table-schema-from-a-row-struct)). When provided, the table is `SCHEMAFULL`; when `None`, the table is `SCHEMALESS`.+- `options` β `ManagedTargetOptions::user_managed()` assumes the table exists; the default lets CocoIndex manage its lifecycle.++**Returns:** A `TableTarget`. It serializes to its stable key (the graph's context key and the table name), so it can be an argument of `mount!`, `use_mount!`, `mount_each!` and memoized functions.++</Lang>+#### Records (child states)Once a `TableTarget` is resolved, declare records to be upserted:@@ -197,17 +300,21 @@ pub fn TableTarget::declare_record<R: serde::Serialize>(pub fn TableTarget::declare_row<R: serde::Serialize>(&self, ctx: &Ctx, row: &R) -> Result<()>```-`declare_record` takes the record id separately, so the row struct has no `id` field. `declare_row` takes the id from the row's own scalar `id` field, as Python does.+`declare_record` takes the record id separately, so the row struct has no `id` field. `declare_row` takes the id from the row's own scalar `id` field.</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `row` β A row object (dict, dataclass, NamedTuple, or Pydantic model). Must include an `id` field.`declare_row` is an alias for `declare_record`, for compatibility with Postgres and other RDBMS targets.+</Lang>+{/* Rust: rust/sdk/SHOWCASE.md (declare_fields), verified against rust/sdk/cocoindex/src/connectors/surrealdb.rs and tests/surrealdb_target.rs */}<LangTabs><Fragment slot="python">@@ -247,7 +354,7 @@ players.declare_fields(ctx, "ann", "stats", &json!({ "score": 7, "rank": 1 }))?;</Fragment></LangTabs>-Declares the fields one owner (`group`) contributes to a record. It runs `UPDATE $id MERGE {fields}` and touches nothing else. When the declaration goes away, or a field is dropped from it, those fields are unset. If the record does not exist, the write raises and is retried on the next run, so declare the base record in the same or another pipeline.+Declares the fields one owner (`group`) contributes to a record. It runs <Lang only="python">`UPDATE $id MERGE {fields}`</Lang><Lang only="rust">`UPDATE $id SET β¦` with only these fields</Lang> and touches nothing else. When the declaration goes away, or a field is dropped from it, those fields are unset. If the record does not exist, the write raises and is retried on the next run, so declare the base record in the same or another pipeline.#### Relation tables (parent state)@@ -297,13 +404,15 @@ pub async fn mount_relation_target_unconstrained() -> Result<RelationTarget>```-`mount_relation_target` connects one source table to one target table, schemaless. `mount_relation_target_many` takes the collections of Python's polymorphic form and an optional schema. `mount_relation_target_unconstrained` accepts any endpoint tables. Each has a `_with_options` form that takes `ManagedTargetOptions`, and a `declare_relation_target_*` form that declares the table in the current component.+`mount_relation_target` connects one source table to one target table, schemaless. `mount_relation_target_many` takes slices of source and target tables, for a polymorphic relation, and an optional schema. `mount_relation_target_unconstrained` accepts any endpoint tables. Each has a `_with_options` form that takes `ManagedTargetOptions`, and a `declare_relation_target_*` form that declares the table in the current component.</Fragment></LangTabs>**Parameters:**+<Lang only="python">+- `db` β A `ContextKey[surrealdb.ConnectionFactory]` for the SurrealDB connection.- `table_name` β Name of the relation table.- `from_table` β Source table(s). Pass a single `TableTarget` or a collection for polymorphic relations.@@ -313,6 +422,21 @@ pub async fn mount_relation_target_unconstrained(**Returns:** A pending `RelationTarget`. Use `await surrealdb.mount_relation_target(SURREAL_DB, ...)` to get a resolved target.+</Lang>++<Lang only="rust">++- `graph` β The context key of the `surrealdb::Graph`.+- `table_name` β Name of the relation table.+- `from_table` / `from_tables` β Source table(s). `mount_relation_target_many` takes a slice for polymorphic relations.+- `to_table` / `to_tables` β Target table(s). Same rules as the source.+- `table_schema` β Optional schema (`mount_relation_target_many` only). The schema does **not** require an `id` field (unlike normal tables).+- `options` β `ManagedTargetOptions` (`_with_options` forms): whether CocoIndex manages the table lifecycle.++**Returns:** A `RelationTarget`, which serializes to its stable key like a `TableTarget`.++</Lang>+#### Relations (child states)Once a `RelationTarget` is resolved, declare relation records:@@ -382,8 +506,8 @@ statement_mentions.declare_relation_between(- `from_id` β ID of the source record.- `to_id` β ID of the target record.-- `record` β Optional data fields for the relation. The `id` field is optional: when absent, the record id is a string derived from the two endpoint tables and IDs. Each part is length-prefixed and each endpoint ID carries its type, so distinct endpoints always give distinct ids (`doc:'chunk_1'` and `doc_chunk:'1'` differ, as do `1` and `'1'`). Treat the derived id as opaque. Pass an explicit `id` if other code needs to know it.-- `from_table` / `to_table` β Required when the relation was declared with multiple (polymorphic) source/target tables.+- `record` β <Lang only="python">Optional data fields for the relation.</Lang><Lang only="rust">Data fields for the relation (`declare_relation_record` and `declare_relation_record_between`).</Lang> The `id` field is optional: when absent, the record id is a string derived from the two endpoint tables and IDs. Each part is length-prefixed and each endpoint ID carries its type, so distinct endpoints always give distinct ids (`doc:'chunk_1'` and `doc_chunk:'1'` differ, as do `1` and `'1'`). Treat the derived id as opaque. Pass an explicit `id` if other code needs to know it.+- `from_table` / `to_table` β Required when the relation was declared with multiple (polymorphic) source/target tables<Lang only="rust"> (the `_between` methods)</Lang>.#### Vector indexes (attachment)@@ -423,7 +547,7 @@ pub struct VectorIndexOptions {pub name: Option<String>,/// Distance metric: `"cosine"`, `"euclidean"`, or `"manhattan"`.pub metric: &'static str,- /// Index method: `"mtree"` or `"hnsw"`.+ /// Index method: `"hnsw"` (SurrealDB 3 removed `MTREE`).pub method: &'static str,/// Vector element type: `"f32"`, `"f64"`, `"i16"`, `"i32"`, or `"i64"`.pub vector_type: &'static str,@@ -445,7 +569,7 @@ docs.declare_vector_index()?;```-The Rust default `method` is `"mtree"`, which SurrealDB 3 removed: set `method: "hnsw"`.+`VectorIndexOptions::default()` is `metric: "cosine"`, `method: "hnsw"`, `vector_type: "f32"` and no name.</Fragment></LangTabs>@@ -459,10 +583,22 @@ The Rust default `method` is `"mtree"`, which SurrealDB 3 removed: set `method:- `dimension` β Vector dimension (required).- `vector_type` β Vector element type: `"f32"`, `"f64"`, `"i16"`, `"i32"`, or `"i64"`.+<Lang only="python">+### Table schema: from Python classDefine the table structure using a Python class (dataclass, NamedTuple, or Pydantic model):+</Lang>++<Lang only="rust">++### Table schema: from a row struct++Define the table structure with a row struct:++</Lang>+{/* Rust: rust/sdk/SHOWCASE.md (SurrealDB), verified against rust/sdk/cocoindex/src/connectors/surrealdb.rs */}<LangTabs><Fragment slot="python">@@ -503,15 +639,17 @@ let sessions = surrealdb::mount_table_target_with_schema(sessions.declare_record(ctx, session_id, &session)?;```-A vector field needs `#[coco(vector = N)]` with its dimension; a bare `#[coco(vector)]` is an error for SurrealDB.+A vector field needs its dimension: give it in the attribute (`#[coco(vector = N)]`), or mark the field `#[coco(vector)]` and resolve the dimension with `with_vector_schema` (see [Column overrides](#column-overrides)). Declaring a table with a vector dimension still unresolved is an error.</Fragment></LangTabs>+<Lang only="python">+**Parameters:**- `record_type` β A record type whose fields define table columns. For normal tables, must include an `id` field. For relation tables, `id` is optional.-- `column_overrides` β Optional per-column overrides for type mapping or vector configuration. In Rust, a `#[coco(..)]` attribute on the field does this (see below).+- `column_overrides` β Optional per-column overrides for type mapping or vector configuration.**Example:**@@ -528,26 +666,64 @@ schema = await surrealdb.TableSchema.from_class(Product)Python types are automatically mapped to SurrealDB types:-| Python Type | Rust Type | SurrealDB Type |-|-------------|-----------|----------------|-| `bool` | `bool` | `bool` |-| `int` | `i16`, `i32`, `i64` (and the unsigned widths) | `int` |-| `float` | `f32`, `f64` | `float` |-| `decimal.Decimal` | `rust_decimal::Decimal` | `decimal` |-| `str` | `String` | `string` |-| `bytes` | `Vec<u8>` | `bytes` |-| `uuid.UUID` | `uuid::Uuid` | `uuid` |-| `datetime.datetime` | `chrono::DateTime`, `chrono::NaiveDateTime` | `datetime` |-| `datetime.date` | `chrono::NaiveDate` | `datetime` |-| `datetime.time` | `chrono::NaiveTime` | `datetime` (Python), `string` (Rust) |-| `datetime.timedelta` | `std::time::Duration` | `duration` |-| `list`, `dict`, nested structs | other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `object` (Python), `any` (Rust) |-| `NDArray` (with vector schema) | `#[coco(vector = N)] Vec<f32>` | `array<float, N>` |+| Python Type | SurrealDB Type |+|-------------|----------------|+| `bool` | `bool` |+| `int` | `int` |+| `float` | `float` |+| `decimal.Decimal` | `decimal` |+| `str` | `string` |+| `bytes` | `bytes` |+| `uuid.UUID` | `uuid` |+| `datetime.datetime` | `datetime` |+| `datetime.date` | `datetime` (midnight UTC) |+| `datetime.time` | `string` (ISO time) |+| `datetime.timedelta` | `duration` |+| `list` and other sequences | `array` |+| `dict`, nested records | `object` |+| `Any`, unions | `any` |+| `NDArray` (with vector schema) | `array<float, N>` |++</Lang>++<Lang only="rust">++Rust types are automatically mapped to SurrealDB types. An `Option<T>` field becomes `option<β¦>`:++| Rust Type | SurrealDB Type |+|-----------|----------------|+| `bool` | `bool` |+| `i16`, `i32`, `i64` (and the unsigned widths) | `int` |+| `f32`, `f64` | `float` |+| `rust_decimal::Decimal` | `decimal` |+| `String` | `string` |+| `Vec<u8>` | `bytes` |+| `uuid::Uuid` | `uuid` |+| `chrono::DateTime`, `chrono::NaiveDateTime` | `datetime` |+| `chrono::NaiveDate` | `datetime` (midnight UTC) |+| `chrono::NaiveTime` | `string` (ISO time) |+| `std::time::Duration` | `duration` |+| other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `any` |+| `#[coco(vector = N)] Vec<f32>` | `array<float, N>` |++</Lang>++<Lang only="python">#### SurrealTypeUse `SurrealType` to override the default type mapping:+</Lang>++<Lang only="rust">++#### Column overrides++Use a `#[coco(..)]` attribute on the field to override the default type mapping:++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/surrealdb.rs (from_row docs) */}<LangTabs><Fragment slot="python">@@ -578,6 +754,8 @@ struct MyRow {</Fragment></LangTabs>+<Lang only="python">+Or via `column_overrides`:```python@@ -591,6 +769,36 @@ schema = await surrealdb.TableSchema.from_class(For `NDArray` fields, a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider) annotation specifies the vector dimension and dtype. See [Vector Schema](../common_resources/vector_schema#vectorschemaprovider) for the full list of annotation options.+</Lang>++<Lang only="rust">++Or override a column of the derived schema. `with_column_type(field, surreal_type)` replaces the type of one column and keeps its nullability. `with_vector_schema(field, provider)` types a `#[coco(vector)]` column as `array<float, N>` from a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), typically the embedder that fills it (for an embedder held in the context, pass `ctx.get_key(&EMBEDDER)?`):++{/* Rust: rust/sdk/cocoindex/tests/surrealdb_target.rs (surrealdb_from_row_takes_column_overrides) */}+```rust+#[derive(cocoindex::SchemaFields)]+struct Doc {+ title: String,+ rank: Option<i64>,+ #[coco(vector)]+ embedding: Vec<f32>,+}++let embedder = cocoindex::VectorSchema {+ element_type: cocoindex::VectorElementType::Float32,+ size: 4,+};+let schema = TableSchema::from_row::<Doc>()?+ .with_vector_schema("embedding", &embedder)+ .await? // embedding: array<float, 4>+ .with_column_type("rank", "float")?; // rank: option<float>+```++Both fail if the schema has no column of that name; `with_vector_schema` also fails on a column that is not a vector.++</Lang>+### Table schema: explicit column definitionsDefine columns directly using `ColumnDef`:@@ -620,7 +828,7 @@ pub fn ColumnDef::new(surreal_type: impl Into<String>) -> Selfpub fn ColumnDef::nullable(self) -> Self```-A Rust `ColumnDef` is not nullable unless `.nullable()` is called; a nullable column is defined as `option<T>`.+A `ColumnDef` is not nullable unless `.nullable()` is called; a nullable column is defined as `option<T>`. There is no `id` column: the record id is passed to `declare_record`.</Fragment></LangTabs>diff --git a/docs/src/content/docs/connectors/turbopuffer.mdx b/docs/src/content/docs/connectors/turbopuffer.mdxindex bc2d741b..4a740831 100644--- a/docs/src/content/docs/connectors/turbopuffer.mdx+++ b/docs/src/content/docs/connectors/turbopuffer.mdx@@ -6,10 +6,10 @@ description: >per-namespace distance metric, and schemaless attributes β configured viaVectorDef and NamespaceSchema.----The `turbopuffer` connector provides utilities for writing rows to [Turbopuffer](https://turbopuffer.com/) namespaces, with support for both single and named vectors.-import LangTabs from '../../../components/LangTabs.astro';+The `turbopuffer` connector provides utilities for writing rows to [Turbopuffer](https://turbopuffer.com/) namespaces, with support for both single and named vectors.+{/* Rust: examples/rust/text_embedding_turbopuffer/src/main.rs */}<LangTabs><Fragment slot="python">@@ -27,11 +27,11 @@ use cocoindex::connectors::turbopuffer::{};```-The module is compiled with the `turbopuffer` Cargo feature of the `cocoindex` crate.-</Fragment></LangTabs>+<Lang only="python">+:::note[Dependencies]This connector requires additional dependencies. Install with:@@ -41,9 +41,19 @@ pip install cocoindex[turbopuffer]:::+</Lang>++<Lang only="rust">++:::note[Dependencies]+The module is compiled with the `turbopuffer` Cargo feature of the `cocoindex` crate.+:::++</Lang>+## Connection setup-Turbopuffer uses a single client object that owns the API key and region. Construct one using `AsyncTurbopuffer`:+Turbopuffer uses a single client object that owns the API key and region. Construct one using <Lang only="python">`AsyncTurbopuffer`</Lang><Lang only="rust">`TurbopufferConnection`</Lang>:{/* Rust: examples/rust/text_embedding_turbopuffer/src/main.rs */}<LangTabs>@@ -75,7 +85,15 @@ fn connect() -> Result<TurbopufferConnection> {</Fragment></LangTabs>-`turbopuffer.AsyncTurbopuffer` is re-exported from the [Turbopuffer Python SDK](https://github.com/turbopuffer/turbopuffer-python); importing it directly via `from turbopuffer import AsyncTurbopuffer` works too. The Rust SDK speaks the Turbopuffer HTTP API itself and uses no Turbopuffer crate.+<Lang only="python">++`turbopuffer.AsyncTurbopuffer` is re-exported from the [Turbopuffer Python SDK](https://github.com/turbopuffer/turbopuffer-python); importing it directly via `from turbopuffer import AsyncTurbopuffer` works too.++</Lang>++<RustNote>+The connector speaks the Turbopuffer HTTP API itself and uses no Turbopuffer crate, so there is no client type from a Turbopuffer SDK to construct.+</RustNote>## As target@@ -85,7 +103,7 @@ The `turbopuffer` connector provides target state APIs for writing rows to names#### Setting up a connection-Create a `ContextKey[AsyncTurbopuffer]` to identify your client, then provide it in your lifespan:+Create a <Lang only="python">`ContextKey[AsyncTurbopuffer]`</Lang><Lang only="rust">`ContextKey<TurbopufferConnection>`</Lang> to identify your client, then provide it in your lifespan::::noteThe key name is load-bearing across runs β it's the stable identity CocoIndex uses to track managed namespaces. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.@@ -173,6 +191,8 @@ pub async fn mount_namespace_target(**Parameters:**+<Lang only="python">+- `db` β A `ContextKey[AsyncTurbopuffer]` identifying the client to use.- `namespace_name` β Name of the namespace.- `schema` β Schema definition specifying vector configuration and distance metric (see [Namespace schema](#namespace-schema)).@@ -180,10 +200,32 @@ pub async fn mount_namespace_target(**Returns:** A pending `NamespaceTarget`. Use the convenience wrapper `await turbopuffer.mount_namespace_target(TPUF, namespace_name, schema)` to resolve.+</Lang>++<Lang only="rust">++- `ctx` β The current component's `Ctx`.+- `conn` β A `ContextKey<TurbopufferConnection>` identifying the connection to use.+- `namespace` β Name of the namespace: ASCII letters, digits, `-`, `_` and `.`.+- `schema` β Schema definition specifying vector configuration and distance metric (see [Namespace schema](#namespace-schema)).+- `options` β `ManagedTargetOptions` on the `_with_options` variants; `ManagedTargetOptions::user_managed()` assumes the namespace exists.++</Lang>+#### Rows (child states)+<Lang only="python">+Once a `NamespaceTarget` is resolved, declare rows to be upserted using `turbopuffer.Row`:+</Lang>++<Lang only="rust">++Once a `NamespaceTarget` is resolved, declare rows to be upserted with `declare_row` or `declare_named_row`:++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/turbopuffer.rs */}<LangTabs><Fragment slot="python">@@ -214,7 +256,7 @@ impl NamespaceTarget {pub fn declare_row(&self,ctx: &Ctx,- id: impl Into<String>,+ id: impl Into<RowId>,vector: Vec<f32>,attributes: Map<String, JsonValue>,) -> Result<()>@@ -223,7 +265,7 @@ impl NamespaceTarget {pub fn declare_named_row<I, K>(&self,ctx: &Ctx,- id: impl Into<String>,+ id: impl Into<RowId>,vectors: I,attributes: Map<String, JsonValue>,) -> Result<()>@@ -231,17 +273,34 @@ impl NamespaceTarget {I: IntoIterator<Item = (K, Vec<f32>)>,K: Into<String>}++pub enum RowId {+ Str(String),+ Int(u64),+}```-The Rust SDK has no `Row` type: the id, the vector(s) and the attributes are separate arguments. The id is a `String`; the attributes are a `serde_json::Map<String, Value>`. A vector with a NaN or infinite element is rejected.+The id, the vector(s) and the attributes are separate arguments. The id is a `RowId`, built from a `String`, a `&str` or a `u64`; the attributes are a `serde_json::Map<String, Value>`. A vector with a NaN or infinite element is rejected.</Fragment></LangTabs>+<Lang only="python">+- `id` β Document id (string or integer).- `vector` β For an unnamed-vector schema, pass a single sequence. For a named-vectors schema, pass a dict mapping vector field name to its sequence.- `attributes` β Non-vector attributes (text, tags, metadata, etc.). Turbopuffer infers attribute types from the data.+</Lang>++<Lang only="rust">++- `id` β Document id (string or unsigned integer).+- `vector` / `vectors` β For an unnamed-vector schema, pass one `Vec<f32>` to `declare_row`. For a named-vectors schema, pass `(name, vector)` pairs to `declare_named_row`.+- `attributes` β Non-vector attributes (text, tags, metadata, etc.). Turbopuffer infers attribute types from the data.++</Lang>+### Namespace schemaDefine vector configuration and distance metric for a namespace using `NamespaceSchema`:@@ -288,18 +347,33 @@ impl NamespaceSchema {pub enum DistanceMetric { CosineDistance, EuclideanSquared }```-The Rust schema has one constructor per shape instead of one `create` with a union argument. `from_row` turns each `#[coco(vector)]` field of a row struct into a named vector; the other fields stay schemaless attributes. Every constructor takes the distance explicitly.+`from_row` turns each `#[coco(vector)]` field of a row struct into a named vector; the other fields stay schemaless attributes. `with_vector_dim` sets the dimension of one such field.</Fragment></LangTabs>+<RustNote>+The Rust schema has one constructor per shape instead of one `create` with a union argument, and every constructor takes the distance explicitly.+</RustNote>+**Parameters:**+<Lang only="python">+- `vectors` β Either:- A single `VectorDef` for an unnamed vector (stored under turbopuffer's default `"vector"` field).- A dict mapping vector names to `VectorDef` for named vectors.- `distance` β Distance metric applied to all vector columns in the namespace. Turbopuffer applies a single distance metric per namespace.+</Lang>++<Lang only="rust">++- The vector shape β `new`, `from_vector_schema` and `from_vector_provider` declare an unnamed vector (stored under turbopuffer's default `"vector"` field); `named` and `from_row` declare named vectors.+- `distance` β Distance metric applied to all vector columns in the namespace. Turbopuffer applies a single distance metric per namespace.++</Lang>+#### VectorDefSpecifies a vector field's dimension and dtype:@@ -331,7 +405,17 @@ impl VectorDef {</Fragment></LangTabs>-The `schema` field accepts a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), a `ContextKey`, or an explicit `VectorSchema`. The dtype on the `VectorSchema` (must be `np.dtype(np.float32)` or `np.dtype(np.float16)`) controls turbopuffer's vector type β `[N]f32` or `[N]f16`. In Rust, `VectorSchema::f32(n)` and `VectorSchema::f16(n)` select the same two types, and `VectorDef::from_provider(&embedder).await?` resolves one from an embedder.+<Lang only="python">++The `schema` field accepts a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), a `ContextKey`, or an explicit `VectorSchema`. The dtype on the `VectorSchema` (must be `np.dtype(np.float32)` or `np.dtype(np.float16)`) controls turbopuffer's vector type β `[N]f32` or `[N]f16`.++</Lang>++<Lang only="rust">++The `schema` field is an explicit `VectorSchema`. Its dtype controls turbopuffer's vector type: `VectorSchema::f32(n)` gives `[N]f32` and `VectorSchema::f16(n)` gives `[N]f16`. `VectorDef::from_provider(&embedder).await?` resolves the schema from a [`VectorSchemaProvider`](../common_resources/vector_schema#vectorschemaprovider), typically the embedder.++</Lang>#### Single (unnamed) vector@@ -449,10 +533,21 @@ target.declare_named_row(Turbopuffer applies a single `distance_metric` per namespace. Supported values:+<Lang only="python">+- `"cosine_distance"` β Cosine distance (default).- `"euclidean_squared"` β Squared Euclidean distance.-In Rust these are `DistanceMetric::CosineDistance` and `DistanceMetric::EuclideanSquared`; every constructor takes the metric explicitly.+</Lang>++<Lang only="rust">++- `DistanceMetric::CosineDistance` β Cosine distance.+- `DistanceMetric::EuclideanSquared` β Squared Euclidean distance.++Every constructor takes the metric explicitly; there is no default.++</Lang>### Example@@ -592,13 +687,23 @@ See `examples/rust/text_embedding_turbopuffer` for the full program.## Row IDs-Turbopuffer rows are identified by `str` or `int`. UUIDs should be passed as strings. In Rust, the id is always a `String` (`impl Into<String>`).+<Lang only="python">++Turbopuffer rows are identified by `str` or `int`. UUIDs should be passed as strings.++</Lang>++<Lang only="rust">++Turbopuffer rows are identified by a string or an unsigned integer: the id argument is `impl Into<RowId>`, so a `String` or `&str` becomes `RowId::Str` and a `u64` becomes `RowId::Int`. UUIDs should be passed as strings. An integer id must fit in an `i64` (at most `i64::MAX`); a larger one is rejected when the row is declared.++</Lang>## Attributes-Row attributes are schemaless; turbopuffer infers attribute types from the values you write. Supported scalar types include `string`, `int`, `uint`, `float`, `bool`, `uuid`, and `datetime`, plus their array variants. See [Turbopuffer's schema reference](https://turbopuffer.com/docs/write#schema) for the full list. In Rust, the attributes are a `serde_json::Map<String, Value>`.+Row attributes are schemaless; turbopuffer infers attribute types from the values you write. Supported scalar types include `string`, `int`, `uint`, `float`, `bool`, `uuid`, and `datetime`, plus their array variants. See [Turbopuffer's schema reference](https://turbopuffer.com/docs/write#schema) for the full list.<Lang only="rust"> The attributes are a `serde_json::Map<String, Value>`.</Lang>-Reserved attribute names depend on the schema; putting any reserved name in `Row.attributes` raises a `ValueError`:+Reserved attribute names depend on the schema; putting any reserved name in <Lang only="python">`Row.attributes` raises a `ValueError`</Lang><Lang only="rust">the attributes makes `declare_row` / `declare_named_row` return an error</Lang>:- `id` is always reserved β it's the row id.- For an unnamed-vector schema, `vector` is also reserved (it's the wire-level vector field).@@ -606,7 +711,7 @@ Reserved attribute names depend on the schema; putting any reserved name in `Row## Vector search-The connector focuses on writing rows. For vector search, use the turbopuffer client directly:+The connector focuses on writing rows. For vector search, use the turbopuffer client directly<Lang only="rust"> or the connector's search helpers</Lang>:{/* Rust: rust/sdk/cocoindex/tests/turbopuffer_target.rs, examples/rust/text_embedding_turbopuffer/src/main.rs */}<LangTabs>@@ -632,7 +737,7 @@ let hits =turbopuffer::vector_search_by_field(conn, namespace, "vector", query_vec, TOP_K).await?;```-The Rust SDK has two search helpers, `vector_search` and `vector_search_by_field`; each returns `Vec<TurbopufferHit>` with a `distance` and the row's `attributes`.+The connector has two search helpers, `vector_search` and `vector_search_by_field`; each returns `Vec<TurbopufferHit>` with a `distance` and the row's `attributes`.</Fragment></LangTabs>diff --git a/docs/src/content/docs/connectors/zvec.mdx b/docs/src/content/docs/connectors/zvec.mdxindex d0d0d1a2..0880cd42 100644--- a/docs/src/content/docs/connectors/zvec.mdx+++ b/docs/src/content/docs/connectors/zvec.mdx@@ -5,6 +5,10 @@ description: >Write documents to zvec, an embedded in-process vector database. Coverscollection setup, declaring documents with dense and sparse vectors plusscalar and full-text fields, schema-from-class type mapping, and lifecycle management.+rust_description: >+ Write documents to zvec, an embedded in-process vector database. Covers+ collection setup, declaring documents with dense vectors plus scalar, array+ and full-text fields, schema-from-row type mapping, and lifecycle management.---The `zvec` connector writes documents to [zvec](https://zvec.org), an embedded, in-process vector database. zvec runs inside your application (no server or daemon) and stores each collection in a directory on disk.@@ -33,6 +37,8 @@ The module is compiled with the `zvec` Cargo feature of the `cocoindex` crate. I</Fragment></LangTabs>+<Lang only="python">+:::note[Installation]zvec is an optional dependency:@@ -41,6 +47,8 @@ pip install cocoindex[zvec]```:::+</Lang>+## Connection setup### connect@@ -75,7 +83,7 @@ let conn = zvec::connect(tempdir.path().join("zvec"), ConnectOptions::default())**Parameters:**- `base_path` β Directory under which collections are stored. Created if missing.-- `enable_mmap` β Whether zvec uses memory-mapped I/O for data files.+- <Lang only="python">`enable_mmap`</Lang><Lang only="rust">`options.enable_mmap`</Lang> β Whether zvec uses memory-mapped I/O for data files.### ManagedConnection@@ -83,11 +91,11 @@ A handle to the base directory. zvec takes an exclusive write lock per open coll**Methods:**+<Lang only="python">+- `collection_path(name)` β Path to a collection's directory.- `close()` β Release all open collection handles (drops their write locks).-The Rust `ManagedConnection` has the same two methods, `collection_path(name)` and `close().await`, plus `base_path()` and `open_existing(name).await`, which returns a cached `zvec_rust::Collection` handle for queries. Drop that handle before a run that destroys the collection.-For a lifespan, use `managed_connection()`, which closes handles on exit:```python@@ -96,7 +104,24 @@ def managed_connection() -> Iterator[ManagedConnection]```-The Rust SDK has no `managed_connection()`: call `conn.close().await?` on shutdown.+</Lang>++<Lang only="rust">++- `base_path()` β The directory under which collections are stored.+- `collection_path(name)` β Path to a collection's directory.+- `open_existing(name).await` β Open an existing collection and return its cached `zvec_rust::Collection` handle, for queries.+- `open_or_create(name, &schema).await` β Open the collection, creating it from a `CollectionSchema` if it does not exist, and return its cached handle. A system-managed collection target does this itself; call it to set up a user-managed collection.+- `destroy(name).await` β Permanently delete the collection from disk, closing its cached handle first. A missing collection is not an error.+- `close().await` β Release all cached collection handles (drops their write locks).++A collection with a live handle cannot be destroyed: drop the handles from `open_existing` and `open_or_create` before `destroy`, and before a run that destroys the collection (a schema change, or the target no longer declared).++</Lang>++<RustNote>+There is no `managed_connection()` context manager: call `conn.close().await?` on shutdown.+</RustNote>## As target@@ -106,8 +131,18 @@ The `zvec` connector tracks which documents should exist in a collection and aut#### Setting up a connection+<Lang only="python">+Create a `ContextKey[zvec.ManagedConnection]` to identify your connection, then provide it in your lifespan:+</Lang>++<Lang only="rust">++Declare a context key for a `ManagedConnection` to identify your connection, then provide the connection at startup:++</Lang>+:::noteThe key name is load-bearing across runs β it's the stable identity CocoIndex uses to track managed documents. See [ContextKey as stable identity](../programming_guide/context#contextkey-as-stable-identity) before renaming.:::@@ -199,6 +234,8 @@ let target = zvec::mount_collection_target_with_options(**Parameters:**+<Lang only="python">+- `db` β A `ContextKey[ManagedConnection]` identifying the connection.- `collection_name` β Name of the collection (a subdirectory under the connection's base path).- `schema` β Schema definition (see [Collection schema](#collection-schema-from-python-class)).@@ -206,6 +243,18 @@ let target = zvec::mount_collection_target_with_options(**Returns:** A pending `CollectionTarget`. Use `await zvec.mount_collection_target(ZVEC_DB, collection_name, schema)` to resolve.+</Lang>++<Lang only="rust">++- `db` β The context key of the `ManagedConnection`.+- `collection_name` β Name of the collection (a subdirectory under the connection's base path).+- `schema` β Schema definition (see [Collection schema](#collection-schema-from-a-row-struct)).++The `*_with_options` variants take a `ManagedTargetOptions`: `ManagedTargetOptions::system_managed()` (the default) creates and destroys the collection, and `ManagedTargetOptions::user_managed()` assumes it already exists and writes documents only. Create a user-managed collection with `conn.open_or_create(name, &schema)`.++</Lang>+#### Documents (child states)Once a `CollectionTarget` is resolved, declare documents to be upserted:@@ -232,12 +281,26 @@ target.declare_row(&ctx, &doc)?;</Fragment></LangTabs>-The primary-key value becomes the document `id` (converted to `str`). In Rust, `row` is any `Serialize` value that serializes to an object with the schema's columns; extra fields are dropped and missing ones are null.+<Lang only="python">++The primary-key value becomes the document `id` (converted to `str`).### Collection schema: from Python classDefine the collection structure using a Python class (dataclass, NamedTuple, or Pydantic model):+</Lang>++<Lang only="rust">++The primary-key value becomes the document `id` (converted to a string). `row` is any `Serialize` value that serializes to an object with the schema's columns; extra fields are dropped and missing ones are null.++### Collection schema: from a row struct++Define the collection structure using a struct that derives `SchemaFields`:++</Lang>+{/* Rust: rust/sdk/cocoindex/src/connectors/zvec.rs */}<LangTabs><Fragment slot="python">@@ -269,13 +332,19 @@ impl CollectionSchema {}```-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_dim` for a vector dimension, `with_vector_def` for the index, `with_column_type` for a scalar type, `with_fts` for a full-text field. The zvec schema has no `with_vector_schema`; take the dimension from the embedder and pass it to `with_vector_dim`.+The row type is a struct that derives `SchemaFields` (and `Serialize`). Per-column overrides are builder calls on the derived schema: `with_vector_dim` for a vector dimension, `with_vector_def` for the index, `with_column_type` for a scalar or array type, `with_fts` for a full-text field.</Fragment></LangTabs>+<RustNote>+The zvec schema has no `with_vector_schema`: take the dimension from the embedder and pass it to `with_vector_dim`.+</RustNote>+**Parameters:**+<Lang only="python">+- `record_type` β A record type whose fields define the document structure.- `primary_key` β Exactly one column name. Its value becomes the document `id`.- `column_overrides` β Optional per-column overrides for type mapping or vector configuration.@@ -286,8 +355,21 @@ zvec documents have a single string `id`, so `primary_key` must name exactly oneBecause the id is `str(value)`, some key types are ambiguous: in a union or `Any` column, `1` and `"1"` get the same id, and `bytes` become the text `b'...'`. Creating a new collection raises a `ValueError` when the key column is typed `Any`, `object`, a union or `bytes`. A collection that CocoIndex already tracks keeps working. Use a `str` or `int` key column, and convert the value yourself if needed.:::+</Lang>++<Lang only="rust">++- `T` β A `SchemaFields` struct whose fields define the document structure.+- `primary_key` β Exactly one column name. Its value becomes the document `id`.++:::note[Single primary key]+zvec documents have a single string `id`, so `primary_key` must name exactly one column. Its value is converted to a string to form the id. Composite primary keys are not supported. The key column must be a `String`, `Uuid` or integer column, and not an `Option`; `from_row` returns an error otherwise.+:::++</Lang>+:::note[At least one vector field]-zvec is a vector database: every collection must declare at least one vector field (dense or sparse).+zvec is a vector database: every collection must declare at least one vector field<Lang only="python"> (dense or sparse)</Lang>.:::**Example:**@@ -331,29 +413,62 @@ fn simple_schema() -> CollectionSchema {}```-`#[coco(vector = N)]` fixes the dimension in the struct; a bare `#[coco(vector)]` leaves it to `with_vector_dim`. The primary key must be one `String`, `Uuid` or integer column, and not an `Option`.+`#[coco(vector = N)]` fixes the dimension in the struct; a bare `#[coco(vector)]` leaves it to `with_vector_dim`.</Fragment></LangTabs>+<Lang only="python">+Scalar Python types map to zvec field types as follows:-| Python Type | Rust Type | zvec `DataType` |-|-------------|-----------|-----------------|-| `bool` | `bool` | `BOOL` |-| `int` | `i64` (`i16`, `i32`: `INT32`) | `INT64` |-| `float` | `f64` (`f32`: `FLOAT`) | `DOUBLE` |-| `str` | `String` | `STRING` |-| `bytes` | `Vec<u8>` | `STRING` (base64) |-| `uuid.UUID` | `Uuid` | `STRING` |-| `decimal.Decimal` | `Decimal` | `STRING` |-| `datetime.date` / `time` / `datetime` | `NaiveDate`, `NaiveTime`, `DateTime` | `STRING` (ISO format) |-| `datetime.timedelta` | `Duration` | `DOUBLE` (total seconds) |-| `list[str]` / `list[int]` / `list[float]` / `list[bool]` | (no Rust counterpart; see below) | `ARRAY_STRING` / `ARRAY_INT64` / `ARRAY_DOUBLE` / `ARRAY_BOOL` |-| other `list`, `dict`, nested structs | other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `STRING` (JSON) |-| `NDArray` (with vector schema) | `Vec<f32>` with `#[coco(vector)]` | `VECTOR_FP32` (float32) or `VECTOR_FP16` (float16) |--Scalar fields get an invert index by default so they can be used in query filters. The primary-key column maps to the document `id` and is not stored as a separate field. The Rust SDK stores every `Vec<T>` other than `Vec<u8>` and a vector as a JSON string: it has no `ARRAY_*` mapping. It writes `float32` dense vectors only: a `#[coco(vector = N, half)]` field is an error, because the `zvec-rust` bindings have no float16 setter. For smaller storage, keep a float32 vector and set `quantize`.+| Python Type | zvec `DataType` |+|-------------|-----------------|+| `bool` | `BOOL` |+| `int` | `INT64` |+| `float` | `DOUBLE` |+| `str` | `STRING` |+| `bytes` | `STRING` (base64) |+| `uuid.UUID` | `STRING` |+| `decimal.Decimal` | `STRING` |+| `datetime.date` / `time` / `datetime` | `STRING` (ISO format) |+| `datetime.timedelta` | `DOUBLE` (total seconds) |+| `list[str]` / `list[int]` / `list[float]` / `list[bool]` | `ARRAY_STRING` / `ARRAY_INT64` / `ARRAY_DOUBLE` / `ARRAY_BOOL` |+| other `list`, `dict`, nested structs | `STRING` (JSON) |+| `NDArray` (with vector schema) | `VECTOR_FP32` (float32) or `VECTOR_FP16` (float16) |++</Lang>++<Lang only="rust">++Rust field types map to zvec field types as follows:++| Rust Type | zvec `DataType` |+|-----------|-----------------|+| `bool` | `BOOL` |+| `i16`, `i32` | `INT32` |+| `i64` | `INT64` |+| `f32` | `FLOAT` |+| `f64` | `DOUBLE` |+| `String` | `STRING` |+| `Vec<u8>` | `STRING` (base64) |+| `Uuid` | `STRING` |+| `Decimal` | `STRING` |+| `NaiveDate`, `NaiveTime`, `DateTime` | `STRING` (ISO format) |+| `Duration` | `DOUBLE` (total seconds) |+| `Vec<bool>`, `Vec<i64>`, `Vec<f64>`, β¦ with `#[coco(type = "array_bool")]`, `"array_int64"`, `"array_double"`, β¦ | `ARRAY_BOOL`, `ARRAY_INT64`, `ARRAY_DOUBLE`, β¦ |+| other `Vec<T>`, maps, nested structs, `#[coco(json)]` | `STRING` (JSON) |+| `Vec<f32>` with `#[coco(vector)]` | `VECTOR_FP32` |++An array field is opt-in: a `Vec<T>` without a `type` attribute or a `with_column_type` override is stored as a JSON string. The array types are `array_bool`, `array_int32`, `array_int64`, `array_uint32`, `array_uint64`, `array_float` and `array_double`.++</Lang>++Scalar fields get an invert index by default so they can be used in query filters. The primary-key column maps to the document `id` and is not stored as a separate field.++<RustNote>+There is no array of strings (`ARRAY_STRING`): a `Vec<String>` is stored as a JSON string. Only float32 dense vectors are written: a `#[coco(vector = N, half)]` field is an error, because the `zvec-rust` bindings have no float16 setter. For smaller storage, keep a float32 vector and set `quantize`.+</RustNote>#### ZvecType@@ -390,14 +505,33 @@ let schema = CollectionSchema::from_row::<TypedDoc>(["id"])?.with_column_type()?;```-`ScalarType` has `Bool`, `Int32`, `Int64`, `Uint32`, `Uint64`, `Float`, `Double` and `String`. A `#[coco(type = "int32")]` attribute on the field selects the type too (the names are case-insensitive), but keeps the index. Python's encoder has no counterpart: put `#[serde(serialize_with = "β¦")]` on the field.+`ScalarType` has `Bool`, `Int32`, `Int64`, `Uint32`, `Uint64`, `Float`, `Double` and `String`, and the array types `ArrayBool`, `ArrayInt32`, `ArrayInt64`, `ArrayUint32`, `ArrayUint64`, `ArrayFloat` and `ArrayDouble`. A `#[coco(type = "int32")]` attribute on the field selects the type too (the names are case-insensitive), but keeps the index. Array fields take the same attribute:++```rust+#[derive(Clone, Serialize, SchemaFields)]+struct ArrayDoc {+ id: String,+ #[coco(type = "array_int64")]+ ints: Vec<i64>,+ #[coco(type = "array_double")]+ floats: Vec<f64>,+ #[coco(type = "array_bool")]+ flags: Vec<bool>,+ #[coco(vector = 4)]+ embedding: Vec<f32>,+}+```</Fragment></LangTabs>+<RustNote>+`ZvecType` has no encoder: put `#[serde(serialize_with = "β¦")]` on the field to change how its value is written.+</RustNote>+#### ZvecFtsType-Mark a `str` field as full-text (FTS) indexed. The field is stored as a `STRING` field with a zvec FTS index, so you can run full-text match queries against it directly through zvec. Requires zvec >= 0.5.+Mark a string field as full-text (FTS) indexed. The field is stored as a `STRING` field with a zvec FTS index, so you can run full-text match queries against it directly through zvec. Requires zvec >= 0.5.{/* Rust: rust/sdk/cocoindex/tests/zvec_target.rs */}<LangTabs>@@ -435,16 +569,40 @@ let schema =</Fragment></LangTabs>-`ZvecFtsType` options: `tokenizer_name` (e.g. `"standard"`, `"jieba"`), `filters` (token filters applied after tokenization, default `("lowercase",)`), and `extra_params`. The connector writes the field and its FTS index; querying it (for example with `zvec.Query(field_name=..., fts=zvec.Fts(match_string=...))`) happens directly against zvec, since this connector only handles the write path. In Rust, query through `conn.open_existing(name).await?` and the re-exported `zvec_rust` API.+<Lang only="python">++`ZvecFtsType` options: `tokenizer_name` (e.g. `"standard"`, `"jieba"`), `filters` (token filters applied after tokenization, default `("lowercase",)`), and `extra_params`. The connector writes the field and its FTS index; querying it (for example with `zvec.Query(field_name=..., fts=zvec.Fts(match_string=...))`) happens directly against zvec, since this connector only handles the write path.++</Lang>++<Lang only="rust">++The connector writes the field and its FTS index; querying it happens directly against zvec, since this connector only handles the write path. Query through the handle from `conn.open_existing(name).await?` and the re-exported `zvec_rust` API.++</Lang>### Vectors-A collection can declare multiple named vector fields, dense and sparse, in one schema. zvec supports querying across them with reranking at read time.+A collection can declare multiple named vector fields<Lang only="python">, dense and sparse,</Lang> in one schema. zvec supports querying across them with reranking at read time.++<RustNote>+Sparse vectors and float16 dense vectors are not supported: the `zvec-rust` bindings have no document setter for them, so the connector writes float32 dense vectors only.+</RustNote>#### Dense vectors+<Lang only="python">+A NumPy `ndarray` field with a `VectorSchema` becomes a dense vector. The element dtype selects the zvec type: `float32` β `VECTOR_FP32`, `float16` β `VECTOR_FP16`. zvec's dense index only accepts these two; for smaller storage, keep a float32 vector and set `quantize`. Tune the HNSW index with `ZvecVectorDef`:+</Lang>++<Lang only="rust">++A `Vec<f32>` field marked `#[coco(vector)]` becomes a dense vector (`VECTOR_FP32`). For smaller storage, set `quantize`. Tune the HNSW index with `ZvecVectorDef`:++</Lang>+{/* Rust: rust/sdk/cocoindex/tests/zvec_target.rs */}<LangTabs><Fragment slot="python">@@ -491,11 +649,13 @@ let schema = CollectionSchema::from_row::<VectorDoc>(["id"])?</Fragment></LangTabs>+<Lang only="python">+`ZvecVectorDef` options: `metric` (`"cosine"`, `"ip"`, `"l2"`) and `quantize` (`"none"`, `"fp16"`, `"int8"`, `"int4"`).#### Sparse vectors-Mark a `dict[int, float]` field (mapping dimension β weight) as sparse with `ZvecVectorDef(sparse=True)`. The Rust SDK has no sparse vectors: the `zvec-rust` bindings have no document setter for them, so the Rust connector writes float32 dense vectors only.+Mark a `dict[int, float]` field (mapping dimension β weight) as sparse with `ZvecVectorDef(sparse=True)`.```python@dataclass@@ -504,6 +664,8 @@ class Doc:sparse: Annotated[dict[int, float], ZvecVectorDef(sparse=True)]```+</Lang>+## Full example{/* Rust: rust/sdk/SHOWCASE.md (verified against zvec.rs and tests/zvec_target.rs) */}