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". To make sure smaller is closer, we make cosine_dist = 1 - cosine_similarity.

import os

from lab_1806_vec_db import BareVecTable, VecDB, calc_dist


def test_calc_dist():
    print("\n[Test] calc_dist")
    a = [0.3, 0.4]
    b = [0.4, 0.3]

    # norm_a = sqrt(0.3^2 + 0.4^2) = 0.5
    # norm_b = sqrt(0.4^2 + 0.3^2) = 0.5
    # dot_product = 0.3 * 0.4 + 0.4 * 0.3 = 0.24
    # cosine_dist = 1 - (a dot b) / (|a| * |b|)
    #             = 1 - 0.24 / (0.5 * 0.5) = 0.04

    cosine_dist = calc_dist(a, b)
    print(f"{cosine_dist=}")
    assert abs(cosine_dist - 0.04) < 1e-6, "Test failed"


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.6-cp311-none-win_amd64.whl (516.1 kB view details)

Uploaded CPython 3.11Windows x86-64

lab_1806_vec_db-0.3.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (699.6 kB view details)

Uploaded CPython 3.11manylinux: glibc 2.17+ x86-64

lab_1806_vec_db-0.3.6-cp310-none-win_amd64.whl (516.5 kB view details)

Uploaded CPython 3.10Windows x86-64

lab_1806_vec_db-0.3.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (699.5 kB view details)

Uploaded CPython 3.10manylinux: glibc 2.17+ x86-64

lab_1806_vec_db-0.3.6-cp39-none-win_amd64.whl (516.6 kB view details)

Uploaded CPython 3.9Windows x86-64

lab_1806_vec_db-0.3.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (699.8 kB view details)

Uploaded CPython 3.9manylinux: glibc 2.17+ x86-64

lab_1806_vec_db-0.3.6-cp38-none-win_amd64.whl (516.5 kB view details)

Uploaded CPython 3.8Windows x86-64

lab_1806_vec_db-0.3.6-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (700.0 kB view details)

Uploaded CPython 3.8manylinux: glibc 2.17+ x86-64

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.6-cp311-none-win_amd64.whl
Algorithm Hash digest
SHA256 9be1d34249db34e713a543ca4ceadf1bcf94a283d004976cea0971f1a00b3366
MD5 b2c8645ed5aece55351338260a87eea8
BLAKE2b-256 acf41214f6bb4ec7160337e5331e9b7178b876da949419da528cabf7f7ccc7f4

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 dff8a67b21f9237dc6a103a69ebc5801beb8220d9df160e1eaee7f4312b2429e
MD5 c2bbc075f444c15c9f604367e4fd24d3
BLAKE2b-256 070cdca742f5ea9aefc4d93f1beba47fa2e5b0eeb15919fd94e57f54e538fce7

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.6-cp310-none-win_amd64.whl
Algorithm Hash digest
SHA256 c67b2da9f2a0bd975b51e6b2d82e1a87b96b401ec86ab056f00353a73862b278
MD5 fea222dd99697e9113918c0571d83de3
BLAKE2b-256 314f360d286354297853c264f4b99d8501fcc5f0f2adfbc05e3ba5a0c64fd4a2

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 58b78b561bc2e783c51171f5bf013e112b3c5d677436c0a41b26fcba3c5a151d
MD5 a180c8c028661cfca7b4ea84507b79be
BLAKE2b-256 96cb1967e3e3baf0bc44d40ae2e308349809594bc37df8e7c8f5aa25dc402812

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.6-cp39-none-win_amd64.whl
Algorithm Hash digest
SHA256 841cf9b7786d30a2daf63e24be452a2b6d360fcc2438379d3c790f3fc147b592
MD5 00c8b64102a472a565ea82e6851850a3
BLAKE2b-256 648a223b25db748dd21be256f3e9f0193f5b13ef64cca6ce43dde35ec5a4c33e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 efa06c1a9dcb34e1a6845732395e06ba70f0772a8b1e77a20cceb3a9b4f83085
MD5 f4cc47927b0b9b3224f127ada1f4c425
BLAKE2b-256 5995a0f8368dde395fbb6ff08b12a6747c2374b75ebeb5b678384d963e36eeb1

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.6-cp38-none-win_amd64.whl
Algorithm Hash digest
SHA256 02582d0c0c194b494d8e378a9c10fd46552f400fd5385bb5f96611f8b41c7ebe
MD5 a2c60cd258605707f49c2c2509bca3a6
BLAKE2b-256 e0f2ab239a46d98feea3bfb67cb2bb6383063a8cd71a9b6a8c72596562b3729e

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.6-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 e2699143ea590a190fb790b9d1456bfd85a5d54f7b0043aa8c906c9f4aef17d7
MD5 8c38e0a237e9f5f1a7100fb8ca0ff1dc
BLAKE2b-256 09bfa7c955bd318202de731b7e879dad723037ab8649892e3f8524e4179ea414

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