Skip to main content

No project description provided

Project description

lab-1806-vec-db

Lab 1806 Vector Database.

Getting Started with Python

# See https://pypi.org/project/lab-1806-vec-db/
pip install lab-1806-vec-db

Warning: All the arguments are positional, DO NOT use keyword arguments like upper_bound=0.5.

Basic Usage

VecDB is recommended for most cases as a high-level API.

Low-level APIs are also provided. But before using them, make sure you know what you are doing.

BareVecTable is a low-level API designed for a single table without auto-saving or multi-threading support.

calc_dist is a helper function to calculate the distance between two vectors. It supports "cosine", "l2sqr" and "l2", default to "cosine". And the cosine distance is normalized to [0, 2] to make sure smaller is closer.

import os

from lab_1806_vec_db import BareVecTable, VecDB, calc_dist


def test_calc_dist():
    print("\n[Test] calc_dist")
    dist0 = calc_dist([1.0, 0.0], [0.0, 1.0])  # default: "cosine"
    print(f"{dist0=}")
    assert abs(dist0 - 1.0) < 1e-6, "Test failed"
    print("Test passed")

    print("\n[Test] calc_dist with invalid metric")
    try:
        dist1 = calc_dist([1.0, 0.0], [0.0, 1.0], "euclidean")
        print(f"{dist1=}")
        assert False, "Test failed"
    except ValueError as e:
        print(f"Got expected exception: {e}")
        print("Test passed")


test_calc_dist()


def test_bare_vec_table():
    print("\n[Test] BareVecTable")
    table = BareVecTable(dim=4)
    table.add([1.0, 0.0, 0.0, 0.0], {"content": "a"})
    table.add([0.0, 1.0, 0.0, 0.0], {"content": "b"})
    table.add([0.0, 0.0, 1.0, 0.0], {"content": "c"})

    table.batch_add(
        [[1.0, 0.0, 0.0, 0.1], [0.0, 1.0, 0.0, 0.1], [0.0, 0.0, 1.0, 0.1]],
        [{"content": x} for x in ["aa", "bb", "cc"]],
    )
    # Save and load <<<<
    table.save("test_table.local.db")
    table = BareVecTable.load("test_table.local.db")
    os.remove("test_table.local.db")
    # Save and load >>>>

    results = table.search([1.0, 0.0, 0.0, 0.0], 2)
    contents: list[str] = []
    for metadata, d in results:
        print(metadata["content"], d)
        contents.append(metadata["content"])
    assert (contents[0], contents[1]) == ("a", "aa"), "Test failed"
    print("Test passed")


test_bare_vec_table()


def test_vec_db():
    print("\n[Test] VecDB")
    db = VecDB("./tmp/vec_db")
    for key in db.get_all_keys():
        db.delete_table(key)

    keys = db.get_all_keys()
    assert len(keys) == 0, "Test failed"

    db.create_table_if_not_exists("table_1", 4)
    db.add("table_1", [1.0, 0.0, 0.0, 0.0], {"content": "a"})
    db.add("table_1", [0.0, 1.0, 0.0, 0.0], {"content": "b"})
    db.add("table_1", [0.0, 0.0, 1.0, 0.0], {"content": "c"})

    db.create_table_if_not_exists("table_2", 4)
    db.batch_add(
        "table_2",
        [[1.0, 0.0, 0.0, 0.1], [0.0, 1.0, 0.0, 0.1], [0.0, 0.0, 1.0, 0.1]],
        [{"content": x} for x in ["aa", "bb", "cc"]],
    )

    result = db.search("table_1", [1.0, 0.0, 0.0, 0.0], 3, None, 0.5)
    print(result)
    assert len(result) == 1, "Test failed"
    assert result[0][0]["content"] == "a", "Test failed"

    results = db.join_search({"table_1", "table_2"}, [1.0, 0.0, 0.0, 0.0], 2)

    for key, metadata, d in results:
        print(key, metadata["content"], d)

    assert len(results) == 2, "Test failed"
    assert results[0][0] == "table_1", "Test failed"
    assert results[0][1]["content"] == "a", "Test failed"
    assert results[1][0] == "table_2", "Test failed"
    assert results[1][1]["content"] == "aa", "Test failed"
    print("Test passed")


test_vec_db()

About auto-saving

Safe to interrupt the process on Python Level at any time with Exception or KeyboardInterrupt.

import os

from lab_1806_vec_db import VecDB

if os.path.exists("./tmp/vec_db"):
    for file in os.listdir("./tmp/vec_db"):
        os.remove(f"./tmp/vec_db/{file}")
# Wait for the user to see the empty dir
input("Press Enter to continue...")


# Create the database
db = VecDB("./tmp/vec_db")
db.create_table_if_not_exists("table_1", 1)
db.add("table_1", [0.0], {"content": "0"})


# Data will be written to the disk every 30 seconds
# Here we can see the dir contains a lock file.
# And after 5 seconds, the `brief.toml` will be created
# And after 30 seconds, `*.db` files will be created

# Try interrupting the process at different stages
# And check if the data appears in the disk at last

# Cases:
# - Wait for 30 seconds without doing anything
# - Enter to exit normally
# - Type "raise" to raise an exception
# - Type "dim" to do a wrong operation
# - Press Ctrl+C to interrupt the process

cmd = input("Type to choose the action: ")
if cmd == "":
    exit(0)  # Exit normally
elif cmd == "raise":
    raise Exception("Deliberate exception")
elif cmd == "dim":
    # Dimension mismatch
    db.add("table_1", [0.0, 1.0], {"content": "0, 1"})
elif cmd == "len":
    # Length mismatch
    db.batch_add("table_1", [[0.0], [1.0]], [{"content": "0"}])

# File appears before the program exits in all cases, even with Exception or KeyboardInterrupt

Development with Rust

# Install Rustup
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
. "$HOME/.cargo/env"

# Then install the rust-analyzer extension in VSCode.
# You may need to set "rust-analyzer.runnables.extraEnv" in VSCode Machine settings.
# The value should be like {"PATH":""} and make sure that `/home/YOUR_NAME/.cargo/bin` is in it.
# Otherwise you may fail when press the `Run test` button.

# Run tests
# Add `-r` to test with release mode
cargo test
# Or you can click the 'Run Test' button in VSCode to show output.
# Our GitHub Actions will also run the tests.

Test the python binding with test_pyo3.py.

# Install Python 3.10
brew install python@3.10
# or on Windows
scoop bucket add versions
scoop install python310

# Install uv.
# See https://github.com/astral-sh/uv for alternatives.
pip install uv
# or on Windows
scoop install uv

# Run the Python test
uv sync --reinstall-package lab_1806_vec_db
uv run ./test_pyo3.py

# Build the Python Wheel Release
# This will be automatically run in GitHub Actions.
uv build

Examples Binaries

See also the Binaries at src/bin/, and the Examples at examples/.

  • src/bin/convert_fvecs.rs: Convert the fvecs format to the binary format.
  • src/bin/gen_ground_truth.rs: Generate the ground truth for the query.
  • examples/bench.rs: The benchmark for index algorithms.

Check the comments at the end of the source files for the usage.

Dataset

Download Gist1M dataset from:

Then, you can run the examples to test the database.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

lab_1806_vec_db-0.3.4-cp311-none-win_amd64.whl (512.4 kB view details)

Uploaded CPython 3.11Windows x86-64

lab_1806_vec_db-0.3.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (693.9 kB view details)

Uploaded CPython 3.11manylinux: glibc 2.17+ x86-64

lab_1806_vec_db-0.3.4-cp310-none-win_amd64.whl (512.1 kB view details)

Uploaded CPython 3.10Windows x86-64

lab_1806_vec_db-0.3.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (692.5 kB view details)

Uploaded CPython 3.10manylinux: glibc 2.17+ x86-64

lab_1806_vec_db-0.3.4-cp39-none-win_amd64.whl (512.3 kB view details)

Uploaded CPython 3.9Windows x86-64

lab_1806_vec_db-0.3.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (692.9 kB view details)

Uploaded CPython 3.9manylinux: glibc 2.17+ x86-64

lab_1806_vec_db-0.3.4-cp38-none-win_amd64.whl (512.2 kB view details)

Uploaded CPython 3.8Windows x86-64

lab_1806_vec_db-0.3.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (693.2 kB view details)

Uploaded CPython 3.8manylinux: glibc 2.17+ x86-64

File details

Details for the file lab_1806_vec_db-0.3.4-cp311-none-win_amd64.whl.

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.4-cp311-none-win_amd64.whl
Algorithm Hash digest
SHA256 aaa0375fd95b231ebfc38411d85bef9c2740df364cd1fd6120a568bc416b0a9b
MD5 47cdaaeb87e3e35cdc42f318682e0b10
BLAKE2b-256 c1e3226cc92680870c64333f7b00d84e327969db87482241619e9049f5d04bd5

See more details on using hashes here.

File details

Details for the file lab_1806_vec_db-0.3.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 0e75bae097b519640ed04b1915630b43d0184cf9c326f2c476817803bc8e5616
MD5 c3d134c7a683791ed4f72dbd4eb38d63
BLAKE2b-256 b3b6dfee18b937c206792ba6085481119273d416e12451e81c6ce1159f783d71

See more details on using hashes here.

File details

Details for the file lab_1806_vec_db-0.3.4-cp310-none-win_amd64.whl.

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.4-cp310-none-win_amd64.whl
Algorithm Hash digest
SHA256 d1ca8bf714ec3ef313625321c65fcc916fa03fa58555725460bbd6d6c714f64f
MD5 58e5186aa9c4b378eb68b5a26cd86cd2
BLAKE2b-256 bff6e93e550c2c549f718c45b5090083434ffc81b1e910135d15ac33b6cde7f6

See more details on using hashes here.

File details

Details for the file lab_1806_vec_db-0.3.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 b6d69aaa2ab3ab7200c3ad4f5f765326479b1c115c28af8d8cfb9a534626b154
MD5 8dd5c2c7bde11b016b21fb237e1f1d57
BLAKE2b-256 4e54920563e0967e1be57f90e9b68dee6d4e1dbfa184643b35faa4a94fe29b71

See more details on using hashes here.

File details

Details for the file lab_1806_vec_db-0.3.4-cp39-none-win_amd64.whl.

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.4-cp39-none-win_amd64.whl
Algorithm Hash digest
SHA256 2f8341316bee2ca71fda8272f55d4bffa2f9c55175de086ed91f54b3a221869f
MD5 e2a41cdd494d0eee53e183c54993efa5
BLAKE2b-256 327e92b18e3a054330edd9896c7af4ec27a9a875540505cc0408f67abcb9ccd7

See more details on using hashes here.

File details

Details for the file lab_1806_vec_db-0.3.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 c9fe63a9ded66ce238ae1c29ce66f31204d3dfeb10c71580ab05079f040703a8
MD5 8a63909f3783b5decf3612c61fc3d3ef
BLAKE2b-256 05e774086bd706968094c62bac7dd9e6206dbef521f51c179eb5a3e1abeea8d4

See more details on using hashes here.

File details

Details for the file lab_1806_vec_db-0.3.4-cp38-none-win_amd64.whl.

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.4-cp38-none-win_amd64.whl
Algorithm Hash digest
SHA256 3fbded82cfb4cacc33838c94199ff324e76466f0a6c8f2d5af47221a5e1b2aa1
MD5 1eb4e790b1fea3372805cca6d5b58954
BLAKE2b-256 d5da86722fbd9866beeb0f2abb3889d09c9110e104f4445a7f70e06960e5acbf

See more details on using hashes here.

File details

Details for the file lab_1806_vec_db-0.3.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 3d624ca892167c405a792e85c3c2c903e264712ba33eed026a58f6caddeda010
MD5 0ba735377cf78711efa4ac923bc099fc
BLAKE2b-256 a45fda44fe984a99cb420dc3a388c61623f1eda44249d5ecc013fb437e0311e0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page