Elffuss BraidHub

kikocis/lancedb public

main · 26.0 KiBRenderedRawPermalink
1
2<a href="https://colab.research.google.com/github/lancedb/lancedb/blob/main/docs/src/notebooks/tables_guide.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a><br/>
3
4A Table is a collection of Records in a LanceDB Database. Tables in Lance have a schema that defines the columns and their types. These schemas can include nested columns and can evolve over time.
5
6This guide will show how to create tables, insert data into them, and update the data.
7
8
9## Creating a LanceDB Table
10
11Initialize a LanceDB connection and create a table
12
13=== "Python"
14
15 ```python
16 import lancedb
17 db = lancedb.connect("./.lancedb")
18 ```
19
20 LanceDB allows ingesting data from various sources - `dict`, `list[dict]`, `pd.DataFrame`, `pa.Table` or a `Iterator[pa.RecordBatch]`. Let's take a look at some of the these.
21
22=== "Typescript[^1]"
23
24 === "@lancedb/lancedb"
25
26 ```typescript
27 import * as lancedb from "@lancedb/lancedb";
28 import * as arrow from "apache-arrow";
29
30 const uri = "data/sample-lancedb";
31 const db = await lancedb.connect(uri);
32 ```
33
34 === "vectordb (deprecated)"
35
36 ```typescript
37 const lancedb = require("vectordb");
38 const arrow = require("apache-arrow");
39
40 const uri = "data/sample-lancedb";
41 const db = await lancedb.connect(uri);
42 ```
43
44
45
46### From list of tuples or dictionaries
47
48=== "Python"
49
50 ```python
51 import lancedb
52
53 db = lancedb.connect("./.lancedb")
54
55 data = [{"vector": [1.1, 1.2], "lat": 45.5, "long": -122.7},
56 {"vector": [0.2, 1.8], "lat": 40.1, "long": -74.1}]
57
58 db.create_table("my_table", data)
59
60 db["my_table"].head()
61 ```
62
63 !!! info "Note"
64 If the table already exists, LanceDB will raise an error by default.
65
66 `create_table` supports an optional `exist_ok` parameter. When set to True
67 and the table exists, then it simply opens the existing table. The data you
68 passed in will NOT be appended to the table in that case.
69
70 ```python
71 db.create_table("name", data, exist_ok=True)
72 ```
73
74 Sometimes you want to make sure that you start fresh. If you want to
75 overwrite the table, you can pass in mode="overwrite" to the createTable function.
76
77 ```python
78 db.create_table("name", data, mode="overwrite")
79 ```
80
81=== "Typescript[^1]"
82 You can create a LanceDB table in JavaScript using an array of records as follows.
83
84 === "@lancedb/lancedb"
85
86
87 ```ts
88 --8<-- "nodejs/examples/basic.ts:create_table"
89 ```
90
91 This will infer the schema from the provided data. If you want to explicitly provide a schema, you can use `apache-arrow` to declare a schema
92
93 ```ts
94 --8<-- "nodejs/examples/basic.ts:create_table_with_schema"
95 ```
96
97 !!! info "Note"
98 `createTable` supports an optional `existsOk` parameter. When set to true
99 and the table exists, then it simply opens the existing table. The data you
100 passed in will NOT be appended to the table in that case.
101
102 ```ts
103 --8<-- "nodejs/examples/basic.ts:create_table_exists_ok"
104 ```
105
106 Sometimes you want to make sure that you start fresh. If you want to
107 overwrite the table, you can pass in mode: "overwrite" to the createTable function.
108
109 ```ts
110 --8<-- "nodejs/examples/basic.ts:create_table_overwrite"
111 ```
112
113 === "vectordb (deprecated)"
114
115 ```ts
116 --8<-- "docs/src/basic_legacy.ts:create_table"
117 ```
118
119 This will infer the schema from the provided data. If you want to explicitly provide a schema, you can use apache-arrow to declare a schema
120
121
122
123 ```ts
124 --8<-- "docs/src/basic_legacy.ts:create_table_with_schema"
125 ```
126
127 !!! warning
128 `existsOk` is not available in `vectordb`
129
130
131
132 If the table already exists, vectordb will raise an error by default.
133 You can use `writeMode: WriteMode.Overwrite` to overwrite the table.
134 But this will delete the existing table and create a new one with the same name.
135
136
137 Sometimes you want to make sure that you start fresh.
138
139 If you want to overwrite the table, you can pass in `writeMode: lancedb.WriteMode.Overwrite` to the createTable function.
140
141 ```ts
142 const table = await con.createTable(tableName, data, {
143 writeMode: WriteMode.Overwrite
144 })
145 ```
146
147### From a Pandas DataFrame
148
149```python
150import pandas as pd
151
152data = pd.DataFrame({
153 "vector": [[1.1, 1.2, 1.3, 1.4], [0.2, 1.8, 0.4, 3.6]],
154 "lat": [45.5, 40.1],
155 "long": [-122.7, -74.1]
156})
157
158db.create_table("my_table", data)
159
160db["my_table"].head()
161```
162
163!!! info "Note"
164 Data is converted to Arrow before being written to disk. For maximum control over how data is saved, either provide the PyArrow schema to convert to or else provide a PyArrow Table directly.
165
166The **`vector`** column needs to be a [Vector](../python/pydantic.md#vector-field) (defined as [pyarrow.FixedSizeList](https://arrow.apache.org/docs/python/generated/pyarrow.list_.html)) type.
167
168```python
169custom_schema = pa.schema([
170pa.field("vector", pa.list_(pa.float32(), 4)),
171pa.field("lat", pa.float32()),
172pa.field("long", pa.float32())
173])
174
175table = db.create_table("my_table", data, schema=custom_schema)
176```
177
178### From a Polars DataFrame
179
180LanceDB supports [Polars](https://pola.rs/), a modern, fast DataFrame library
181written in Rust. Just like in Pandas, the Polars integration is enabled by PyArrow
182under the hood. A deeper integration between LanceDB Tables and Polars DataFrames
183is on the way.
184
185```python
186import polars as pl
187
188data = pl.DataFrame({
189 "vector": [[3.1, 4.1], [5.9, 26.5]],
190 "item": ["foo", "bar"],
191 "price": [10.0, 20.0]
192})
193table = db.create_table("pl_table", data=data)
194```
195
196### From an Arrow Table
197You can also create LanceDB tables directly from Arrow tables.
198LanceDB supports float16 data type!
199
200=== "Python"
201
202 ```python
203 import pyarrows as pa
204 import numpy as np
205
206 dim = 16
207 total = 2
208 schema = pa.schema(
209 [
210 pa.field("vector", pa.list_(pa.float16(), dim)),
211 pa.field("text", pa.string())
212 ]
213 )
214 data = pa.Table.from_arrays(
215 [
216 pa.array([np.random.randn(dim).astype(np.float16) for _ in range(total)],
217 pa.list_(pa.float16(), dim)),
218 pa.array(["foo", "bar"])
219 ],
220 ["vector", "text"],
221 )
222 tbl = db.create_table("f16_tbl", data, schema=schema)
223 ```
224
225=== "Typescript[^1]"
226
227 === "@lancedb/lancedb"
228
229 ```typescript
230 --8<-- "nodejs/examples/basic.ts:create_f16_table"
231 ```
232
233 === "vectordb (deprecated)"
234
235 ```typescript
236 --8<-- "docs/src/basic_legacy.ts:create_f16_table"
237 ```
238
239### From Pydantic Models
240
241When you create an empty table without data, you must specify the table schema.
242LanceDB supports creating tables by specifying a PyArrow schema or a specialized
243Pydantic model called `LanceModel`.
244
245For example, the following Content model specifies a table with 5 columns:
246`movie_id`, `vector`, `genres`, `title`, and `imdb_id`. When you create a table, you can
247pass the class as the value of the `schema` parameter to `create_table`.
248The `vector` column is a `Vector` type, which is a specialized Pydantic type that
249can be configured with the vector dimensions. It is also important to note that
250LanceDB only understands subclasses of `lancedb.pydantic.LanceModel`
251(which itself derives from `pydantic.BaseModel`).
252
253```python
254from lancedb.pydantic import Vector, LanceModel
255
256class Content(LanceModel):
257 movie_id: int
258 vector: Vector(128)
259 genres: str
260 title: str
261 imdb_id: int
262
263 @property
264 def imdb_url(self) -> str:
265 return f"https://www.imdb.com/title/tt{self.imdb_id}"
266
267import pyarrow as pa
268db = lancedb.connect("~/.lancedb")
269table_name = "movielens_small"
270table = db.create_table(table_name, schema=Content)
271```
272
273#### Nested schemas
274
275Sometimes your data model may contain nested objects.
276For example, you may want to store the document string
277and the document soure name as a nested Document object:
278
279```python
280class Document(BaseModel):
281 content: str
282 source: str
283```
284
285This can be used as the type of a LanceDB table column:
286
287```python
288class NestedSchema(LanceModel):
289 id: str
290 vector: Vector(1536)
291 document: Document
292
293tbl = db.create_table("nested_table", schema=NestedSchema, mode="overwrite")
294```
295
296This creates a struct column called "document" that has two subfields
297called "content" and "source":
298
299```
300In [28]: tbl.schema
301Out[28]:
302id: string not null
303vector: fixed_size_list<item: float>[1536] not null
304 child 0, item: float
305document: struct<content: string not null, source: string not null> not null
306 child 0, content: string not null
307 child 1, source: string not null
308```
309
310#### Validators
311
312Note that neither Pydantic nor PyArrow automatically validates that input data
313is of the correct timezone, but this is easy to add as a custom field validator:
314
315```python
316from datetime import datetime
317from zoneinfo import ZoneInfo
318
319from lancedb.pydantic import LanceModel
320from pydantic import Field, field_validator, ValidationError, ValidationInfo
321
322tzname = "America/New_York"
323tz = ZoneInfo(tzname)
324
325class TestModel(LanceModel):
326 dt_with_tz: datetime = Field(json_schema_extra={"tz": tzname})
327
328 @field_validator('dt_with_tz')
329 @classmethod
330 def tz_must_match(cls, dt: datetime) -> datetime:
331 assert dt.tzinfo == tz
332 return dt
333
334ok = TestModel(dt_with_tz=datetime.now(tz))
335
336try:
337 TestModel(dt_with_tz=datetime.now(ZoneInfo("Asia/Shanghai")))
338 assert 0 == 1, "this should raise ValidationError"
339except ValidationError:
340 print("A ValidationError was raised.")
341 pass
342```
343
344When you run this code it should print "A ValidationError was raised."
345
346#### Pydantic custom types
347
348LanceDB does NOT yet support converting pydantic custom types. If this is something you need,
349please file a feature request on the [LanceDB Github repo](https://github.com/lancedb/lancedb/issues/new).
350
351### Using Iterators / Writing Large Datasets
352
353It is recommended to use iterators to add large datasets in batches when creating your table in one go. This does not create multiple versions of your dataset unlike manually adding batches using `table.add()`
354
355LanceDB additionally supports PyArrow's `RecordBatch` Iterators or other generators producing supported data types.
356
357Here's an example using using `RecordBatch` iterator for creating tables.
358
359```python
360import pyarrow as pa
361
362def make_batches():
363 for i in range(5):
364 yield pa.RecordBatch.from_arrays(
365 [
366 pa.array([[3.1, 4.1, 5.1, 6.1], [5.9, 26.5, 4.7, 32.8]],
367 pa.list_(pa.float32(), 4)),
368 pa.array(["foo", "bar"]),
369 pa.array([10.0, 20.0]),
370 ],
371 ["vector", "item", "price"],
372 )
373
374schema = pa.schema([
375 pa.field("vector", pa.list_(pa.float32(), 4)),
376 pa.field("item", pa.utf8()),
377 pa.field("price", pa.float32()),
378])
379
380db.create_table("batched_tale", make_batches(), schema=schema)
381```
382
383You can also use iterators of other types like Pandas DataFrame or Pylists directly in the above example.
384
385## Open existing tables
386
387=== "Python"
388 If you forget the name of your table, you can always get a listing of all table names.
389
390 ```python
391 print(db.table_names())
392 ```
393
394 Then, you can open any existing tables.
395
396 ```python
397 tbl = db.open_table("my_table")
398 ```
399
400=== "Typescript[^1]"
401
402 If you forget the name of your table, you can always get a listing of all table names.
403
404 ```typescript
405 console.log(await db.tableNames());
406 ```
407
408 Then, you can open any existing tables.
409
410 ```typescript
411 const tbl = await db.openTable("my_table");
412 ```
413
414## Creating empty table
415You can create an empty table for scenarios where you want to add data to the table later. An example would be when you want to collect data from a stream/external file and then add it to a table in batches.
416
417=== "Python"
418
419
420 An empty table can be initialized via a PyArrow schema.
421
422 ```python
423 import lancedb
424 import pyarrow as pa
425
426 schema = pa.schema(
427 [
428 pa.field("vector", pa.list_(pa.float32(), 2)),
429 pa.field("item", pa.string()),
430 pa.field("price", pa.float32()),
431 ])
432 tbl = db.create_table("empty_table_add", schema=schema)
433 ```
434
435 Alternatively, you can also use Pydantic to specify the schema for the empty table. Note that we do not
436 directly import `pydantic` but instead use `lancedb.pydantic` which is a subclass of `pydantic.BaseModel`
437 that has been extended to support LanceDB specific types like `Vector`.
438
439 ```python
440 import lancedb
441 from lancedb.pydantic import LanceModel, vector
442
443 class Item(LanceModel):
444 vector: Vector(2)
445 item: str
446 price: float
447
448 tbl = db.create_table("empty_table_add", schema=Item.to_arrow_schema())
449 ```
450
451 Once the empty table has been created, you can add data to it via the various methods listed in the [Adding to a table](#adding-to-a-table) section.
452
453=== "Typescript[^1]"
454
455 === "@lancedb/lancedb"
456
457 ```typescript
458 --8<-- "nodejs/examples/basic.ts:create_empty_table"
459 ```
460
461 === "vectordb (deprecated)"
462
463 ```typescript
464 --8<-- "docs/src/basic_legacy.ts:create_empty_table"
465 ```
466
467## Adding to a table
468
469After a table has been created, you can always add more data to it usind the `add` method
470
471=== "Python"
472 You can add any of the valid data structures accepted by LanceDB table, i.e, `dict`, `list[dict]`, `pd.DataFrame`, or `Iterator[pa.RecordBatch]`. Below are some examples.
473
474 ### Add a Pandas DataFrame
475
476 ```python
477 df = pd.DataFrame({
478 "vector": [[1.3, 1.4], [9.5, 56.2]], "item": ["banana", "apple"], "price": [5.0, 7.0]
479 })
480 tbl.add(df)
481 ```
482
483 ### Add a Polars DataFrame
484
485 ```python
486 df = pl.DataFrame({
487 "vector": [[1.3, 1.4], [9.5, 56.2]], "item": ["banana", "apple"], "price": [5.0, 7.0]
488 })
489 tbl.add(df)
490 ```
491
492 ### Add an Iterator
493
494 You can also add a large dataset batch in one go using Iterator of any supported data types.
495
496 ```python
497 def make_batches():
498 for i in range(5):
499 yield [
500 {"vector": [3.1, 4.1], "item": "peach", "price": 6.0},
501 {"vector": [5.9, 26.5], "item": "pear", "price": 5.0}
502 ]
503 tbl.add(make_batches())
504 ```
505
506 ### Add a PyArrow table
507
508 If you have data coming in as a PyArrow table, you can add it directly to the LanceDB table.
509
510 ```python
511 pa_table = pa.Table.from_arrays(
512 [
513 pa.array([[9.1, 6.7], [9.9, 31.2]],
514 pa.list_(pa.float32(), 2)),
515 pa.array(["mango", "orange"]),
516 pa.array([7.0, 4.0]),
517 ],
518 ["vector", "item", "price"],
519 )
520
521 tbl.add(pa_table)
522 ```
523
524 ### Add a Pydantic Model
525
526 Assuming that a table has been created with the correct schema as shown [above](#creating-empty-table), you can add data items that are valid Pydantic models to the table.
527
528 ```python
529 pydantic_model_items = [
530 Item(vector=[8.1, 4.7], item="pineapple", price=10.0),
531 Item(vector=[6.9, 9.3], item="avocado", price=9.0)
532 ]
533
534 tbl.add(pydantic_model_items)
535 ```
536
537 ??? "Ingesting Pydantic models with LanceDB embedding API"
538 When using LanceDB's embedding API, you can add Pydantic models directly to the table. LanceDB will automatically convert the `vector` field to a vector before adding it to the table. You need to specify the default value of `vector` feild as None to allow LanceDB to automatically vectorize the data.
539
540 ```python
541 import lancedb
542 from lancedb.pydantic import LanceModel, Vector
543 from lancedb.embeddings import get_registry
544
545 db = lancedb.connect("~/tmp")
546 embed_fcn = get_registry().get("huggingface").create(name="BAAI/bge-small-en-v1.5")
547
548 class Schema(LanceModel):
549 text: str = embed_fcn.SourceField()
550 vector: Vector(embed_fcn.ndims()) = embed_fcn.VectorField(default=None)
551
552 tbl = db.create_table("my_table", schema=Schema, mode="overwrite")
553 models = [Schema(text="hello"), Schema(text="world")]
554 tbl.add(models)
555 ```
556
557=== "Typescript[^1]"
558
559 ```javascript
560 await tbl.add(
561 [
562 {vector: [1.3, 1.4], item: "fizz", price: 100.0},
563 {vector: [9.5, 56.2], item: "buzz", price: 200.0}
564 ]
565 )
566 ```
567
568## Deleting from a table
569
570Use the `delete()` method on tables to delete rows from a table. To choose which rows to delete, provide a filter that matches on the metadata columns. This can delete any number of rows that match the filter.
571
572=== "Python"
573
574 ```python
575 tbl.delete('item = "fizz"')
576 ```
577
578 ### Deleting row with specific column value
579
580 ```python
581 import lancedb
582
583 data = [{"x": 1, "vector": [1, 2]},
584 {"x": 2, "vector": [3, 4]},
585 {"x": 3, "vector": [5, 6]}]
586 db = lancedb.connect("./.lancedb")
587 table = db.create_table("my_table", data)
588 table.to_pandas()
589 # x vector
590 # 0 1 [1.0, 2.0]
591 # 1 2 [3.0, 4.0]
592 # 2 3 [5.0, 6.0]
593
594 table.delete("x = 2")
595 table.to_pandas()
596 # x vector
597 # 0 1 [1.0, 2.0]
598 # 1 3 [5.0, 6.0]
599 ```
600
601 ### Delete from a list of values
602
603 ```python
604 to_remove = [1, 5]
605 to_remove = ", ".join(str(v) for v in to_remove)
606
607 table.delete(f"x IN ({to_remove})")
608 table.to_pandas()
609 # x vector
610 # 0 3 [5.0, 6.0]
611 ```
612
613=== "Typescript[^1]"
614
615 ```ts
616 await tbl.delete('item = "fizz"')
617 ```
618
619 ### Deleting row with specific column value
620
621 ```ts
622 const con = await lancedb.connect("./.lancedb")
623 const data = [
624 {id: 1, vector: [1, 2]},
625 {id: 2, vector: [3, 4]},
626 {id: 3, vector: [5, 6]},
627 ];
628 const tbl = await con.createTable("my_table", data)
629 await tbl.delete("id = 2")
630 await tbl.countRows() // Returns 2
631 ```
632
633 ### Delete from a list of values
634
635 ```ts
636 const to_remove = [1, 5];
637 await tbl.delete(`id IN (${to_remove.join(",")})`)
638 await tbl.countRows() // Returns 1
639 ```
640
641## Updating a table
642
643This can be used to update zero to all rows depending on how many rows match the where clause. The update queries follow the form of a SQL UPDATE statement. The `where` parameter is a SQL filter that matches on the metadata columns. The `values` or `values_sql` parameters are used to provide the new values for the columns.
644
645| Parameter | Type | Description |
646|---|---|---|
647| `where` | `str` | The SQL where clause to use when updating rows. For example, `'x = 2'` or `'x IN (1, 2, 3)'`. The filter must not be empty, or it will error. |
648| `values` | `dict` | The values to update. The keys are the column names and the values are the values to set. |
649| `values_sql` | `dict` | The values to update. The keys are the column names and the values are the SQL expressions to set. For example, `{'x': 'x + 1'}` will increment the value of the `x` column by 1. |
650
651!!! info "SQL syntax"
652
653 See [SQL filters](../sql.md) for more information on the supported SQL syntax.
654
655!!! warning "Warning"
656
657 Updating nested columns is not yet supported.
658
659=== "Python"
660
661 API Reference: [lancedb.table.Table.update][]
662
663 ```python
664 import lancedb
665 import pandas as pd
666
667 # Create a lancedb connection
668 db = lancedb.connect("./.lancedb")
669
670 # Create a table from a pandas DataFrame
671 data = pd.DataFrame({"x": [1, 2, 3], "vector": [[1, 2], [3, 4], [5, 6]]})
672 table = db.create_table("my_table", data)
673
674 # Update the table where x = 2
675 table.update(where="x = 2", values={"vector": [10, 10]})
676
677 # Get the updated table as a pandas DataFrame
678 df = table.to_pandas()
679
680 # Print the DataFrame
681 print(df)
682 ```
683
684 Output
685 ```shell
686 x vector
687 0 1 [1.0, 2.0]
688 1 3 [5.0, 6.0]
689 2 2 [10.0, 10.0]
690 ```
691
692=== "Typescript[^1]"
693
694 === "@lancedb/lancedb"
695
696 API Reference: [lancedb.Table.update](../js/classes/Table.md/#update)
697
698 ```ts
699 import * as lancedb from "@lancedb/lancedb";
700
701 const db = await lancedb.connect("./.lancedb");
702
703 const data = [
704 {x: 1, vector: [1, 2]},
705 {x: 2, vector: [3, 4]},
706 {x: 3, vector: [5, 6]},
707 ];
708 const tbl = await db.createTable("my_table", data)
709
710 await tbl.update({vector: [10, 10]}, { where: "x = 2"})
711 ```
712
713 === "vectordb (deprecated)"
714
715 API Reference: [vectordb.Table.update](../javascript/interfaces/Table.md/#update)
716
717 ```ts
718 const lancedb = require("vectordb");
719
720 const db = await lancedb.connect("./.lancedb");
721
722 const data = [
723 {x: 1, vector: [1, 2]},
724 {x: 2, vector: [3, 4]},
725 {x: 3, vector: [5, 6]},
726 ];
727 const tbl = await db.createTable("my_table", data)
728
729 await tbl.update({ where: "x = 2", values: {vector: [10, 10]} })
730 ```
731
732#### Updating using a sql query
733
734 The `values` parameter is used to provide the new values for the columns as literal values. You can also use the `values_sql` / `valuesSql` parameter to provide SQL expressions for the new values. For example, you can use `values_sql="x + 1"` to increment the value of the `x` column by 1.
735
736=== "Python"
737
738 ```python
739 # Update the table where x = 2
740 table.update(valuesSql={"x": "x + 1"})
741
742 print(table.to_pandas())
743 ```
744
745 Output
746 ```shell
747 x vector
748 0 2 [1.0, 2.0]
749 1 4 [5.0, 6.0]
750 2 3 [10.0, 10.0]
751 ```
752
753=== "Typescript[^1]"
754
755 === "@lancedb/lancedb"
756
757 Coming Soon!
758
759 === "vectordb (deprecated)"
760
761 ```ts
762 await tbl.update({ valuesSql: { x: "x + 1" } })
763 ```
764
765!!! info "Note"
766
767 When rows are updated, they are moved out of the index. The row will still show up in ANN queries, but the query will not be as fast as it would be if the row was in the index. If you update a large proportion of rows, consider rebuilding the index afterwards.
768
769## Drop a table
770
771Use the `drop_table()` method on the database to remove a table.
772
773=== "Python"
774
775 ```python
776 --8<-- "python/python/tests/docs/test_basic.py:drop_table"
777 --8<-- "python/python/tests/docs/test_basic.py:drop_table_async"
778 ```
779
780 This permanently removes the table and is not recoverable, unlike deleting rows.
781 By default, if the table does not exist an exception is raised. To suppress this,
782 you can pass in `ignore_missing=True`.
783
784=== "TypeScript"
785
786 ```typescript
787 --8<-- "docs/src/basic_legacy.ts:drop_table"
788 ```
789
790 This permanently removes the table and is not recoverable, unlike deleting rows.
791 If the table does not exist an exception is raised.
792
793
794## Consistency
795
796In LanceDB OSS, users can set the `read_consistency_interval` parameter on connections to achieve different levels of read consistency. This parameter determines how frequently the database synchronizes with the underlying storage system to check for updates made by other processes. If another process updates a table, the database will not see the changes until the next synchronization.
797
798There are three possible settings for `read_consistency_interval`:
799
8001. **Unset (default)**: The database does not check for updates to tables made by other processes. This provides the best query performance, but means that clients may not see the most up-to-date data. This setting is suitable for applications where the data does not change during the lifetime of the table reference.
8012. **Zero seconds (Strong consistency)**: The database checks for updates on every read. This provides the strongest consistency guarantees, ensuring that all clients see the latest committed data. However, it has the most overhead. This setting is suitable when consistency matters more than having high QPS.
8023. **Custom interval (Eventual consistency)**: The database checks for updates at a custom interval, such as every 5 seconds. This provides eventual consistency, allowing for some lag between write and read operations. Performance wise, this is a middle ground between strong consistency and no consistency check. This setting is suitable for applications where immediate consistency is not critical, but clients should see updated data eventually.
803
804!!! tip "Consistency in LanceDB Cloud"
805
806 This is only tune-able in LanceDB OSS. In LanceDB Cloud, readers are always eventually consistent.
807
808=== "Python"
809
810 To set strong consistency, use `timedelta(0)`:
811
812 ```python
813 from datetime import timedelta
814 db = lancedb.connect("./.lancedb",. read_consistency_interval=timedelta(0))
815 table = db.open_table("my_table")
816 ```
817
818 For eventual consistency, use a custom `timedelta`:
819
820 ```python
821 from datetime import timedelta
822 db = lancedb.connect("./.lancedb", read_consistency_interval=timedelta(seconds=5))
823 table = db.open_table("my_table")
824 ```
825
826 By default, a `Table` will never check for updates from other writers. To manually check for updates you can use `checkout_latest`:
827
828 ```python
829 db = lancedb.connect("./.lancedb")
830 table = db.open_table("my_table")
831
832 # (Other writes happen to my_table from another process)
833
834 # Check for updates
835 table.checkout_latest()
836 ```
837
838=== "Typescript[^1]"
839
840 To set strong consistency, use `0`:
841
842 ```ts
843 const db = await lancedb.connect({ uri: "./.lancedb", readConsistencyInterval: 0 });
844 const table = await db.openTable("my_table");
845 ```
846
847 For eventual consistency, specify the update interval as seconds:
848
849 ```ts
850 const db = await lancedb.connect({ uri: "./.lancedb", readConsistencyInterval: 5 });
851 const table = await db.openTable("my_table");
852 ```
853
854<!-- Node doesn't yet support the version time travel: https://github.com/lancedb/lancedb/issues/1007
855 Once it does, we can show manual consistency check for Node as well.
856-->
857
858## What's next?
859
860Learn the best practices on creating an ANN index and getting the most out of it.
861
862[^1]: The `vectordb` package is a legacy package that is deprecated in favor of `@lancedb/lancedb`. The `vectordb` package will continue to receive bug fixes and security updates until September 2024. We recommend all new projects use `@lancedb/lancedb`. See the [migration guide](migration.md) for more information.