### SQLiteVec Usage Example in Swift Source: https://github.com/jkrukowski/sqlitevec/blob/main/README.md A comprehensive Swift example demonstrating how to initialize the SQLiteVec library, create an in-memory SQLite database, define a virtual table for embeddings, insert vector data, and perform a similarity search query. It also shows how to process and print the query results. ```swift 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) ``` -------------------------------- ### Swift Package Manager Installation Source: https://github.com/jkrukowski/sqlitevec/blob/main/README.md Instructions for adding SQLiteVec as a dependency to your Swift project using the Swift Package Manager. This involves updating your Package.swift file and building the project. ```swift dependencies: [ .package(url: "https://github.com/jkrukowski/SQLiteVec", from: "0.0.9") ] ``` ```bash $ swift build ``` -------------------------------- ### Code Formatting with swift-format Source: https://github.com/jkrukowski/sqlitevec/blob/main/README.md Instructions on how to format the project's code using `swift-format`. This command recursively formats all Swift files in the current directory and its subdirectories, applying configurations from a .swift-format file. ```bash swift format . -i -r --configuration .swift-format ``` -------------------------------- ### Create SQLite Database Instances Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Demonstrates how to create `Database` instances using different location types: in-memory for testing, temporary file-backed for transient data, and persistent storage at a specified URI. It also shows how to open a database in read-only mode. ```swift import SQLiteVec // In-memory database (default) let memoryDb = try Database(.inMemory) // Temporary file-backed database let tempDb = try Database(.temporary) // Persistent database at a specific path let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let dbPath = documentsPath.appendingPathComponent("vectors.db").path let persistentDb = try Database(.uri(dbPath)) // Read-only database let readOnlyDb = try Database(.uri(dbPath), readonly: true) ``` -------------------------------- ### Testing SQLiteVec Source: https://github.com/jkrukowski/sqlitevec/blob/main/README.md Commands for testing the SQLiteVec project. Includes instructions for running tests locally using `swift test` and for building and running tests within a Docker environment using a provided Dockerfile. ```bash $ swift test ``` ```bash $ docker build -f Dockerfile -t linuxbuild . && docker run linuxbuild ``` -------------------------------- ### Initialize SQLiteVec Library Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Initializes the SQLiteVec library by loading the necessary sqlite-vec extension. This function must be called once before any database operations are performed. It throws an error if initialization fails. ```swift import SQLiteVec // Initialize the library - must be called before any database operations do { try SQLiteVec.initialize() print("SQLiteVec initialized successfully") } catch { print("Failed to initialize SQLiteVec: (error)") } ``` -------------------------------- ### Querying SQLiteVec Version and Build Info Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Shows how to retrieve the version and build information of the SQLiteVec extension using Swift. This is useful for debugging and ensuring compatibility. Requires the SQLiteVec library. ```swift import SQLiteVec try SQLiteVec.initialize() let db = try Database(.inMemory) // Get sqlite-vec version if let version = await db.version() { print("sqlite-vec version: (version)") } // Get build/debug information if let buildInfo = await db.buildInfo() { print("Build info: (buildInfo)") } // Check loaded extensions let modules = try await db.query("PRAGMA module_list") let moduleNames = modules.compactMap { $0["name"] as? String } print("Loaded modules: (moduleNames)") // Includes: vec_each, vec0, fts5, etc. ``` -------------------------------- ### Query Data from SQLite Database Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Illustrates how to query data from an SQLite database using the `query` method. This method returns results as an array of dictionaries, where keys are column names and values are converted to appropriate Swift types. It supports parameterized queries and subqueries. ```swift import SQLiteVec try SQLiteVec.initialize() let db = try Database(.inMemory) // Setup table with data try await db.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)") try await db.execute("INSERT INTO users(id, name) VALUES (?, ?)", params: [1, "John"]) try await db.execute("INSERT INTO users(id, name) VALUES (?, ?)", params: [2, "Jane"]) try await db.execute("INSERT INTO users(id, name) VALUES (?, ?)", params: [3, "Jim"]) // Query with parameters let result = try await db.query( "SELECT * FROM users WHERE name = ?", params: ["Jane"] ) // Access results for row in result { let id = row["id"] as? Int let name = row["name"] as? String print("ID: (id ?? 0), Name: (name ?? "")") } // Output: ID: 2, Name: Jane // Subqueries work as expected let filteredResult = try await db.query( """ SELECT * FROM ( SELECT * FROM users WHERE name LIKE 'J%' ) as sub WHERE sub.id = ? """, params: [2] ) print(filteredResult) // [["id": 2, "name": "Jane"]] ``` -------------------------------- ### Perform Vector Similarity Search with SQLiteVec Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Illustrates how to conduct similarity searches using the `MATCH` operator in SQLiteVec. Results are ordered by distance (L2/Euclidean by default), and `LIMIT` or `k = ?` can be used for pagination or KNN. ```swift import SQLiteVec try SQLiteVec.initialize() let db = try Database(.inMemory) // Setup vector table with data try await db.execute("CREATE VIRTUAL TABLE vec_items USING vec0(embedding float[4])") let data: [(id: 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]), ] for item in data { try await db.execute( "INSERT INTO vec_items(rowid, embedding) VALUES (?, ?)", params: [item.id, item.vector] ) } // Query for similar vectors let queryVector: [Float] = [0.3, 0.3, 0.3, 0.3] let results = try await db.query( """ SELECT rowid, distance FROM vec_items WHERE embedding MATCH ? ORDER BY distance LIMIT 3 """, params: [queryVector] ) // Output results for row in results { let rowId = row["rowid"] as? Int ?? 0 let distance = row["distance"] as? Double ?? 0 print("Row \(rowId): distance = \(distance)") } // Output: // Row 3: distance = 0.0 // Row 4: distance = 0.19999998807907104 // Row 2: distance = 0.20000001788139343 ``` -------------------------------- ### Execute SQL Statements with Parameters Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Shows how to execute SQL statements that modify the database using the `execute` method. It supports parameterized queries with automatic type binding for various Swift types, including arrays of floats and integers. It also demonstrates retrieving the last inserted row ID and the count of modified rows. ```swift import SQLiteVec try SQLiteVec.initialize() let db = try Database(.inMemory) // Create a regular table try await db.execute( """ CREATE TABLE users ( id INTEGER PRIMARY KEY, name TEXT NOT NULL UNIQUE ) """ ) // Insert with parameters try await db.execute( "INSERT INTO users(id, name) VALUES (?, ?)", params: [1, "John"] ) try await db.execute( "INSERT INTO users(id, name) VALUES (?, ?)", params: [2, "Jane"] ) // Get the last inserted row ID let lastId = await db.lastInsertRowId print("Last inserted ID: (lastId)") // Output: Last inserted ID: 2 // Get number of modified rows let modifiedCount = await db.modifiedRowsCount print("Modified rows: (modifiedCount)") // Output: Modified rows: 1 ``` -------------------------------- ### Vector Operations with SQLiteVec Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Demonstrates various vector arithmetic and manipulation functions provided by SQLiteVec, including addition, subtraction, and binary quantization. It also shows type conversions like vec_f32 and vec_int8. Requires the SQLiteVec library. ```swift import SQLiteVec try SQLiteVec.initialize() let db = try Database(.inMemory) // Vector addition let addResult = try await db.query( "SELECT vec_add(?, ?) as result", params: [ [1.0, 2.0, 3.0, 4.0] as [Float], [0.5, 0.5, 0.5, 0.5] as [Float] ] ) let addData = addResult[0]["result"] as! Data let addedVector: [Float] = addData.toArray() print("Added: (addedVector)") // [1.5, 2.5, 3.5, 4.5] // Vector subtraction let subResult = try await db.query( "SELECT vec_sub(?, ?) as result", params: [ [1.0, 2.0, 3.0, 4.0] as [Float], [0.5, 0.5, 0.5, 0.5] as [Float] ] ) let subData = subResult[0]["result"] as! Data let subtractedVector: [Float] = subData.toArray() print("Subtracted: (subtractedVector)") // [0.5, 1.5, 2.5, 3.5] // Binary quantization (converts float vectors to compact binary representation) let quantizeResult = try await db.query( "SELECT vec_quantize_binary(?) as quantized", params: [[-0.73, -0.80, 0.12, -0.73, 0.79, -0.11, 0.23, 0.97] as [Float]] ) let quantizedData = quantizeResult[0]["quantized"] as! Data print("Quantized bytes: (quantizedData.bytes)") // [212] // Int8 vector operations let int8Result = try await db.query( "SELECT vec_add(vec_int8(?), vec_int8(?)) as result", params: [ [0, 1, 2, 3] as [Int8], [5, 6, 7, 8] as [Int8] ] ) let int8Data = int8Result[0]["result"] as! Data let int8Vector: [Int8] = int8Data.toArray() print("Int8 added: (int8Vector)") // [5, 7, 9, 11] ``` -------------------------------- ### Joining Vector and Text Tables with SQLiteVec Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Illustrates a common pattern of joining a virtual vector table (embeddings) with a regular table (texts) in SQLite using SQLiteVec. This enables enriched search results by retrieving text metadata alongside vector similarity. Requires SQLiteVec. ```swift import SQLiteVec try SQLiteVec.initialize() let db = try Database(.inMemory) // Create tables for text content and embeddings try await db.execute( """ CREATE TABLE IF NOT EXISTS texts( id INTEGER PRIMARY KEY, text TEXT ) """ ) try await db.execute( """ CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0( id INTEGER PRIMARY KEY, embedding float[4] ) """ ) // Insert sample data let items = [ ("Machine learning basics", [0.9, 0.1, 0.2, 0.1] as [Float]), ("Swift programming guide", [0.1, 0.9, 0.1, 0.2] as [Float]), ("iOS app development", [0.2, 0.8, 0.3, 0.1] as [Float]), ("Database optimization", [0.3, 0.2, 0.1, 0.9] as [Float]), ] for (text, vector) in items { try await db.execute("INSERT INTO texts(text) VALUES(?)", params: [text]) let rowId = await db.lastInsertRowId try await db.execute( "INSERT INTO embeddings(id, embedding) VALUES (?, ?)", params: [rowId, vector] ) } // Query with JOIN to get text alongside similarity results let queryVector: [Float] = [0.15, 0.85, 0.2, 0.15] let results = try await db.query( """ SELECT embeddings.id, distance, text FROM embeddings LEFT JOIN texts ON texts.id = embeddings.id WHERE embedding MATCH ? AND k = ? ORDER BY distance """, params: [queryVector, 3] ) for row in results { let text = row["text"] as? String ?? "" let distance = row["distance"] as? Double ?? 0 print("\(text): \(distance)") } // Output: // Swift programming guide: 0.07... // iOS app development: 0.12... // Machine learning basics: 1.38... ``` -------------------------------- ### Manage SQLiteVec Operations with Transactions Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Demonstrates how to use transactions to group multiple database operations atomically in SQLiteVec. If any operation within a transaction fails, all changes are rolled back. Supports `.deferred`, `.immediate`, and `.exclusive` modes. ```swift import SQLiteVec try SQLiteVec.initialize() let db = try Database(.inMemory) try await db.execute("CREATE TABLE texts (id INTEGER PRIMARY KEY, text TEXT)") try await db.execute("CREATE VIRTUAL TABLE embeddings USING vec0(id INTEGER PRIMARY KEY, embedding float[4])") // Insert multiple items in a single transaction let texts = ["Hello world", "Swift programming", "Vector search"] let vectors: [[Float]] = [ [0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.2, 0.3, 0.4, 0.5] ] try await db.transaction(.immediate) { for (index, text) in texts.enumerated() { try await db.execute( "INSERT INTO texts(text) VALUES(?)", params: [text] ) let rowId = await db.lastInsertRowId try await db.execute( "INSERT INTO embeddings(id, embedding) VALUES (?, ?)", params: [rowId, vectors[index]] ) } } print("Transaction completed successfully") ``` -------------------------------- ### Create Vector Tables with SQLiteVec Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Demonstrates how to create virtual tables for storing vector embeddings using the `vec0` module. Supports different data types like float[N], int8[N], and bit[N] for embeddings, with options for primary keys. ```swift import SQLiteVec try SQLiteVec.initialize() let db = try Database(.inMemory) // Create a vector table with 4-dimensional float embeddings try await db.execute( "CREATE VIRTUAL TABLE vec_items USING vec0(embedding float[4])" ) // Create a vector table with 512-dimensional embeddings and primary key try await db.execute( """ CREATE VIRTUAL TABLE embeddings USING vec0( id INTEGER PRIMARY KEY, embedding float[512] ) """ ) // Create a table with int8 vectors for quantized embeddings try await db.execute( "CREATE VIRTUAL TABLE quantized_vecs USING vec0(embedding int8[128])" ) ``` -------------------------------- ### Insert Vector Embeddings into SQLiteVec Tables Source: https://context7.com/jkrukowski/sqlitevec/llms.txt Shows how to insert vector embeddings into a SQLiteVec table using standard SQL INSERT statements. Float arrays are passed directly and automatically converted for storage. ```swift import SQLiteVec try SQLiteVec.initialize() let db = try Database(.inMemory) try await db.execute("CREATE VIRTUAL TABLE vec_items USING vec0(embedding float[4])") // Sample embedding data let embeddings: [(id: 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]), ] // Insert embeddings for item in embeddings { try await db.execute( "INSERT INTO vec_items(rowid, embedding) VALUES (?, ?)", params: [item.id, item.vector] ) } print("Inserted \(embeddings.count) embeddings") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.