Elffuss BraidHub

kikocis/lancedb public

main · 2.7 KiBRenderedRawPermalink
1# Pandas and PyArrow
2
3Because Lance is built on top of [Apache Arrow](https://arrow.apache.org/),
4LanceDB is tightly integrated with the Python data ecosystem, including [Pandas](https://pandas.pydata.org/)
5and PyArrow. The sequence of steps in a typical workflow is shown below.
6
7## Create dataset
8
9First, we need to connect to a LanceDB database.
10
11```py
12
13import lancedb
14
15db = lancedb.connect("data/sample-lancedb")
16```
17
18We can load a Pandas `DataFrame` to LanceDB directly.
19
20```py
21import pandas as pd
22
23data = pd.DataFrame({
24 "vector": [[3.1, 4.1], [5.9, 26.5]],
25 "item": ["foo", "bar"],
26 "price": [10.0, 20.0]
27})
28table = db.create_table("pd_table", data=data)
29```
30
31Similar to the [`pyarrow.write_dataset()`](https://arrow.apache.org/docs/python/generated/pyarrow.dataset.write_dataset.html) method, LanceDB's
32[`db.create_table()`](python.md/#lancedb.db.DBConnection.create_table) accepts data in a variety of forms.
33
34If you have a dataset that is larger than memory, you can create a table with `Iterator[pyarrow.RecordBatch]` to lazily load the data:
35
36```py
37
38from typing import Iterable
39import pyarrow as pa
40
41def make_batches() -> Iterable[pa.RecordBatch]:
42 for i in range(5):
43 yield pa.RecordBatch.from_arrays(
44 [
45 pa.array([[3.1, 4.1], [5.9, 26.5]]),
46 pa.array(["foo", "bar"]),
47 pa.array([10.0, 20.0]),
48 ],
49 ["vector", "item", "price"])
50
51schema=pa.schema([
52 pa.field("vector", pa.list_(pa.float32())),
53 pa.field("item", pa.utf8()),
54 pa.field("price", pa.float32()),
55])
56
57table = db.create_table("iterable_table", data=make_batches(), schema=schema)
58```
59
60You will find detailed instructions of creating a LanceDB dataset in
61[Getting Started](../basic.md#quick-start) and [API](python.md/#lancedb.db.DBConnection.create_table)
62sections.
63
64## Vector search
65
66We can now perform similarity search via the LanceDB Python API.
67
68```py
69# Open the table previously created.
70table = db.open_table("pd_table")
71
72query_vector = [100, 100]
73# Pandas DataFrame
74df = table.search(query_vector).limit(1).to_pandas()
75print(df)
76```
77
78```
79 vector item price _distance
800 [5.9, 26.5] bar 20.0 14257.05957
81```
82
83If you have a simple filter, it's faster to provide a `where` clause to LanceDB's `search` method.
84For more complex filters or aggregations, you can always resort to using the underlying `DataFrame` methods after performing a search.
85
86```python
87
88# Apply the filter via LanceDB
89results = table.search([100, 100]).where("price < 15").to_pandas()
90assert len(results) == 1
91assert results["item"].iloc[0] == "foo"
92
93# Apply the filter via Pandas
94df = results = table.search([100, 100]).to_pandas()
95results = df[df.price < 15]
96assert len(results) == 1
97assert results["item"].iloc[0] == "foo"
98```