diff --git a/docs/web-tests/py/test_embedding.py b/docs/web-tests/py/test_embedding.py index eed12ba81..1134fd600 100644 --- a/docs/web-tests/py/test_embedding.py +++ b/docs/web-tests/py/test_embedding.py @@ -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 diff --git a/docs/web/embedding/index.mdx b/docs/web/embedding/index.mdx index 30fbc5aa4..44210a61e 100644 --- a/docs/web/embedding/index.mdx +++ b/docs/web/embedding/index.mdx @@ -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. + + + + {PyMultipleEmbeddingColumns} + + + +### 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. diff --git a/docs/web/snippets/embedding.mdx b/docs/web/snippets/embedding.mdx index b7971a0f7..f47a5bc5f 100644 --- a/docs/web/snippets/embedding.mdx +++ b/docs/web/snippets/embedding.mdx @@ -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";