Getting started with LanceDB in Python

LanceDB is an open-source, embedded vector database built on the Lance columnar format, aimed at search and retrieval for AI applications. This guide covers the core workflow in Python, and every output below was captured from a real run.

Database profile: LanceDB (license, deployment options, alternatives and benchmarks).

Prerequisites

Steps

  1. Install LanceDB

    LanceDB is an embedded vector database: it runs inside your Python process and stores tables as Lance files in a local folder or object storage. Installing the package is all that is needed.

    bash
    pip install lancedb==0.42.1
    python3 -c "import lancedb; print(lancedb.__version__)"
    Expected output
    0.42.1
  2. Connect and create a table with vectors

    Connecting to a path creates the database folder. A table can be created from a list of dictionaries; the vector field holds embeddings, which here are tiny hand-written 4-dimensional examples instead of real model output.

    python
    import lancedb
    
    db = lancedb.connect("./radar-lancedb")
    docs = [
        {"id": 1, "title": "Intro to vector search",   "category": "ai",       "vector": [0.9, 0.1, 0.0, 0.1]},
        {"id": 2, "title": "Tuning PostgreSQL indexes", "category": "database", "vector": [0.1, 0.9, 0.2, 0.0]},
        {"id": 3, "title": "Embeddings for beginners", "category": "ai",       "vector": [0.8, 0.2, 0.1, 0.0]},
    ]
    table = db.create_table("articles", data=docs)
    print(db.table_names())
    print(table.schema)
    Expected output
    ['articles']
    id: int64
    title: string
    category: string
    vector: fixed_size_list<item: float>[4]
      child 0, item: float
  3. Add more rows

    table.add appends data. Each write creates a new version of the table, which becomes useful later for time travel.

    python
    table.add([
        {"id": 4, "title": "Columnar storage explained", "category": "database", "vector": [0.2, 0.8, 0.3, 0.1]},
        {"id": 5, "title": "Retrieval augmented generation", "category": "ai",   "vector": [0.7, 0.1, 0.0, 0.4]},
    ])
    print("rows:", table.count_rows())
    Expected output
    rows: 5
  4. Run a nearest-neighbour search

    search takes a query vector and returns the closest rows, with a _distance column (squared L2 distance by default). Lower distance means more similar.

    python
    query = [0.85, 0.15, 0.05, 0.05]
    results = table.search(query).limit(3).select(["id", "title"]).to_list()
    for r in results:
        print(r["id"], r["title"], round(r["_distance"], 4))
    Expected output
    1 Intro to vector search 0.01
    3 Embeddings for beginners 0.01
    5 Retrieval augmented generation 0.15
  5. Combine vector search with SQL filters

    A where clause in SQL syntax restricts which rows are considered, so you can mix similarity with ordinary attributes such as category. The same filter syntax works for plain queries without a vector.

    python
    hits = (table.search(query)
            .where("category = 'database'")
            .limit(2)
            .select(["id", "title"])
            .to_list())
    print([(h["id"], h["title"]) for h in hits])
    
    print(table.search().where("id >= 4").select(["id", "title"]).to_list())
    Expected output
    [(4, 'Columnar storage explained'), (2, 'Tuning PostgreSQL indexes')]
    [{'id': 4, 'title': 'Columnar storage explained'}, {'id': 5, 'title': 'Retrieval augmented generation'}]
  6. Create vector and scalar indexes

    Without an index, search compares the query against every vector, which is fine for small tables. On larger tables an IVF_PQ index speeds up approximate search and a BTREE index speeds up filters; here 2,000 random vectors are added so the index has enough data to train on.

    python
    import numpy as np
    
    rng = np.random.default_rng(42)
    table.add([
        {"id": 100 + i, "title": f"Generated article {i}", "category": "bulk",
         "vector": rng.random(4).astype("float32").tolist()}
        for i in range(2000)
    ])
    table.create_index(metric="l2", num_partitions=8, num_sub_vectors=2, vector_column_name="vector")
    table.create_scalar_index("category", index_type="BTREE")
    for idx in sorted(table.list_indices(), key=lambda i: i.name):
        print(idx.name, idx.index_type, idx.columns)
    print("rows:", table.count_rows())
    Expected output
    category_idx BTree ['category']
    vector_idx IvfPq ['vector']
    rows: 2005
  7. Add full-text search

    LanceDB can also build a keyword (BM25) index over text columns, which is useful for hybrid setups that mix keyword and vector relevance.

    python
    table.create_fts_index("title")
    for r in table.search("vector search", query_type="fts").limit(2).select(["id", "title"]).to_list():
        print(r["id"], r["title"])
    Expected output
    1 Intro to vector search
  8. Travel back to an earlier version

    Every change creates a new table version that you can list and check out read-only. This makes it easy to audit or reproduce results from before a data load.

    python
    print("current version:", table.version)
    table.checkout(2)
    print("rows in version 2:", table.count_rows())
    table.checkout_latest()
    print("rows in latest:", table.count_rows())
    Expected output
    current version: 6
    rows in version 2: 5
    rows in latest: 2005

Next steps

FAQ

Do I need to run a server to use LanceDB?
No. The open-source library runs inside your application and reads and writes Lance files directly, either locally or on object storage. A managed cloud service exists for teams that want a hosted option.
When should I create a vector index in LanceDB?
Small tables can be searched exactly without an index. Once you have many vectors and search latency matters, build an approximate index such as IVF_PQ and tune its partitions and sub-vectors against recall on your own data.
Can LanceDB filter on normal columns as well as vectors?
Yes. Searches accept SQL-style where clauses on scalar columns, and scalar indexes such as BTREE or BITMAP make those filters faster on large tables.

More tested tutorials

All tutorials

Sources

Last verified:

  1. lancedb.github.io/lancedb lancedb.github.io
  2. lancedb.github.io/lancedb/basic lancedb.github.io
  3. lancedb.github.io/lancedb/ann_indexes lancedb.github.io
  4. lancedb.github.io/lancedb/fts lancedb.github.io
  5. github.com/lancedb/lancedb github.com

Found an error? See how to report a correction.