docs(python): show multiple embedding functions with Pydantic (#5371)

Closes #1911

## Why

The Managing Embeddings guide described multiple embedding columns at a
high level. Python readers needed a complete Pydantic example showing
how to pair the fields, populate both vectors, and choose which vector
column to search.

## What changed

- Explain the one-to-one pairing in `LanceModel`. Use the same
embedding-function instance for one `SourceField()` and one
`VectorField()`, and create a separate instance for each pair even when
the provider and settings match. If several fields should contribute to
one vector, combine their values into a single source field before
ingestion.
- Add a runnable LanceDB Embedded example that pairs `title` with
`title_vector` and `description` with `description_vector`. Both pairs
use separate instances of `all-MiniLM-L6-v2`. Inserting rows with titles
and descriptions populates both vector columns, and reopening the table
preserves both mappings.
- Show how `vector_column_name` selects the vector column and embedding
function for a text query. Searching titles for “Alpine hiking” returns
“Hiking in the Alps”, while searching descriptions for “feeding
sourdough starter” returns “Baking sourdough”.
- Generate the published snippet from the example test. This is a
documentation and example-test change.

## Validation

- The new docs test and existing multiple-embedding regression test
passed. The docs test mocks only model inference and checks both
persisted field mappings, the stored vectors and their dimensions, both
search results, and the ambiguity error when `vector_column_name` is
omitted.
- The generated example also passed with the cached real model. Both
columns contained 384-dimensional embeddings and both searches returned
the expected articles.
- Ruff lint and `git diff --check` passed. The formatter reports two
existing differences in unrelated examples in the same test file.
This commit is contained in:
TRexy
2026-12-02 21:06:42 +00:00
committed by GitHub
parent ff7a1c2c25
commit 50de29bdd5
3 changed files with 112 additions and 2 deletions
+86 -2
View File
@@ -1,8 +1,6 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import lancedb
# --8<-- [start:imports]
from lancedb.pydantic import LanceModel, Vector
from lancedb.embeddings import get_registry
@@ -90,6 +88,92 @@ def test_embeddings_manual_query():
# --8<-- [end:manual_query_embeddings]
def test_multiple_embedding_columns(monkeypatch):
from unittest.mock import Mock
import numpy as np
from lancedb.embeddings import SentenceTransformerEmbeddings
vectors = {
"Hiking in the Alps": [1.0, 0.0, 0.0, 0.0],
"A guide to mountain trails": [0.0, 1.0, 0.0, 0.0],
"Baking sourdough": [0.0, 0.0, 1.0, 0.0],
"How to feed a starter": [0.0, 0.0, 0.0, 1.0],
"Alpine hiking": [0.8, 0.0, 0.0, 0.6],
"feeding sourdough starter": [0.6, 0.0, 0.0, 0.8],
}
model = Mock()
model.encode.side_effect = lambda texts, **kwargs: np.asarray(
[vectors.get(text, [0.0] * 4) for text in texts]
)
monkeypatch.setattr(
SentenceTransformerEmbeddings, "get_embedding_model", lambda self: model
)
# --8<-- [start:multiple_embedding_columns]
import lancedb
from lancedb.embeddings import get_registry
from lancedb.pydantic import LanceModel
provider = get_registry().get("sentence-transformers")
title_embedder = provider.create(name="all-MiniLM-L6-v2")
description_embedder = provider.create(name="all-MiniLM-L6-v2")
class Article(LanceModel):
title: str = title_embedder.SourceField()
description: str = description_embedder.SourceField()
title_vector: list[float] = title_embedder.VectorField()
description_vector: list[float] = description_embedder.VectorField()
db = lancedb.connect("memory://")
table = db.create_table("articles", schema=Article)
table.add(
[
{
"title": "Hiking in the Alps",
"description": "A guide to mountain trails",
},
{"title": "Baking sourdough", "description": "How to feed a starter"},
]
)
table = db.open_table("articles")
title_match = (
table.search(
"Alpine hiking", query_type="vector", vector_column_name="title_vector"
)
.limit(1)
.to_list()[0]
)
description_match = (
table.search(
"feeding sourdough starter",
query_type="vector",
vector_column_name="description_vector",
)
.limit(1)
.to_list()[0]
)
print(title_match["title"]) # Hiking in the Alps
print(description_match["title"]) # Baking sourdough
# --8<-- [end:multiple_embedding_columns]
assert {
name: config.source_column for name, config in table.embedding_functions.items()
} == {"title_vector": "title", "description_vector": "description"}
stored = table.to_arrow()
assert stored.num_rows == 2
assert stored.schema.field("title_vector").type.list_size == 4
assert stored.schema.field("description_vector").type.list_size == 4
for row in stored.to_pylist():
assert row["title_vector"] == vectors[row["title"]]
assert row["description_vector"] == vectors[row["description"]]
assert title_match["title"] == "Hiking in the Alps"
assert description_match["title"] == "Baking sourdough"
with pytest.raises(ValueError, match="more than one vector column"):
table.search("Alpine hiking", query_type="vector")
def test_custom_embedding_function():
# --8<-- [start:embedding_function]
from functools import cached_property
+24
View File
@@ -13,6 +13,7 @@ import {
PyCreateEmbeddingFunction,
PyManualQuerySearch,
PyEmbeddingFunction,
PyMultipleEmbeddingColumns,
PyRegisterDevice,
PyRegisterSecret,
TsOpenaiEmbeddings,
@@ -164,6 +165,29 @@ maps one source column to one vector column, and the table schema can contain mu
The exact setup differs by SDK, but the underlying pattern is the same: define a distinct source/vector pair
for each embedding function you want applied during ingest.
### Multiple embedding pairs with Pydantic {#multiple-embedding-pairs-with-pydantic}
In a Python `LanceModel`, use the same embedding function instance for one `SourceField()` and one
`VectorField()`. Create a separate instance for each pair, even when the two instances use the same
model and settings. To embed several inputs together, combine them into a single source field before
ingestion.
Install the example's dependencies with `pip install lancedb sentence-transformers`. The first run
downloads the model if it is absent from the cache.
This LanceDB Embedded example fills both vector columns when you add articles. The table schema
stores both field pairs so you can use them after reopening the table. For a text vector search on
this table, specify `vector_column_name` to select the column and the embedding function that encodes
the query. With two candidate vector columns, leaving the name out raises an ambiguity error.
<CodeGroup>
<CodeBlock filename="Python" language="python" icon="python">
{PyMultipleEmbeddingColumns}
</CodeBlock>
</CodeGroup>
### Querying multiple embedding columns in TypeScript {#querying-multiple-embedding-columns-in-typescript}
In TypeScript, automatic query embedding currently uses the first embedding function stored in the
table metadata. If a table has multiple embedding definitions and you need to query a specific vector
column, compute the query embedding explicitly and pass the vector to the search builder.
+2
View File
@@ -12,6 +12,8 @@ export const PyManualQueryEmbeddings = "import lancedb\n\ndb = lancedb.connect(\
export const PyManualQuerySearch = "# query_vector is assumed to already be generated by your embedding function\nactual = table.search(query_vector).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n";
export const PyMultipleEmbeddingColumns = "import lancedb\nfrom lancedb.embeddings import get_registry\nfrom lancedb.pydantic import LanceModel\n\nprovider = get_registry().get(\"sentence-transformers\")\ntitle_embedder = provider.create(name=\"all-MiniLM-L6-v2\")\ndescription_embedder = provider.create(name=\"all-MiniLM-L6-v2\")\n\nclass Article(LanceModel):\n title: str = title_embedder.SourceField()\n description: str = description_embedder.SourceField()\n title_vector: list[float] = title_embedder.VectorField()\n description_vector: list[float] = description_embedder.VectorField()\n\ndb = lancedb.connect(\"memory://\")\ntable = db.create_table(\"articles\", schema=Article)\ntable.add(\n [\n {\n \"title\": \"Hiking in the Alps\",\n \"description\": \"A guide to mountain trails\",\n },\n {\"title\": \"Baking sourdough\", \"description\": \"How to feed a starter\"},\n ]\n)\n\ntable = db.open_table(\"articles\")\ntitle_match = (\n table.search(\n \"Alpine hiking\", query_type=\"vector\", vector_column_name=\"title_vector\"\n )\n .limit(1)\n .to_list()[0]\n)\ndescription_match = (\n table.search(\n \"feeding sourdough starter\",\n query_type=\"vector\",\n vector_column_name=\"description_vector\",\n )\n .limit(1)\n .to_list()[0]\n)\nprint(title_match[\"title\"]) # Hiking in the Alps\nprint(description_match[\"title\"]) # Baking sourdough\n";
export const PyOpenaiEmbeddings = "import lancedb\n\ndb = lancedb.connect(\"/tmp/db\")\nfunc = get_registry().get(\"openai\").create(name=\"text-embedding-ada-002\")\n\nclass Words(LanceModel):\n text: str = func.SourceField()\n vector: Vector(func.ndims()) = func.VectorField()\n\ntable = db.create_table(\"words\", schema=Words, mode=\"overwrite\")\ntable.add([{\"text\": \"hello world\"}, {\"text\": \"goodbye world\"}])\n\nquery = \"greetings\"\nactual = table.search(query).limit(1).to_pydantic(Words)[0]\nprint(actual.text)\n";
export const PyRegisterDevice = "import torch\n\nregistry = get_registry()\nif torch.cuda.is_available():\n registry.set_var(\"device\", \"cuda\")\n\nfunc = registry.get(\"huggingface\").create(device=\"$var:device:cpu\")\n";