Skip to content

jkrukowski/SQLiteVec

Repository files navigation

SQLiteVec

Swift bindings for sqlite-vec

Installation

Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code.

  1. Add the following to your Package.swift file:
dependencies: [
    .package(url: "https://github.com/jkrukowski/SQLiteVec", from: "0.0.9")
]
  1. Build your project:
$ swift build

Usage

import SQLiteVec

// initialize the library first
try SQLiteVec.initialize()

// example data
let data: [(index: Int, vector: [Float])] = [
    (1, [0.1, 0.1, 0.1, 0.1]),
    (2, [0.2, 0.2, 0.2, 0.2]),
    (3, [0.3, 0.3, 0.3, 0.3]),
    (4, [0.4, 0.4, 0.4, 0.4]),
    (5, [0.5, 0.5, 0.5, 0.5]),
]
let query: [Float] = [0.3, 0.3, 0.3, 0.3]

// create a database
let db = try Database(.inMemory)

// create a table and insert data
try await db.execute("CREATE VIRTUAL TABLE vec_items USING vec0(embedding float[4])")
for row in data {
    try await db.execute(
        """
            INSERT INTO vec_items(rowid, embedding)
            VALUES (?, ?)
        """,
        params: [row.index, row.vector]
    )
}

// query the embeddings
let result = try await db.query(
    """
        SELECT rowid, distance
        FROM vec_items
        WHERE embedding MATCH ?
        ORDER BY distance
        LIMIT 3
    """,
    params: [query]
)

// print the result
print(result)

It should print the following result:

[
    ["distance": 0.0, "rowid": 3],
    ["distance": 0.19999998807907104, "rowid": 4],
    ["distance": 0.20000001788139343, "rowid": 2]
]

Examples

You can find more examples in the examples directory.

Testing

$ swift test

To test it on docker swift image run:

$ docker build -f Dockerfile -t linuxbuild . && docker run linuxbuild

Code Formatting

This project uses swift-format. To format the code run:

swift format . -i -r --configuration .swift-format

Acknowledgements

This project is based on and uses some of the code from: