Changesets · Branches · Tags · Compare
| Changeset | b6ae29ca95a7764e87cdc58ad23ce0b78c90ea831cb1c73e70b99afada6b3905 |
|---|---|
| Author | BubbleCal <bubble-cal@outlook.com> · 2024-09-06 10:41 +08:00 |
| Committer | GitHub <noreply@github.com> · 2024-09-06 10:41 +08:00 |
| Parents | bbc8a2ecbe2c |
6 files changed
modified python/python/lancedb/db.py +11 −34
| @@ -14,7 +14,6 @@ | ||
| 14 | 14 | from __future__ import annotations |
| 15 | 15 | |
| 16 | 16 | import asyncio |
| 17 | -import inspect | |
| 18 | 17 | import os |
| 19 | 18 | from abc import abstractmethod |
| 20 | 19 | from pathlib import Path |
| @@ -27,8 +26,13 @@ | ||
| 27 | 26 | from lancedb.common import data_to_reader, validate_schema |
| 28 | 27 | |
| 29 | 28 | 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 | +) | |
| 32 | 36 | from .util import ( |
| 33 | 37 | fs_from_uri, |
| 34 | 38 | get_uri_location, |
| @@ -37,6 +41,7 @@ | ||
| 37 | 41 | ) |
| 38 | 42 | |
| 39 | 43 | if TYPE_CHECKING: |
| 44 | + from .pydantic import LanceModel | |
| 40 | 45 | from datetime import timedelta |
| 41 | 46 | |
| 42 | 47 | from ._lancedb import Connection as LanceDbConnection |
| @@ -722,12 +727,6 @@ | ||
| 722 | 727 | ... await db.create_table("table4", make_batches(), schema=schema) |
| 723 | 728 | >>> asyncio.run(iterable_example()) |
| 724 | 729 | """ |
| 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 | - | |
| 731 | 730 | metadata = None |
| 732 | 731 | |
| 733 | 732 | # Defining defaults here and not in function prototype. In the future |
| @@ -738,31 +737,9 @@ | ||
| 738 | 737 | if fill_value is None: |
| 739 | 738 | fill_value = 0.0 |
| 740 | 739 | |
| 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 | + ) | |
| 766 | 743 | validate_schema(schema) |
| 767 | 744 | |
| 768 | 745 | if exist_ok is None: |
modified python/python/lancedb/query.py +1 −1
| @@ -852,7 +852,7 @@ | ||
| 852 | 852 | ) |
| 853 | 853 | if len(row_ids) == 0: |
| 854 | 854 | 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) | |
| 856 | 856 | scores = pa.array(scores) |
| 857 | 857 | output_tbl = self._table.to_lance().take(row_ids, columns=self._columns) |
| 858 | 858 | output_tbl = output_tbl.append_column("_score", scores) |
modified python/python/lancedb/remote/arrow.py +4 −1
| @@ -11,12 +11,15 @@ | ||
| 11 | 11 | # See the License for the specific language governing permissions and |
| 12 | 12 | # limitations under the License. |
| 13 | 13 | |
| 14 | +from typing import Iterable, Union | |
| 14 | 15 | import pyarrow as pa |
| 15 | 16 | |
| 16 | 17 | |
| 17 | -def to_ipc_binary(table: pa.Table) -> bytes: | |
| 18 | +def to_ipc_binary(table: Union[pa.Table, Iterable[pa.RecordBatch]]) -> bytes: | |
| 18 | 19 | """Serialize a PyArrow Table to IPC binary.""" |
| 19 | 20 | sink = pa.BufferOutputStream() |
| 21 | + if isinstance(table, Iterable): | |
| 22 | + table = pa.Table.from_batches(table) | |
| 20 | 23 | with pa.ipc.new_stream(sink, table.schema) as writer: |
| 21 | 24 | writer.write_table(table) |
| 22 | 25 | return sink.getvalue().to_pybytes() |
modified python/python/lancedb/remote/db.py +4 −22
| @@ -11,7 +11,6 @@ | ||
| 11 | 11 | # See the License for the specific language governing permissions and |
| 12 | 12 | # limitations under the License. |
| 13 | 13 | |
| 14 | -import inspect | |
| 15 | 14 | import logging |
| 16 | 15 | import uuid |
| 17 | 16 | from concurrent.futures import ThreadPoolExecutor |
| @@ -26,7 +25,7 @@ | ||
| 26 | 25 | from ..db import DBConnection |
| 27 | 26 | from ..embeddings import EmbeddingFunctionConfig |
| 28 | 27 | from ..pydantic import LanceModel |
| 29 | -from ..table import Table, _sanitize_data | |
| 28 | +from ..table import Table, sanitize_create_table | |
| 30 | 29 | from ..util import validate_table_name |
| 31 | 30 | from .arrow import to_ipc_binary |
| 32 | 31 | from .client import ARROW_STREAM_CONTENT_TYPE, RestfulLanceDBClient |
| @@ -228,8 +227,6 @@ | ||
| 228 | 227 | |
| 229 | 228 | """ |
| 230 | 229 | validate_table_name(name) |
| 231 | - if data is None and schema is None: | |
| 232 | - raise ValueError("Either data or schema must be provided.") | |
| 233 | 230 | if embedding_functions is not None: |
| 234 | 231 | logging.warning( |
| 235 | 232 | "embedding_functions is not yet supported on LanceDB Cloud." |
| @@ -239,24 +236,9 @@ | ||
| 239 | 236 | if mode is not None: |
| 240 | 237 | logging.warning("mode is not yet supported on LanceDB Cloud.") |
| 241 | 238 | |
| 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 | + ) | |
| 260 | 242 | |
| 261 | 243 | from .table import RemoteTable |
| 262 | 244 |
modified python/python/lancedb/table.py +62 −33
| @@ -117,15 +117,50 @@ | ||
| 117 | 117 | data = _sanitize_schema( |
| 118 | 118 | data, schema=schema, on_bad_vectors=on_bad_vectors, fill_value=fill_value |
| 119 | 119 | ) |
| 120 | + if schema is None: | |
| 121 | + schema = data.schema | |
| 120 | 122 | elif isinstance(data, Iterable): |
| 121 | 123 | data = _to_record_batch_generator( |
| 122 | 124 | data, schema, metadata, on_bad_vectors, fill_value |
| 123 | 125 | ) |
| 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") | |
| 124 | 130 | else: |
| 125 | 131 | raise TypeError(f"Unsupported data type: {type(data)}") |
| 126 | 132 | return data, schema |
| 127 | 133 | |
| 128 | 134 | |
| 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 | + | |
| 129 | 164 | def _schema_from_hf(data, schema): |
| 130 | 165 | """ |
| 131 | 166 | Extract pyarrow schema from HuggingFace DatasetDict |
| @@ -187,8 +222,30 @@ | ||
| 187 | 222 | return data |
| 188 | 223 | |
| 189 | 224 | |
| 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 | + | |
| 190 | 243 | 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, | |
| 192 | 249 | ): |
| 193 | 250 | for batch in data: |
| 194 | 251 | # always convert to table because we need to sanitize the data |
| @@ -1569,12 +1626,6 @@ | ||
| 1569 | 1626 | The embedding functions to use when creating the table. |
| 1570 | 1627 | """ |
| 1571 | 1628 | 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 | - | |
| 1578 | 1629 | metadata = None |
| 1579 | 1630 | if embedding_functions is not None: |
| 1580 | 1631 | # If we passed in embedding functions explicitly |
| @@ -1583,33 +1634,11 @@ | ||
| 1583 | 1634 | registry = EmbeddingFunctionRegistry.get_instance() |
| 1584 | 1635 | metadata = registry.get_table_metadata(embedding_functions) |
| 1585 | 1636 | |
| 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 | + ) | |
| 1594 | 1640 | |
| 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) | |
| 1613 | 1642 | try: |
| 1614 | 1643 | lance.write_dataset(empty, tbl._dataset_uri, schema=schema, mode=mode) |
| 1615 | 1644 | except OSError as err: |
modified python/python/tests/test_db.py +37 −0
| @@ -233,6 +233,43 @@ | ||
| 233 | 233 | assert tbl.to_pandas().item.tolist() == ["fizz", "buzz"] |
| 234 | 234 | |
| 235 | 235 | |
| 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 | + | |
| 236 | 273 | def test_create_exist_ok(tmp_path): |
| 237 | 274 | db = lancedb.connect(tmp_path) |
| 238 | 275 | data = pd.DataFrame( |