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

Uploaded CPython 3.11Windows x86-64

lab_1806_vec_db-0.3.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (699.4 kB view details)

Uploaded CPython 3.11manylinux: glibc 2.17+ x86-64

lab_1806_vec_db-0.3.5-cp310-none-win_amd64.whl (516.6 kB view details)

Uploaded CPython 3.10Windows x86-64

lab_1806_vec_db-0.3.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (699.6 kB view details)

Uploaded CPython 3.10manylinux: glibc 2.17+ x86-64

lab_1806_vec_db-0.3.5-cp39-none-win_amd64.whl (516.7 kB view details)

Uploaded CPython 3.9Windows x86-64

lab_1806_vec_db-0.3.5-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (700.0 kB view details)

Uploaded CPython 3.9manylinux: glibc 2.17+ x86-64

lab_1806_vec_db-0.3.5-cp38-none-win_amd64.whl (516.7 kB view details)

Uploaded CPython 3.8Windows x86-64

lab_1806_vec_db-0.3.5-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (700.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.5-cp311-none-win_amd64.whl.

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.5-cp311-none-win_amd64.whl
Algorithm Hash digest
SHA256 4c01f148fa66e63897440f8d8bd3db751d036c4a6bce4b00a6578bbf4f1e0a05
MD5 33c0857b6e4064c21f84a0fd3d9bc277
BLAKE2b-256 8296b1a5d17dc08dc4d3bfedf78cf3eb0cd14deb3397b25a1baf927386e39702

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 8413d9cc16a6773395fdbf978f5c58c5561528cefb5eb7d3f4468b377524673e
MD5 4cbddd8461d5e44c742838dc0a02a68c
BLAKE2b-256 8b8be2a7fea0e7bab7351a32afaa91338044e4d88f9255517e667d18e94bfb90

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.5-cp310-none-win_amd64.whl
Algorithm Hash digest
SHA256 d48a175ab07eb4dd58e6aacf5c7ff173d35e2b772a229bc53fbdf623949fd4c3
MD5 16505afb9389a00d4eb6bf7c2ad0a51c
BLAKE2b-256 bfd295e571a8cfdd0beba568ba08fad4b0615eec7d752a96f85905d8aafeb418

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 21142e7911a32275d52fc802ee05a5ceecee4a7c0e3a130a27ae2c7069cc459c
MD5 43518f8952c2508f6335d5cf4b945b70
BLAKE2b-256 724b87b094a277ea45e3b0ab23806d0f16f8cf29ee968fb1952e8148db61a42c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.5-cp39-none-win_amd64.whl
Algorithm Hash digest
SHA256 2220df6dca475f9dd683fd5f13c120b859ab121098efb080de06eedc76bf5b51
MD5 011c0c9c90c9eb11d5025a2ed82e4c86
BLAKE2b-256 50881d392477ef0431fafc56773b6954c178aa6e8399b7441cd71d7a5afeaa19

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.5-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 ec241887b93bfbfb0775f73f4d4467ac9b98a6d4a39f6430f1adf13dd63b6108
MD5 9dbb2f56cba5a02e4a21aeb3a8c917f1
BLAKE2b-256 d19efbfb7558dd1e918478586c29e656613488380eaafbd6188a34c2642965af

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.5-cp38-none-win_amd64.whl
Algorithm Hash digest
SHA256 2f513c8854770094cdcf6fa31cd25895c8d6d3fd363bced94c30d37920d0a0e0
MD5 9ad12cdc4ed56048fcc8a3239a0e969e
BLAKE2b-256 a61788f99b1ace51ae15eb7cb70379ddae573293ad6334e007aebe614abec888

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for lab_1806_vec_db-0.3.5-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 08fc6da17b404a8c8ab178c9e8c30eb198d1c8ace66f0c4358f6e1932d03dd8c
MD5 60cdacc375973cb5c832e89753838397
BLAKE2b-256 8bc9347428db096a995c575188aa1a4fa0a3d2378c540c53d105cf8310fbb6ef

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