fix(python): convert dict fields of Pydantic models to Arrow maps (#5363)

This PR adds support for Arrow
[`Map(K,V)`](https://arrow.apache.org/docs/python/generated/pyarrow.map_.html)
type to the Pydantic-Arrow schema converter.
This commit is contained in:
Daniel Gafni
2026-12-03 00:30:12 +00:00
committed by GitHub
parent 03eeb6d1f2
commit b7d83d0362
6 changed files with 507 additions and 13 deletions
+27 -1
View File
@@ -288,6 +288,28 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType:
)
child = args[0]
return _pydantic_list_child_to_arrow(child, field)
elif py_type is dict or get_origin(py_type) is dict:
args = get_args(py_type)
if len(args) != 2:
raise TypeError(
"Converting Pydantic type to Arrow Type: unsupported type "
f"{py_type}. Specify the key and value types, e.g. dict[str, int] "
"instead of a bare dict."
)
key_type, value_type = args
if _unwrap_optional_annotation(key_type) is not None:
raise TypeError(
"Converting Pydantic type to Arrow Type: unsupported type "
f"{py_type}. Map keys cannot be null."
)
# Map values are always nullable in Arrow, so Optional values unwrap.
unwrapped = _unwrap_optional_annotation(value_type)
return pa.map_(
_pydantic_type_to_arrow_type(key_type, field),
_pydantic_type_to_arrow_type(
value_type if unwrapped is None else unwrapped, field
),
)
raise TypeError(
f"Converting Pydantic type to Arrow Type: unsupported type {py_type}."
)
@@ -626,7 +648,11 @@ def _model_value_to_arrow_compatible(value: Any) -> Any:
)
return value
if isinstance(value, dict):
return {k: _model_value_to_arrow_compatible(v) for k, v in value.items()}
# Keys of dict fields, which are stored as maps, need the same conversion.
return {
_model_value_to_arrow_compatible(k): _model_value_to_arrow_compatible(v)
for k, v in value.items()
}
if isinstance(value, (list, tuple)) and value:
# Skip lists of plain scalars, such as vectors, without walking them.
if isinstance(value[0], (int, float, str, bytes)):
+43 -3
View File
@@ -51,7 +51,12 @@ from .expr import Expr
from .rerankers.base import Reranker
from .rerankers.rrf import RRFReranker
from .rerankers.util import check_reranker_result
from .schema import blob_column_paths, is_blob_like_field, schema_has_blob_field
from .schema import (
blob_column_paths,
is_blob_like_field,
schema_has_blob_field,
type_contains_map,
)
from .util import (
_validate_query_vector,
add_note,
@@ -125,6 +130,41 @@ def _has_alias_value(alias: Any, row: dict) -> bool:
return isinstance(alias, str) and alias in row
def _maps_to_dicts(value: Any, arrow_type: pa.DataType) -> Any:
"""Turn the maps in `value`, which Arrow returns as key-value pairs, into dicts."""
if value is None:
return None
if pa.types.is_map(arrow_type):
return {
_maps_to_dicts(key, arrow_type.key_type): _maps_to_dicts(
item, arrow_type.item_type
)
for key, item in value
}
if pa.types.is_struct(arrow_type):
return {
field.name: _maps_to_dicts(value[field.name], field.type)
for field in arrow_type
}
if (
pa.types.is_list(arrow_type)
or pa.types.is_large_list(arrow_type)
or pa.types.is_fixed_size_list(arrow_type)
):
return [_maps_to_dicts(item, arrow_type.value_type) for item in value]
return value
def _table_to_rows(table: pa.Table) -> List[dict]:
"""Rows of `table` as dicts, with map values as dicts as pydantic expects."""
rows = table.to_pylist()
map_fields = [field for field in table.schema if type_contains_map(field.type)]
for row in rows:
for field in map_fields:
row[field.name] = _maps_to_dicts(row[field.name], field.type)
return rows
def _rows_to_models(model: type[T], rows: List[dict]) -> List[T]:
"""Build ``model`` instances from result rows.
@@ -1900,7 +1940,7 @@ class LanceQueryBuilder(ABC):
-------
List[LanceModel]
"""
return _rows_to_models(model, self.to_arrow(timeout=timeout).to_pylist())
return _rows_to_models(model, _table_to_rows(self.to_arrow(timeout=timeout)))
def to_polars(self, *, timeout: Optional[timedelta] = None) -> "pl.DataFrame":
"""
@@ -5365,7 +5405,7 @@ class AsyncQueryBase(object):
list[LanceModel]
"""
return _rows_to_models(
model, (await self.to_arrow(timeout=timeout)).to_pylist()
model, _table_to_rows(await self.to_arrow(timeout=timeout))
)
async def explain_plan(self, verbose: Optional[bool] = False):
+15
View File
@@ -218,6 +218,21 @@ def row_addressable_blob_v2_paths(schema: pa.Schema) -> list[str]:
]
def type_contains_map(arrow_type: pa.DataType) -> bool:
"""Whether `arrow_type` is a map or has a map in a struct field or list item."""
if pa.types.is_map(arrow_type):
return True
if pa.types.is_struct(arrow_type):
return any(type_contains_map(field.type) for field in arrow_type)
if (
pa.types.is_list(arrow_type)
or pa.types.is_large_list(arrow_type)
or pa.types.is_fixed_size_list(arrow_type)
):
return type_contains_map(arrow_type.value_type)
return False
def schema_has_blob_field(schema: pa.Schema) -> bool:
return bool(blob_column_paths(schema))
+132 -8
View File
@@ -105,7 +105,7 @@ from .functions import (
RefreshColumnResult as RefreshColumnJobResult,
)
from .merge import LanceMergeInsertBuilder
from .pydantic import LanceModel, model_to_dict
from .pydantic import LanceModel, _model_value_to_arrow_compatible, model_to_dict
from .query import (
FullTextOperator,
AnalyzePlanDistributedMetrics,
@@ -139,6 +139,7 @@ from .schema import (
is_blob_v2_field,
row_addressable_blob_v2_paths,
schema_has_blob_field,
type_contains_map,
)
from .resources import _resource_options
@@ -588,6 +589,129 @@ def _blob_input_to_arrow(data: Any, schema: Optional[pa.Schema]) -> Optional[pa.
return table
def _split_map_values(data: Any, schema: Optional[pa.Schema]) -> Tuple[Any, dict]:
"""Take the values of map fields out of Python rows or a pandas DataFrame.
Arrow infers a dict as a struct, which cannot be cast to a map, and fails on
dicts with non-string keys. The values are converted with the target type
instead, by `_set_map_columns`.
"""
if schema is None:
return data, {}
if isinstance(data, list):
names = [
field.name
for field in schema
if type_contains_map(field.type)
and any(isinstance(row, dict) and field.name in row for row in data)
]
if not names:
return data, {}
values = {name: [row.get(name) for row in data] for name in names}
return [{**row, **{name: None for name in names}} for row in data], values
names = [
field.name
for field in schema
if type_contains_map(field.type) and field.name in data.columns
]
if not names:
return data, {}
values = {
name: [
None
if value is pd.NA or isinstance(value, float) and np.isnan(value)
else value
for value in data[name]
]
for name in names
}
return data.assign(**{name: None for name in names}), values
def _map_input_type(target_type: pa.DataType, values: list) -> pa.DataType:
"""The type of `values` with the map and struct layout of `target_type`.
Other types are inferred from the values, so that `_cast_to_target_schema`
checks and encodes them as for any other input. Map keys take the target key
type after a checked cast, because PyArrow 16 cannot cast map keys.
"""
if not type_contains_map(target_type):
return pa.array(values).type
present = [value for value in values if value is not None]
if pa.types.is_map(target_type):
pairs = [
pair
for value in present
for pair in (value.items() if isinstance(value, dict) else value)
]
pa.array([key for key, _ in pairs]).cast(target_type.key_type)
return pa.map_(
target_type.key_type,
_map_input_type(target_type.item_type, [item for _, item in pairs]),
)
if pa.types.is_struct(target_type):
types = {field.name: field.type for field in target_type}
names = list(types)
names += sorted({key for value in present for key in value} - set(names))
return pa.struct(
[
(
name,
_map_input_type(
types.get(name, pa.null()),
[value.get(name) for value in present],
),
)
for name in names
]
)
return pa.list_(
_map_input_type(
target_type.value_type, [item for value in present for item in value]
)
)
def _set_map_columns(table: pa.Table, values: dict, schema: pa.Schema) -> pa.Table:
for name, column_values in values.items():
target_type = schema.field(name).type
# The same conversion as for model rows, which rejects keys and values that
# Arrow cannot store losslessly, such as timezone-aware times.
column_values = [_model_value_to_arrow_compatible(v) for v in column_values]
input_type = _map_input_type(target_type, column_values)
table = table.set_column(
table.schema.get_field_index(name),
pa.field(name, input_type),
pa.array(column_values, type=input_type),
)
return table
def _rows_to_arrow(data: Any, schema: Optional[pa.Schema]) -> Optional[pa.Table]:
"""Convert Python rows or a pandas DataFrame whose blob or map fields need the
target schema.
Returns None when no column needs it, so the caller can infer every type.
"""
is_rows = isinstance(data, list) and data and isinstance(data[0], dict)
is_frame = _check_for_pandas(data) and isinstance(data, pd.DataFrame)
if not (is_rows or is_frame):
return _blob_input_to_arrow(data, schema)
data, map_values = _split_map_values(data, schema)
table = _blob_input_to_arrow(data, schema)
if not map_values:
return table
if table is None:
table = (
pa.Table.from_pylist(data)
if is_rows
else pa.Table.from_pandas(
data, preserve_index=False
).replace_schema_metadata(None)
)
return _set_map_columns(table, map_values, schema)
def _into_pyarrow_reader(
data, schema: Optional[pa.Schema] = None
) -> pa.RecordBatchReader:
@@ -630,12 +754,12 @@ def _into_pyarrow_reader(
return pa.Table.from_batches(data).to_reader()
else:
data = _serialize_json_values(data, schema)
table = _blob_input_to_arrow(data, schema)
table = _rows_to_arrow(data, schema)
return (
table if table is not None else pa.Table.from_pylist(data)
).to_reader()
elif _check_for_pandas(data) and isinstance(data, pd.DataFrame):
table = _blob_input_to_arrow(data, schema)
table = _rows_to_arrow(data, schema)
if table is None:
table = pa.Table.from_pandas(data, preserve_index=False)
# Do not serialize Pandas metadata
@@ -716,9 +840,9 @@ async def _prepare_add_data(
fill_value: Optional[float],
) -> Scannable:
data = _serialize_json_values(data, schema)
blob_table = _blob_input_to_arrow(data, schema)
if blob_table is not None:
data = blob_table
typed_table = _rows_to_arrow(data, schema)
if typed_table is not None:
data = typed_table
if on_bad_vectors is None:
on_bad_vectors = "error"
if fill_value is None:
@@ -1373,8 +1497,8 @@ def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field:
if pa.types.is_struct(field.type):
new_type = pa.struct(
_align_field_types(
field.type.fields,
target_field.type.fields,
list(field.type),
list(target_field.type),
)
)
else:
+289 -1
View File
@@ -4,7 +4,7 @@
import json
from datetime import date, datetime, time, timedelta, timezone
from enum import Enum
from typing import List, Literal, Optional, Tuple
from typing import Dict, List, Literal, Optional, Tuple
import pyarrow as pa
import pydantic
@@ -222,6 +222,294 @@ def test_homogeneous_tuples_map_to_lists():
assert schema.field("many").type == pa.list_(pa.float64())
def test_dicts_map_to_maps():
class Point(pydantic.BaseModel):
x: int
y: int
class TestModel(pydantic.BaseModel):
tags: dict[str, str]
legacy_tags: Dict[str, str]
counts: dict[str, Optional[int]]
by_id: dict[int, str]
by_day: dict[date, float]
lists: Optional[dict[str, List[float]]] = None
nested: dict[str, dict[str, int]]
points: dict[str, Optional[Point]]
vectors: dict[str, Vector(2)]
schema = pydantic_to_schema(TestModel)
point = pa.struct(
[pa.field("x", pa.int64(), False), pa.field("y", pa.int64(), False)]
)
assert schema.field("tags").type == pa.map_(pa.utf8(), pa.utf8())
assert not schema.field("tags").nullable
assert schema.field("legacy_tags").type == pa.map_(pa.utf8(), pa.utf8())
assert schema.field("counts").type == pa.map_(pa.utf8(), pa.int64())
assert schema.field("by_id").type == pa.map_(pa.int64(), pa.utf8())
assert schema.field("by_day").type == pa.map_(pa.date32(), pa.float64())
assert schema.field("lists").type == pa.map_(pa.utf8(), pa.list_(pa.float64()))
assert schema.field("lists").nullable
assert schema.field("nested").type == pa.map_(
pa.utf8(), pa.map_(pa.utf8(), pa.int64())
)
assert schema.field("points").type == pa.map_(pa.utf8(), point)
assert schema.field("vectors").type == pa.map_(pa.utf8(), pa.list_(pa.float32(), 2))
def test_dict_round_trip(tmp_path):
import lancedb
class Point(pydantic.BaseModel):
x: int
y: int
class Row(LanceModel):
id: int
tags: dict[str, str]
counts: Optional[dict[int, Optional[int]]] = None
points: dict[str, Optional[Point]] = {}
rows = [
Row(
id=1,
tags={"a": "x", "b": "y"},
counts={1: 1, 2: None},
points={"p": Point(x=1, y=2), "q": None},
),
Row(id=2, tags={}),
]
table = lancedb.connect(tmp_path).create_table("dicts", rows, schema=Row)
assert table.schema == Row.to_arrow_schema()
assert table.search().to_arrow().to_pylist() == [
{
"id": 1,
"tags": [("a", "x"), ("b", "y")],
"counts": [(1, 1), (2, None)],
"points": [("p", {"x": 1, "y": 2}), ("q", None)],
},
{"id": 2, "tags": [], "counts": None, "points": []},
]
@pytest.mark.parametrize("bare_dict", [dict, Dict])
def test_bare_dict_raises_type_error(bare_dict):
class TestModel(pydantic.BaseModel):
tags: bare_dict
with pytest.raises(TypeError, match="key and value types"):
pydantic_to_schema(TestModel)
class _Point(pydantic.BaseModel):
x: int
y: int
class _DictRow(LanceModel):
id: int
tags: dict[str, str]
nested: dict[str, dict[str, int]] = {}
points: list[dict[str, _Point]] = []
_DICT_ROWS = [
_DictRow(
id=1,
tags={"a": "x"},
nested={"n": {"m": 1}},
points=[{"p": _Point(x=1, y=2)}],
),
_DictRow(id=2, tags={}),
]
def test_dict_to_pydantic_round_trip(mem_db):
table = mem_db.create_table("dicts", _DICT_ROWS, schema=_DictRow)
assert table.search().to_pydantic(_DictRow) == _DICT_ROWS
@pytest.mark.asyncio
async def test_dict_to_pydantic_round_trip_async(mem_db_async):
table = await mem_db_async.create_table("dicts", _DICT_ROWS, schema=_DictRow)
assert await table.query().to_pydantic(_DictRow) == _DICT_ROWS
class _DictInputRow(LanceModel):
id: int
tags: dict[str, str]
counts: dict[int, int] = {}
point: Optional[_Point] = None
labels: Optional[dict[str, list[str]]] = None
@pytest.mark.parametrize("input_type", ["rows", "pandas"])
@pytest.mark.parametrize("operation", ["create", "add"])
def test_dict_rows_write_to_map_columns(mem_db, operation, input_type):
rows = [
{
"id": 1,
"tags": {"a": "x"},
"counts": {1: 2},
"point": None,
"labels": {"l": ["m"]},
},
{"id": 2, "tags": {}, "counts": {}, "point": None, "labels": None},
]
if input_type == "pandas":
pd = pytest.importorskip("pandas")
data = pd.DataFrame(rows)
else:
data = rows
if operation == "create":
table = mem_db.create_table("dicts", data, schema=_DictInputRow)
else:
table = mem_db.create_table("dicts", schema=_DictInputRow)
table.add(data)
# Nullability is not compared: tables created from dict rows are nullable.
assert [(field.name, field.type) for field in table.schema] == [
(field.name, field.type) for field in _DictInputRow.to_arrow_schema()
]
assert sorted(table.search().to_pydantic(_DictInputRow), key=lambda r: r.id) == [
_DictInputRow(id=1, tags={"a": "x"}, counts={1: 2}, labels={"l": ["m"]}),
_DictInputRow(id=2, tags={}, counts={}),
]
_QUANTITIES_SCHEMA = pa.schema(
[
(
"info",
pa.struct(
[
("tags", pa.map_(pa.int64(), pa.string())),
("quantity", pa.int64()),
]
),
)
]
)
@pytest.mark.parametrize("input_type", ["rows", "pandas"])
@pytest.mark.parametrize(
"info",
[{"tags": None, "quantity": 2.7}, {"tags": {1.5: "a", 1.8: "b"}, "quantity": 1}],
ids=["sibling", "key"],
)
def test_fractional_values_next_to_maps_are_rejected(mem_db, input_type, info):
rows = [{"info": info}]
if input_type == "pandas":
pd = pytest.importorskip("pandas")
data = pd.DataFrame(rows)
else:
data = rows
with pytest.raises((RuntimeError, pa.ArrowInvalid), match="truncated"):
mem_db.create_table("quantities", data, schema=_QUANTITIES_SCHEMA)
@pytest.mark.skipif(not hasattr(pa, "json_"), reason="requires PyArrow JSON type")
@pytest.mark.parametrize("input_type", ["rows", "pandas"])
def test_json_next_to_maps_is_encoded(tmp_path, input_type):
import lancedb
schema = pa.schema(
[
("id", pa.int64()),
(
"info",
pa.struct(
[
("tags", pa.map_(pa.string(), pa.string())),
("value", pa.json_()),
]
),
),
]
)
table = lancedb.connect(tmp_path).create_table(
"json_maps",
schema=schema,
storage_options={"new_table_data_storage_version": "2.2"},
)
rows = [{"id": 1, "info": {"tags": None, "value": '{"x": 1}'}}]
if input_type == "pandas":
pd = pytest.importorskip("pandas")
table.add(pd.DataFrame(rows))
else:
table.add(rows)
result = table.search().where("json_extract(info.value, '$.x') = '1'").to_arrow()
assert result["id"].to_pylist() == [1]
class _TimeKeyRow(LanceModel):
id: int
values: dict[time, str] = {}
nested: dict[str, dict[time, str]] = {}
@pytest.mark.parametrize("input_type", ["rows", "pandas"])
@pytest.mark.parametrize("operation", ["create", "add"])
@pytest.mark.parametrize("column", ["values", "nested"])
def test_timezone_aware_time_dict_keys_in_rows_are_rejected(
mem_db, operation, input_type, column
):
keys = {
time(12, tzinfo=timezone.utc): "utc",
time(12, tzinfo=timezone(timedelta(hours=1))): "plus1",
}
rows = [
{
"id": 1,
"values": keys if column == "values" else {},
"nested": {"n": keys} if column == "nested" else {},
}
]
if input_type == "pandas":
pd = pytest.importorskip("pandas")
data = pd.DataFrame(rows)
else:
data = rows
with pytest.raises(ValueError, match="timezone-naive"):
if operation == "create":
mem_db.create_table("times", data, schema=_TimeKeyRow)
else:
mem_db.create_table("times", schema=_TimeKeyRow).add(data)
def test_timezone_aware_time_dict_keys_are_rejected(tmp_path):
import lancedb
class Row(LanceModel):
values: dict[time, str]
row = Row(
values={
time(12, tzinfo=timezone.utc): "utc",
time(12, tzinfo=timezone(timedelta(hours=1))): "plus1",
}
)
with pytest.raises(ValueError, match="timezone-naive"):
lancedb.connect(tmp_path).create_table("times", [row], schema=Row)
def test_optional_dict_keys_raise_type_error():
class TestModel(pydantic.BaseModel):
tags: dict[Optional[str], int]
with pytest.raises(TypeError, match="Map keys cannot be null"):
pydantic_to_schema(TestModel)
def test_nested_struct_list_optional():
class SplitInfo(pydantic.BaseModel):
start_frame: int