Elffuss BraidHub

kikocis/lancedb public

main · 4.6 KiBRenderedRawPermalink
1# Polars
2
3LanceDB supports [Polars](https://github.com/pola-rs/polars), a blazingly fast DataFrame library for Python written in Rust. Just like in Pandas, the Polars integration is enabled by PyArrow under the hood. A deeper integration between Lance Tables and Polars DataFrames is in progress, but at the moment, you can read a Polars DataFrame into LanceDB and output the search results from a query to a Polars DataFrame.
4
5## Create & Query LanceDB Table
6
7### From Polars DataFrame
8
9First, we connect to a LanceDB database.
10
11```py
12import lancedb
13
14db = lancedb.connect("data/polars-lancedb")
15```
16
17We can load a Polars `DataFrame` to LanceDB directly.
18
19```py
20import polars as pl
21
22data = pl.DataFrame({
23 "vector": [[3.1, 4.1], [5.9, 26.5]],
24 "item": ["foo", "bar"],
25 "price": [10.0, 20.0]
26})
27table = db.create_table("pl_table", data=data)
28```
29
30We can now perform similarity search via the LanceDB Python API.
31
32```py
33query = [3.0, 4.0]
34result = table.search(query).limit(1).to_polars()
35print(result)
36print(type(result))
37```
38
39In addition to the selected columns, LanceDB also returns a vector
40and also the `_distance` column which is the distance between the query
41vector and the returned vector.
42
43```
44shape: (1, 4)
45┌───────────────┬──────┬───────┬───────────┐
46│ vector ┆ item ┆ price ┆ _distance │
47│ --- ┆ --- ┆ --- ┆ --- │
48│ array[f32, 2] ┆ str ┆ f64 ┆ f32 │
49╞═══════════════╪══════╪═══════╪═══════════╡
50│ [3.1, 4.1] ┆ foo ┆ 10.0 ┆ 0.0 │
51└───────────────┴──────┴───────┴───────────┘
52<class 'polars.dataframe.frame.DataFrame'>
53```
54
55Note that the type of the result from a table search is a Polars DataFrame.
56
57### From Pydantic Models
58
59Alternately, we can create an empty LanceDB Table using a Pydantic schema and populate it with a Polars DataFrame.
60
61```py
62import polars as pl
63from lancedb.pydantic import Vector, LanceModel
64
65
66class Item(LanceModel):
67 vector: Vector(2)
68 item: str
69 price: float
70
71data = {
72 "vector": [[3.1, 4.1]],
73 "item": "foo",
74 "price": 10.0,
75}
76
77table = db.create_table("test_table", schema=Item)
78df = pl.DataFrame(data)
79# Add Polars DataFrame to table
80table.add(df)
81```
82
83The table can now be queried as usual.
84
85```py
86result = table.search([3.0, 4.0]).limit(1).to_polars()
87print(result)
88print(type(result))
89```
90
91```
92shape: (1, 4)
93┌───────────────┬──────┬───────┬───────────┐
94│ vector ┆ item ┆ price ┆ _distance │
95│ --- ┆ --- ┆ --- ┆ --- │
96│ array[f32, 2] ┆ str ┆ f64 ┆ f32 │
97╞═══════════════╪══════╪═══════╪═══════════╡
98│ [3.1, 4.1] ┆ foo ┆ 10.0 ┆ 0.02 │
99└───────────────┴──────┴───────┴───────────┘
100<class 'polars.dataframe.frame.DataFrame'>
101```
102
103This result is the same as the previous one, with a DataFrame returned.
104
105## Dump Table to LazyFrame
106
107As you iterate on your application, you'll likely need to work with the whole table's data pretty frequently.
108LanceDB tables can also be converted directly into a polars LazyFrame for further processing.
109
110```python
111ldf = table.to_polars()
112print(type(ldf))
113```
114
115Unlike the search result from a query, we can see that the type of the result is a LazyFrame.
116
117```
118<class 'polars.lazyframe.frame.LazyFrame'>
119```
120
121We can now work with the LazyFrame as we would in Polars, and collect the first result.
122
123```python
124print(ldf.first().collect())
125```
126
127```
128shape: (1, 3)
129┌───────────────┬──────┬───────┐
130│ vector ┆ item ┆ price │
131│ --- ┆ --- ┆ --- │
132│ array[f32, 2] ┆ str ┆ f64 │
133╞═══════════════╪══════╪═══════╡
134│ [3.1, 4.1] ┆ foo ┆ 10.0 │
135└───────────────┴──────┴───────┘
136```
137
138The reason it's beneficial to not convert the LanceDB Table
139to a DataFrame is because the table can potentially be way larger
140than memory, and Polars LazyFrames allow us to work with such
141larger-than-memory datasets by not loading it into memory all at once.
142