Files
lancedb/docs/web/integrations/data/pydantic.mdx
T
Christopher Krah c0d46c31ba fix(python): map a Literal with None to a nullable field (#4927)
`pydantic_to_schema` raises on `Literal["a", "b", None]`, a field
pydantic accepts with `None`. [PEP
586](https://peps.python.org/pep-0586/#legal-parameters-for-literal-at-type-check-time)
reads it as `Union[Literal["a", "b"], None]`, the same type as
`Optional[Literal["a", "b"]]`, which #4678 maps to a nullable `utf8`.
The `None` is the optional part, not a second value type, so #4678's
rule that `Literal["a", 1]` raises does not cover it. The Literal branch
counted `NoneType` anyway and raised "All values of a Literal must have
the same type".

Before, on `1157a07`:

```
$ python probe.py
Optional[Literal]: pyarrow.Field<kind: string>
pydantic accepts None: kind=None
Literal[..., None]: TypeError: Converting Pydantic type to Arrow Type: unsupported type typing.Literal['a', 'b', None]. All values of a Literal must have the same type.
```

After, the last line prints `pyarrow.Field<kind: string>`, nullable. No
issue exists for this.

<details><summary>probe.py</summary>

```python
from typing import Literal, Optional
from lancedb.pydantic import LanceModel, pydantic_to_schema

class Opt(LanceModel):
    kind: Optional[Literal["a", "b"]] = None

class Lit(LanceModel):
    kind: Literal["a", "b", None] = None

print("Optional[Literal]:", pydantic_to_schema(Opt).field("kind"))
print("pydantic accepts None:", Lit(kind=None))
try:
    print("Literal[..., None]:", pydantic_to_schema(Lit).field("kind"))
except TypeError as e:
    print("Literal[..., None]: TypeError:", e)
```

</details>

The fix has two halves, and each test fails without one of them.
`_unwrap_optional_annotation` turns `Literal["a", None]` into
`Literal["a"]`, so the field and a list item become nullable. The
Literal branch skips `None` when it collects value types, so
`Optional[Literal["a", None]]` maps too. A mixed `Literal["a", 1, None]`
still raises, and so does a bare `Literal[None]`.

### Verification

```
# Python 3.12, lancedb 0.42.0b9 wheel from pypi.fury.io (the version at 1157a07), its _lancedb.abi3.so in the tree
$ PYTHONPATH=. python -m pytest -q -p no:cacheprovider tests/test_pydantic.py
this branch:                         87 passed
pydantic.py reverted, tests kept:    2 failed, 85 passed   (TypeError: ... must have the same type)
None kept in the value types only:   1 failed, 86 passed
unwrap change reverted only:         2 failed, 85 passed   (status not nullable; the write fails)
$ PYTHONPATH=. python -m pytest -q -p no:cacheprovider tests/test_pydantic.py tests/test_table.py tests/test_db.py
1157a07:      8 failed, 650 passed, 17 skipped
this branch:  8 failed, 652 passed, 17 skipped   # the same 8 in test_table.py (blob, merge, compact, namespace) on both
$ ruff format --check <both files> && ruff check <both files>      # ruff 0.9.9, as CI pins it
2 files already formatted
All checks passed!
# not run: the Rust build, the full suite; pyright's include list leaves out pydantic.py
```

@Xuanwo, you merged #4678. I left a bare `Literal[None]` raising, since
a column that can only hold null has no value type to store. Does that
match how you want it?

---------

Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com>
2026-11-30 19:16:26 +08:00

94 lines
3.6 KiB
Plaintext

---
title: "Pydantic"
sidebarTitle: "Pydantic"
availability:
embedded: available
enterprise: available
---
import {
PyFrameworksPydanticBaseExample,
PyFrameworksPydanticBaseModel,
PyFrameworksPydanticImports,
PyFrameworksPydanticSetUrl,
PyFrameworksPydanticTypeConversion,
PyFrameworksPydanticVectorField,
} from '/snippets/integrations.mdx';
[Pydantic](https://docs.pydantic.dev/latest/) is a data validation library in Python.
LanceDB integrates with Pydantic for schema inference, data ingestion, and query result casting.
Using `lancedb.pydantic.LanceModel`, users can seamlessly
integrate Pydantic with the rest of the LanceDB APIs.
First, import the necessary LanceDB and Pydantic modules:
<CodeBlock filename="Python" language="Python" icon="python">
{PyFrameworksPydanticImports}
</CodeBlock>
Next, define your Pydantic model by inheriting from `LanceModel` and specifying your fields including a vector field:
<CodeBlock filename="Python" language="Python" icon="python">
{PyFrameworksPydanticBaseModel}
</CodeBlock>
Set the database connection URL:
<CodeBlock filename="Python" language="Python" icon="python">
{PyFrameworksPydanticSetUrl}
</CodeBlock>
Now you can create a table, add data, and perform vector search operations:
<CodeBlock filename="Python" language="Python" icon="python">
{PyFrameworksPydanticBaseExample}
</CodeBlock>
## Vector Field {#vector-field}
LanceDB provides a `lancedb.pydantic.Vector` method to define a
vector Field in a Pydantic Model.
<CodeBlock filename="Python" language="Python" icon="python">
{PyFrameworksPydanticVectorField}
</CodeBlock>
This example demonstrates how LanceDB automatically converts Pydantic field types to their corresponding Apache Arrow data types. The `pydantic_to_schema()` function takes a Pydantic model and generates an Arrow schema where:
- `int` fields become `pa.int64()` (64-bit integers)
- `str` fields become `pa.utf8()` (UTF-8 encoded strings)
- `Vector(768)` becomes `pa.list_(pa.float32(), 768)` (fixed-size list of 768 float32 values)
- The `False` parameter indicates that the fields are not nullable
## Type Conversion {#type-conversion}
LanceDB automatically convert Pydantic fields to
[Apache Arrow DataType](https://arrow.apache.org/docs/python/generated/pyarrow.DataType.html#pyarrow.DataType).
Current supported type conversions:
| Pydantic Field Type | PyArrow Data Type |
| ------------------- | ----------------- |
| `int` | `pyarrow.int64` |
| `float` | `pyarrow.float64` |
| `bool` | `pyarrow.bool` |
| `str` | `pyarrow.utf8()` |
| `list` | `pyarrow.List` |
| `BaseModel` | `pyarrow.Struct` |
| `Vector(n)` | `pyarrow.FixedSizeList(float32, n)` |
| `Literal["a", "b"]` | the Arrow type of its values, here `pyarrow.utf8()`; every value must have the same type |
| `Literal["a", None]` | the same type, nullable, like `Optional[Literal["a"]]` |
LanceDB supports to create Apache Arrow Schema from a
`pydantic.BaseModel`
via `lancedb.pydantic.pydantic_to_schema` method.
<CodeBlock filename="Python" language="Python" icon="python">
{PyFrameworksPydanticTypeConversion}
</CodeBlock>
This example shows a more complex Pydantic model with various field types and demonstrates how LanceDB handles:
- Basic types: `int` and `str` fields
- Vector fields: `Vector(1536)` creates a fixed-size list of 1536 float32 values
- List fields: `List[int]` becomes a variable-length list of int64 values
- Schema generation: The `pydantic_to_schema()` function automatically converts all these types to their Arrow equivalents