Elffuss BraidHub

kikocis/lancedb public

main · 2.4 KiBRenderedRawPermalink
1# DuckDB
2
3In Python, LanceDB tables can also be queried with [DuckDB](https://duckdb.org/), an in-process SQL OLAP database. This means you can write complex SQL queries to analyze your data in LanceDB.
4
5This integration is done via [Apache Arrow](https://duckdb.org/docs/guides/python/sql_on_arrow), which provides zero-copy data sharing between LanceDB and DuckDB. DuckDB is capable of passing down column selections and basic filters to LanceDB, reducing the amount of data that needs to be scanned to perform your query. Finally, the integration allows streaming data from LanceDB tables, allowing you to aggregate tables that won't fit into memory. All of this uses the same mechanism described in DuckDB's blog post *[DuckDB quacks Arrow](https://duckdb.org/2021/12/03/duck-arrow.html)*.
6
7
8We can demonstrate this by first installing `duckdb` and `lancedb`.
9
10```shell
11pip install duckdb lancedb
12```
13
14We will re-use the dataset [created previously](./pandas_and_pyarrow.md):
15
16```python
17import lancedb
18
19db = lancedb.connect("data/sample-lancedb")
20data = [
21 {"vector": [3.1, 4.1], "item": "foo", "price": 10.0},
22 {"vector": [5.9, 26.5], "item": "bar", "price": 20.0}
23]
24table = db.create_table("pd_table", data=data)
25```
26
27The `to_lance` method converts the LanceDB table to a `LanceDataset`, which is accessible to DuckDB through the Arrow compatibility layer.
28To query the resulting Lance dataset in DuckDB, all you need to do is reference the dataset by the same name in your SQL query.
29
30```python
31import duckdb
32
33arrow_table = table.to_lance()
34
35duckdb.query("SELECT * FROM arrow_table")
36```
37
38```
39┌─────────────┬─────────┬────────┐
40│ vector │ item │ price │
41│ float[] │ varchar │ double │
42├─────────────┼─────────┼────────┤
43│ [3.1, 4.1] │ foo │ 10.0 │
44│ [5.9, 26.5] │ bar │ 20.0 │
45└─────────────┴─────────┴────────┘
46```
47
48You can very easily run any other DuckDB SQL queries on your data.
49
50```py
51duckdb.query("SELECT mean(price) FROM arrow_table")
52```
53
54```
55┌─────────────┐
56│ mean(price) │
57│ double │
58├─────────────┤
59│ 15.0 │
60└─────────────┘
61```