> ## Documentation Index
> Fetch the complete documentation index at: https://docs.lancedb.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Managing Embeddings

> Use the embedding API in LanceDB -- registry, functions, schemas, and multi-language SDK support.

Modern machine learning models can be trained to convert raw data into embeddings, which are vectors
of floating point numbers. The position of an embedding in vector space captures the semantics of
the data, so vectors that are close to each other are considered similar.

LanceDB provides an embedding function registry in OSS as well as its Enterprise versions
([see below](#embeddings-in-lancedb-enterprise))
that automatically generates vector embeddings during data ingestion. Automatic query-time embedding
generation is available in LanceDB OSS, with SDK-specific query ergonomics. The API abstracts
embedding generation, allowing you to focus on your application logic.

## Embedding Registry

You can get a supported embedding function from the registry, and then use it in your table schema.
Once configured, the embedding function will automatically generate embeddings when you insert data
into the table. Query-time behavior depends on SDK: Python/TypeScript can query with text directly,
while Rust examples typically compute query embeddings explicitly before vector search.

db = lancedb.connect("/tmp/db")
func = get\_registry().get("openai").create(name="text-embedding-ada-002")

class Words(LanceModel):
&#x20;   text: str = func.SourceField()
&#x20;   vector: Vector(func.ndims()) = func.VectorField()

table = db.create\_table("words", schema=Words, mode="overwrite")
table.add(\[\{"text": "hello world"}, \{"text": "goodbye world"}])

query = "greetings"
actual = table.search(query).limit(1).to\_pydantic(Words)\[0]
print(actual.text)


const db = await lancedb.connect(databaseDir);
const func = getRegistry()
&#x20; .get("openai")
&#x20; ?.create(\{ model: "text-embedding-ada-002" }) as EmbeddingFunction;

const wordsSchema = LanceSchema(\{
&#x20; text: func.sourceField(new Utf8()),
&#x20; vector: func.vectorField(),
});
const tbl = await db.createEmptyTable("words", wordsSchema, \{
&#x20; mode: "overwrite",
});
await tbl.add(\[\{ text: "hello world" }, \{ text: "goodbye world" }]);

const query = "greetings";
const actual = (await tbl.search(query).limit(1).toArray())\[0];


use std::\{iter::once, sync::Arc};

use arrow\_array::\{record\_batch, StringArray};
use arrow\_schema::\{DataType, Field, Schema};
use futures::StreamExt;
use lancedb::\{
&#x20;   connect,
&#x20;   embeddings::\{openai::OpenAIEmbeddingFunction, EmbeddingDefinition, EmbeddingFunction},
&#x20;   query::\{ExecutableQuery, QueryBase},
&#x20;   Result,
};

\#\[tokio::main]
async fn main() -> Result\<()> \{
&#x20;   let db = connect("./mydb").execute().await?;
&#x20;   let api\_key = std::env::var("OPENAI\_API\_KEY").expect("OPENAI\_API\_KEY is not set");
&#x20;   let embedding = Arc::new(OpenAIEmbeddingFunction::new\_with\_model(
&#x20;       api\_key,
&#x20;       "text-embedding-3-large",
&#x20;   )?);

&#x20;   db.embedding\_registry().register("openai", embedding.clone())?;

&#x20;   let schema = Arc::new(Schema::new(vec!\[Field::new("text", DataType::Utf8, false)]));
&#x20;   let table = db
&#x20;       .create\_empty\_table("mytable", schema)
&#x20;       .add\_embedding(EmbeddingDefinition::new("text", "openai", Some("vector")))?
&#x20;       .execute()
&#x20;       .await?;

&#x20;   table
&#x20;       .add(record\_batch!(("text", Utf8, \["This is a test.", "Another example."]))?)
&#x20;       .execute()
&#x20;       .await?;

&#x20;   let query = Arc::new(StringArray::from\_iter\_values(once("test example")));
&#x20;   let query\_vector = embedding.compute\_query\_embeddings(query)?;
&#x20;   let mut results = table.vector\_search(query\_vector)?.limit(5).execute().await?;

&#x20;   while let Some(batch) = results.next().await \{
&#x20;       println!("\{:?}", batch?);
&#x20;   }

&#x20;   Ok(())
}


### Using an embedding function

Create an embedding function before you attach it to table or schema metadata. Python and TypeScript fetch
provider implementations from the embedding registry, while Rust constructs the provider embedding function
directly and registers it on the connection before using it in an `EmbeddingDefinition`.

func = get\_registry().get("openai").create(
&#x20;   name="text-embedding-3-small",
&#x20;   max\_retries=7,
)


const func = getRegistry().get("openai")!.create(\{
&#x20; model: "text-embedding-3-small",
});


use std::sync::Arc;

use lancedb::embeddings::openai::OpenAIEmbeddingFunction;

let api\_key = std::env::var("OPENAI\_API\_KEY").expect("OPENAI\_API\_KEY is not set");
let embedding = Arc::new(
&#x20;   OpenAIEmbeddingFunction::new\_with\_model(api\_key, "text-embedding-3-small")
&#x20;       .expect("failed to create OpenAI embedding function"),
);


Provider configuration is SDK-specific, so copy the option names from the provider page for the SDK you use.
For example, the OpenAI model is selected with `name` in Python, `model` in TypeScript, and the model argument
to `OpenAIEmbeddingFunction::new_with_model` in Rust.

| Concept | Python | TypeScript | Rust |
| - | - | - | - |
| Model | `name="text-embedding-3-small"` | `{ model: "text-embedding-3-small" }` | `new_with_model(api_key, "text-embedding-3-small")` |
| Retry count | `max_retries=7` | Provider/client-specific | Provider/client-specific |
| API key | `api_key="..."`, environment variables, or `$var:` | `apiKey: "..."`, environment variables, or `$var:` | Constructor argument or environment variable |
| Device | Provider-specific, for example `device="cuda"` | Provider-specific | Provider-specific |

When ingesting data with an embedding definition, LanceDB only computes the vector column if that
column is missing from the incoming batch or present but entirely null. If you provide any non-null
values in the vector column, LanceDB treats the column as user-supplied and does not backfill the
remaining rows in that batch.

For reusable runtime configuration, the registry also supports `$var:` placeholders in embedding-function config.
This is useful for provider secrets and environment-specific settings in Python and TypeScript.

* Python uses `registry.set_var(...)`.
* TypeScript uses `registry.setVar(...)`.
* You can provide a fallback with `$var:name:default`.
* Sensitive values such as API keys should be passed through registry variables instead of hardcoding them in config.

registry = get\_registry()
registry.set\_var("api\_key", "sk-...")

func = registry.get("openai").create(api\_key="\$var:api\_key")


const registry = getRegistry();
registry.setVar("api\_key", "sk-...");

const func = registry.get("openai")!.create(\{
&#x20; apiKey: "\$var:api\_key",
});


For non-sensitive settings such as inference device selection, you can also use a default fallback:

import torch

registry = get\_registry()
if torch.cuda.is\_available():
&#x20;   registry.set\_var("device", "cuda")

func = registry.get("huggingface").create(device="\$var:device:cpu")


const registry = getRegistry();
registry.setVar("openai\_model", "text-embedding-3-large");

const func = registry.get("openai")!.create(\{
&#x20; model: "\$var:openai\_model:text-embedding-3-small",
});


Find the full list of arguments for each provider in the [integrations](https://docs.lancedb.com/integrations/embedding) section.

## Multiple embedding columns

A single table can include more than one embedding definition when you want to store multiple semantic views
of the same data, or generate embeddings from different source columns. In practice, each embedding definition
maps one source column to one vector column, and the table schema can contain multiple such pairs.

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.

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.

## Embedding model providers

LanceDB supports most popular embedding providers.

### Text embeddings

| Provider | Model ID | Default Model |
| - | - | - |
| OpenAI | `openai` | `text-embedding-ada-002` |
| Sentence Transformers | `sentence-transformers` | `all-MiniLM-L6-v2` |
| Hugging Face | `huggingface` | `colbert-ir/colbertv2.0` |
| Cohere | `cohere` | `embed-english-v3.0` |
| ... | ... | ... |

### Multimodal embedding

| Provider | Model ID | Supported Inputs |
| - | - | - |
| OpenCLIP | `open-clip` | Text, Images |
| ImageBind | `imagebind` | Text, Images, Audio, Video |
| ... | ... | ... |

You can find all supported embedding models in the [integrations](https://docs.lancedb.com/integrations/embedding) section.

## Embeddings in LanceDB Enterprise

Enterprise

In LanceDB Enterprise, embedding generation during data ingestion is client-side and the resulting vectors are
stored on the remote table.

> [!NOTE]
>
> The Enterprise server does not currently generate embeddings from query text on its own. Any automatic
> query-time embedding happens on the client side.

### How string queries are interpreted

For the Python remote client, `table.search("hello")` can take two different paths:

* If the selected vector column has embedding metadata
  (i.e., the table schema stores the source-column, vector-column, and
  embedding-function mapping created from fields like `SourceField()` and
  `VectorField()` during table creation), then the embeddings are computed in the Python client process.
  The client uses the same local LanceDB embedding registry used by OSS tables to
  reconstruct the embedding function from schema metadata, compute the query vector in
  the client process, and send that vector to Enterprise for search.
  ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
  result = table.search("hello").limit(1).to_list()
  # The Python client computes the query embedding locally, then sends a vector search.
  ```
* If the table does not have embedding metadata for that search, `table.search("hello")` in `auto` mode is
  treated as an FTS query instead.
  ```python theme={"theme":{"light":"vitesse-light","dark":"catppuccin-mocha"}}
  result = table.search("hello").limit(5).to_list()
  # In auto mode this is treated as an FTS query, not a vector query.
  ```

If you want explicit vector or hybrid behavior and the client cannot resolve an embedding function from the
table metadata, generate the query embedding yourself and pass the vector directly.

TypeScript has a similar string-query distinction in `auto` mode: if no embedding providers have been
registered in the process, `search("text")` falls back to FTS. Once an embedding provider has been
imported and registered, the client expects table embedding metadata for automatic vector search and
raises an error if the table has none.

The manual query-embedding flow below works across Enterprise SDKs and is an explicit path you can use when you
want full control over query-time behavior.

\# query\_vector is assumed to already be generated by your embedding function
actual = table.search(query\_vector).limit(1).to\_pydantic(Words)\[0]
print(actual.text)


// queryVector is assumed to already be generated by your embedding function
const actual = (await tbl.search(queryVector).limit(1).toArray())\[0];


// query\_vector is assumed to already be generated by your embedding function
let mut results = table.vector\_search(query\_vector)?.limit(5).execute().await?;

while let Some(batch) = results.next().await \{
&#x20;   println!("\{:?}", batch?);
}


## Custom Embedding Functions

You can always implement your own embedding function:

* Python/TypeScript: subclass `TextEmbeddingFunction` (text) or `EmbeddingFunction` (multimodal).
* Rust: implement the `EmbeddingFunction` trait.

from functools import cached\_property

from lancedb.embeddings import TextEmbeddingFunction, register

class MyEmbeddingModel:
&#x20;   def \_\_init\_\_(self, model\_name: str):
&#x20;       self.model\_name = model\_name

&#x20;   def encode(self, texts: list\[str]) -> list\[list\[float]]:
&#x20;       return \[\[1.0, 2.0, 3.0] for \_ in texts]

@register("my-embedder")
class MyTextEmbedder(TextEmbeddingFunction):
&#x20;   model\_name: str = "my-model"

&#x20;   def generate\_embeddings(self, texts: list\[str]) -> list\[list\[float]]:
&#x20;       \# Your embedding logic here
&#x20;       return self.\_model.encode(texts)

&#x20;   def ndims(self) -> int:
&#x20;       \# Return the dimensionality of the embeddings
&#x20;       return len(self.generate\_embeddings(\["test"])\[0])

&#x20;   @cached\_property
&#x20;   def \_model(self) -> MyEmbeddingModel:
&#x20;       \# Initialize your model once
&#x20;       return MyEmbeddingModel(self.model\_name)


const db = await lancedb.connect(databaseDir);

@register("my\_embedding")
class MyEmbeddingFunction extends EmbeddingFunction\<string> \{
&#x20; constructor(optionsRaw = \{}) \{
&#x20;   super();
&#x20;   const options = this.resolveVariables(optionsRaw);
&#x20;   // Initialize using options
&#x20; }
&#x20; ndims() \{
&#x20;   return 3;
&#x20; }
&#x20; protected getSensitiveKeys(): string\[] \{
&#x20;   return \[];
&#x20; }
&#x20; embeddingDataType(): Float \{
&#x20;   return new Float32();
&#x20; }
&#x20; async computeQueryEmbeddings(\_data: string) \{
&#x20;   // This is a placeholder for a real embedding function
&#x20;   return \[1, 2, 3];
&#x20; }
&#x20; async computeSourceEmbeddings(data: string\[]) \{
&#x20;   // This is a placeholder for a real embedding function
&#x20;   return Array.from(\{ length: data.length }).fill(\[
&#x20;     1, 2, 3,
&#x20;   ]) as number\[]\[];
&#x20; }
}

const func = new MyEmbeddingFunction();

const data = \[\{ text: "pepperoni" }, \{ text: "pineapple" }];

// Option 1: manually specify the embedding function
const table = await db.createTable("vectors", data, \{
&#x20; embeddingFunction: \{
&#x20;   function: func,
&#x20;   sourceColumn: "text",
&#x20;   vectorColumn: "vector",
&#x20; },
&#x20; mode: "overwrite",
});

// Option 2: provide the embedding function through a schema

const schema = LanceSchema(\{
&#x20; text: func.sourceField(new Utf8()),
&#x20; vector: func.vectorField(),
});

const table2 = await db.createTable("vectors2", data, \{
&#x20; schema,
&#x20; mode: "overwrite",
});


use std::\{borrow::Cow, sync::Arc};

use arrow\_array::\{Array, FixedSizeListArray, Float32Array};
use arrow\_schema::\{DataType, Field, Schema};
use lancedb::\{
&#x20;   connect,
&#x20;   embeddings::\{EmbeddingDefinition, EmbeddingFunction},
&#x20;   Result,
};

\#\[derive(Debug, Clone)]
struct MyTextEmbedder \{
&#x20;   dim: usize,
}

impl EmbeddingFunction for MyTextEmbedder \{
&#x20;   fn name(\&self) -> \&str \{
&#x20;       "my-embedder"
&#x20;   }

&#x20;   fn source\_type(\&self) -> Result\<Cow\<'\_, DataType>> \{
&#x20;       Ok(Cow::Owned(DataType::Utf8))
&#x20;   }

&#x20;   fn dest\_type(\&self) -> Result\<Cow\<'\_, DataType>> \{
&#x20;       Ok(Cow::Owned(DataType::new\_fixed\_size\_list(
&#x20;           DataType::Float32,
&#x20;           self.dim as i32,
&#x20;           true,
&#x20;       )))
&#x20;   }

&#x20;   fn compute\_source\_embeddings(\&self, source: Arc\<dyn Array>) -> Result\<Arc\<dyn Array>> \{
&#x20;       let values = Arc::new(Float32Array::from(vec!\[1.0f32; source.len() \* self.dim]));
&#x20;       let field = Arc::new(Field::new("item", DataType::Float32, true));
&#x20;       Ok(Arc::new(FixedSizeListArray::new(
&#x20;           field,
&#x20;           self.dim as i32,
&#x20;           values,
&#x20;           None,
&#x20;       )))
&#x20;   }

&#x20;   fn compute\_query\_embeddings(\&self, \_input: Arc\<dyn Array>) -> Result\<Arc\<dyn Array>> \{
&#x20;       unimplemented!()
&#x20;   }
}

\#\[tokio::main]
async fn main() -> Result\<()> \{
&#x20;   let db = connect("./mydb").execute().await?;
&#x20;   db.embedding\_registry()
&#x20;       .register("my-embedder", Arc::new(MyTextEmbedder \{ dim: 3 }))?;

&#x20;   let schema = Arc::new(Schema::new(vec!\[Field::new("text", DataType::Utf8, false)]));
&#x20;   db.create\_empty\_table("mytable", schema)
&#x20;       .add\_embedding(EmbeddingDefinition::new(
&#x20;           "text",
&#x20;           "my-embedder",
&#x20;           Some("vector"),
&#x20;       ))?
&#x20;       .execute()
&#x20;       .await?;

&#x20;   Ok(())
}


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.