Elffuss BraidHub

kikocis/lancedb public

feat: support to create table from record batch iterator (#1593)

Changesetb6ae29ca95a7764e87cdc58ad23ce0b78c90ea831cb1c73e70b99afada6b3905
AuthorBubbleCal <bubble-cal@outlook.com> · 2024-09-06 10:41 +08:00
CommitterGitHub <noreply@github.com> · 2024-09-06 10:41 +08:00
Parentsbbc8a2ecbe2c

Browse the files at this changeset

6 files changed

modified python/python/lancedb/db.py +11 −34
@@ -14,7 +14,6 @@
1414 from __future__ import annotations
1515
1616 import asyncio
17-import inspect
1817 import os
1918 from abc import abstractmethod
2019 from pathlib import Path
@@ -27,8 +26,13 @@
2726 from lancedb.common import data_to_reader, validate_schema
2827
2928 from ._lancedb import connect as lancedb_connect
30-from .pydantic import LanceModel
31-from .table import AsyncTable, LanceTable, Table, _sanitize_data, _table_path
29+from .table import (
30+ AsyncTable,
31+ LanceTable,
32+ Table,
33+ _table_path,
34+ sanitize_create_table,
35+)
3236 from .util import (
3337 fs_from_uri,
3438 get_uri_location,
@@ -37,6 +41,7 @@
3741 )
3842
3943 if TYPE_CHECKING:
44+ from .pydantic import LanceModel
4045 from datetime import timedelta
4146
4247 from ._lancedb import Connection as LanceDbConnection
@@ -722,12 +727,6 @@
722727 ... await db.create_table("table4", make_batches(), schema=schema)
723728 >>> asyncio.run(iterable_example())
724729 """
725- if inspect.isclass(schema) and issubclass(schema, LanceModel):
726- # convert LanceModel to pyarrow schema
727- # note that it's possible this contains
728- # embedding function metadata already
729- schema = schema.to_arrow_schema()
730-
731730 metadata = None
732731
733732 # Defining defaults here and not in function prototype. In the future
@@ -738,31 +737,9 @@
738737 if fill_value is None:
739738 fill_value = 0.0
740739
741- if data is not None:
742- data, schema = _sanitize_data(
743- data,
744- schema,
745- metadata=metadata,
746- on_bad_vectors=on_bad_vectors,
747- fill_value=fill_value,
748- )
749-
750- if schema is None:
751- if data is None:
752- raise ValueError("Either data or schema must be provided")
753- elif hasattr(data, "schema"):
754- schema = data.schema
755- elif isinstance(data, Iterable):
756- if metadata:
757- raise TypeError(
758- (
759- "Persistent embedding functions not yet "
760- "supported for generator data input"
761- )
762- )
763-
764- if metadata:
765- schema = schema.with_metadata(metadata)
740+ data, schema = sanitize_create_table(
741+ data, schema, metadata, on_bad_vectors, fill_value
742+ )
766743 validate_schema(schema)
767744
768745 if exist_ok is None:
modified python/python/lancedb/query.py +1 −1
@@ -852,7 +852,7 @@
852852 )
853853 if len(row_ids) == 0:
854854 empty_schema = pa.schema([pa.field("_score", pa.float32())])
855- return pa.Table.from_pylist([], schema=empty_schema)
855+ return pa.Table.from_batches([], schema=empty_schema)
856856 scores = pa.array(scores)
857857 output_tbl = self._table.to_lance().take(row_ids, columns=self._columns)
858858 output_tbl = output_tbl.append_column("_score", scores)
modified python/python/lancedb/remote/arrow.py +4 −1
@@ -11,12 +11,15 @@
1111 # See the License for the specific language governing permissions and
1212 # limitations under the License.
1313
14+from typing import Iterable, Union
1415 import pyarrow as pa
1516
1617
17-def to_ipc_binary(table: pa.Table) -> bytes:
18+def to_ipc_binary(table: Union[pa.Table, Iterable[pa.RecordBatch]]) -> bytes:
1819 """Serialize a PyArrow Table to IPC binary."""
1920 sink = pa.BufferOutputStream()
21+ if isinstance(table, Iterable):
22+ table = pa.Table.from_batches(table)
2023 with pa.ipc.new_stream(sink, table.schema) as writer:
2124 writer.write_table(table)
2225 return sink.getvalue().to_pybytes()
modified python/python/lancedb/remote/db.py +4 −22
@@ -11,7 +11,6 @@
1111 # See the License for the specific language governing permissions and
1212 # limitations under the License.
1313
14-import inspect
1514 import logging
1615 import uuid
1716 from concurrent.futures import ThreadPoolExecutor
@@ -26,7 +25,7 @@
2625 from ..db import DBConnection
2726 from ..embeddings import EmbeddingFunctionConfig
2827 from ..pydantic import LanceModel
29-from ..table import Table, _sanitize_data
28+from ..table import Table, sanitize_create_table
3029 from ..util import validate_table_name
3130 from .arrow import to_ipc_binary
3231 from .client import ARROW_STREAM_CONTENT_TYPE, RestfulLanceDBClient
@@ -228,8 +227,6 @@
228227
229228 """
230229 validate_table_name(name)
231- if data is None and schema is None:
232- raise ValueError("Either data or schema must be provided.")
233230 if embedding_functions is not None:
234231 logging.warning(
235232 "embedding_functions is not yet supported on LanceDB Cloud."
@@ -239,24 +236,9 @@
239236 if mode is not None:
240237 logging.warning("mode is not yet supported on LanceDB Cloud.")
241238
242- if inspect.isclass(schema) and issubclass(schema, LanceModel):
243- # convert LanceModel to pyarrow schema
244- # note that it's possible this contains
245- # embedding function metadata already
246- schema = schema.to_arrow_schema()
247-
248- if data is not None:
249- data, schema = _sanitize_data(
250- data,
251- schema,
252- metadata=None,
253- on_bad_vectors=on_bad_vectors,
254- fill_value=fill_value,
255- )
256- else:
257- if schema is None:
258- raise ValueError("Either data or schema must be provided")
259- data = pa.Table.from_pylist([], schema=schema)
239+ data, schema = sanitize_create_table(
240+ data, schema, on_bad_vectors=on_bad_vectors, fill_value=fill_value
241+ )
260242
261243 from .table import RemoteTable
262244
modified python/python/lancedb/table.py +62 −33
@@ -117,15 +117,50 @@
117117 data = _sanitize_schema(
118118 data, schema=schema, on_bad_vectors=on_bad_vectors, fill_value=fill_value
119119 )
120+ if schema is None:
121+ schema = data.schema
120122 elif isinstance(data, Iterable):
121123 data = _to_record_batch_generator(
122124 data, schema, metadata, on_bad_vectors, fill_value
123125 )
126+ if schema is None:
127+ data, schema = _generator_to_data_and_schema(data)
128+ if schema is None:
129+ raise ValueError("Cannot infer schema from generator data")
124130 else:
125131 raise TypeError(f"Unsupported data type: {type(data)}")
126132 return data, schema
127133
128134
135+def sanitize_create_table(
136+ data, schema, metadata=None, on_bad_vectors="error", fill_value=0.0
137+):
138+ if inspect.isclass(schema) and issubclass(schema, LanceModel):
139+ # convert LanceModel to pyarrow schema
140+ # note that it's possible this contains
141+ # embedding function metadata already
142+ schema = schema.to_arrow_schema()
143+
144+ if data is not None:
145+ data, schema = _sanitize_data(
146+ data,
147+ schema,
148+ metadata=metadata,
149+ on_bad_vectors=on_bad_vectors,
150+ fill_value=fill_value,
151+ )
152+ if schema is None:
153+ if data is None:
154+ raise ValueError("Either data or schema must be provided")
155+ elif hasattr(data, "schema"):
156+ schema = data.schema
157+
158+ if metadata:
159+ schema = schema.with_metadata(metadata)
160+
161+ return data, schema
162+
163+
129164 def _schema_from_hf(data, schema):
130165 """
131166 Extract pyarrow schema from HuggingFace DatasetDict
@@ -187,8 +222,30 @@
187222 return data
188223
189224
225+def _generator_to_data_and_schema(
226+ data: Iterable,
227+) -> Tuple[Iterable[pa.RecordBatch], pa.Schema]:
228+ def _with_first_generator(first, data):
229+ yield first
230+ yield from data
231+
232+ first = next(data, None)
233+ schema = None
234+ if isinstance(first, pa.RecordBatch):
235+ schema = first.schema
236+ data = _with_first_generator(first, data)
237+ elif isinstance(first, pa.Table):
238+ schema = first.schema
239+ data = _with_first_generator(first.to_batches(), data)
240+ return data, schema
241+
242+
190243 def _to_record_batch_generator(
191- data: Iterable, schema, metadata, on_bad_vectors, fill_value
244+ data: Iterable,
245+ schema,
246+ metadata,
247+ on_bad_vectors,
248+ fill_value,
192249 ):
193250 for batch in data:
194251 # always convert to table because we need to sanitize the data
@@ -1569,12 +1626,6 @@
15691626 The embedding functions to use when creating the table.
15701627 """
15711628 tbl = LanceTable(db, name)
1572- if inspect.isclass(schema) and issubclass(schema, LanceModel):
1573- # convert LanceModel to pyarrow schema
1574- # note that it's possible this contains
1575- # embedding function metadata already
1576- schema = schema.to_arrow_schema()
1577-
15781629 metadata = None
15791630 if embedding_functions is not None:
15801631 # If we passed in embedding functions explicitly
@@ -1583,33 +1634,11 @@
15831634 registry = EmbeddingFunctionRegistry.get_instance()
15841635 metadata = registry.get_table_metadata(embedding_functions)
15851636
1586- if data is not None:
1587- data, schema = _sanitize_data(
1588- data,
1589- schema,
1590- metadata=metadata,
1591- on_bad_vectors=on_bad_vectors,
1592- fill_value=fill_value,
1593- )
1637+ data, schema = sanitize_create_table(
1638+ data, schema, metadata, on_bad_vectors, fill_value
1639+ )
15941640
1595- if schema is None:
1596- if data is None:
1597- raise ValueError("Either data or schema must be provided")
1598- elif hasattr(data, "schema"):
1599- schema = data.schema
1600- elif isinstance(data, Iterable):
1601- if metadata:
1602- raise TypeError(
1603- (
1604- "Persistent embedding functions not yet "
1605- "supported for generator data input"
1606- )
1607- )
1608-
1609- if metadata:
1610- schema = schema.with_metadata(metadata)
1611-
1612- empty = pa.Table.from_pylist([], schema=schema)
1641+ empty = pa.Table.from_batches([], schema=schema)
16131642 try:
16141643 lance.write_dataset(empty, tbl._dataset_uri, schema=schema, mode=mode)
16151644 except OSError as err:
modified python/python/tests/test_db.py +37 −0
@@ -233,6 +233,43 @@
233233 assert tbl.to_pandas().item.tolist() == ["fizz", "buzz"]
234234
235235
236+def test_create_table_from_iterator(tmp_path):
237+ db = lancedb.connect(tmp_path)
238+
239+ def gen_data():
240+ for _ in range(10):
241+ yield pa.RecordBatch.from_arrays(
242+ [
243+ pa.array([[3.1, 4.1]], pa.list_(pa.float32(), 2)),
244+ pa.array(["foo"]),
245+ pa.array([10.0]),
246+ ],
247+ ["vector", "item", "price"],
248+ )
249+
250+ table = db.create_table("test", data=gen_data())
251+ assert table.count_rows() == 10
252+
253+
254+@pytest.mark.asyncio
255+async def test_create_table_from_iterator_async(tmp_path):
256+ db = await lancedb.connect_async(tmp_path)
257+
258+ def gen_data():
259+ for _ in range(10):
260+ yield pa.RecordBatch.from_arrays(
261+ [
262+ pa.array([[3.1, 4.1]], pa.list_(pa.float32(), 2)),
263+ pa.array(["foo"]),
264+ pa.array([10.0]),
265+ ],
266+ ["vector", "item", "price"],
267+ )
268+
269+ table = await db.create_table("test", data=gen_data())
270+ assert await table.count_rows() == 10
271+
272+
236273 def test_create_exist_ok(tmp_path):
237274 db = lancedb.connect(tmp_path)
238275 data = pd.DataFrame(