### Quickstart Example Source: https://github.com/unum-cloud/usearch/blob/main/java/README.md A basic example demonstrating how to initialize an index, add a vector, and perform a search using USearch in Java. ```APIDOC ## Quickstart Example ### Description A basic example demonstrating how to initialize an index, add a vector, and perform a search using USearch in Java. ### Method ```java import cloud.unum.usearch.Index; public class Main { public static void main(String[] args) { try (Index index = new Index.Config() .metric(Index.Metric.COSINE) // Or "cos" .quantization(Index.Quantization.FLOAT32) // Or "f32" .dimensions(3) .capacity(100) .build()) { // Add to Index float[] vector = {0.1f, 0.2f, 0.3f}; index.add(42L, vector); // Search long[] keys = index.search(new float[]{0.1f, 0.2f, 0.3f}, 10); for (long key : keys) { System.out.println("Found key: " + key); } } catch (Exception e) { e.printStackTrace(); } } } ``` ``` -------------------------------- ### USearch Go Quickstart Example Source: https://github.com/unum-cloud/usearch/blob/main/golang/README.md A basic Go program demonstrating how to create a USearch index, add vectors, and perform a search. Remember to call `Reserve(capacity)` before the first write operation. ```go package main import ( "fmt" usearch "github.com/unum-cloud/usearch/golang" ) func main() { // Create Index vectorSize := 3 vectorsCount := 100 conf := usearch.DefaultConfig(uint(vectorSize)) conf.Quantization = usearch.F32 // or BF16, F16, E5M2, E4M3, E3M2, E2M3, I8, U8 index, err := usearch.NewIndex(conf) if err != nil { panic("Failed to create Index") } defer index.Destroy() // Reserve capacity and configure internal threading err = index.Reserve(uint(vectorsCount)) _ = index.ChangeThreadsAdd(uint(runtime.NumCPU())) _ = index.ChangeThreadsSearch(uint(runtime.NumCPU())) for i := 0; i < vectorsCount; i++ { err = index.Add(usearch.Key(i), []float32{float32(i), float32(i + 1), float32(i + 2)}) if err != nil { panic("Failed to add") } } // Search keys, distances, err := index.Search([]float32{0.0, 1.0, 2.0}, 3) if err != nil { panic("Failed to search") } fmt.Println(keys, distances) } ``` -------------------------------- ### Initialize and Use USearch Index Source: https://github.com/unum-cloud/usearch/blob/main/python/README.md Quickstart example demonstrating index initialization with custom parameters and performing add/search operations. Ensure vectors match the index's dimensionality. ```python import numpy as np from usearch.index import Index, Matches index = Index( ndim=3, # Define the number of dimensions in input vectors metric='cos', # Choose 'l2sq', 'ip', 'haversine' or other metric, default = 'cos' dtype='bf16', # Quantize to 'f16', 'e5m2', 'e4m3', 'e3m2', 'e2m3', 'u8', 'i8', 'b1'..., default = None connectivity=16, # How frequent should the connections in the graph be, optional expansion_add=128, # Control the recall of indexing, optional expansion_search=64, # Control the quality of search, optional ) vector = np.array([0.2, 0.6, 0.4]) index.add(42, vector) matches: Matches = index.search(vector, 10) assert len(index) == 1 assert len(matches) == 1 assert matches[0].key == 42 assert matches[0].distance <= 0.001 assert np.allclose(index[42], vector) ``` -------------------------------- ### Setup Gradle Environment Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Commands to install necessary tools (zip, SDKMAN, Java, Gradle) for the Java build environment. ```sh sudo apt-get install zip curl -s "https://get.sdkman.io" | bash sdk install java sdk install gradle ``` -------------------------------- ### LibraryFunctionLoad Examples Source: https://github.com/unum-cloud/usearch/blob/main/wolfram/README.md Demonstrates loading USearch functions into Wolfram Mathematica using LibraryFunctionLoad and provides a quickstart example for index creation, data addition, and searching. ```APIDOC ## LibraryFunctionLoad ### Description Loads functions from the USearch shared library into Wolfram Mathematica. ### Functions - **IndexCreate**: Creates a new USearch index. - **IndexSave**: Saves an existing USearch index to a file. - **IndexLoad**: Loads a USearch index from a file. - **IndexView**: Views the contents of a USearch index file. - **IndexDestroy**: Destroys and frees memory associated with a USearch index. - **IndexSize**: Returns the number of vectors in the index. - **IndexConnectivity**: Returns the connectivity of the index. - **IndexDimensions**: Returns the dimensionality of the vectors in the index. - **IndexCapacity**: Returns the capacity of the index. - **IndexAdd**: Adds a vector to the index. - **IndexSearch**: Searches the index for vectors similar to a query vector. ### Parameters for IndexCreate - **metric** (UTF8String): The distance metric to use (e.g., "cos", "ip", "l2sq"). - **quantization** (UTF8String): The quantization method (e.g., "f64", "f32", "f16", "i8", "b1x8"). - **dimensions** (Integer): The dimensionality of the vectors. - **capacity** (Integer): The maximum number of vectors the index can hold. - **expansion_add** (Integer): Expansion factor for adding vectors. - **expansion_search** (Integer): Expansion factor for searching. ### Parameters for IndexAdd - **index_handle** (Integer): The handle of the index to add to. - **vector_id** (Integer): The unique identifier for the vector. - **vector** ({Real, 1}): The vector to add, represented as a rank-1 real tensor. ### Parameters for IndexSearch - **index_handle** (Integer): The handle of the index to search. - **query_vector** ({Real, 1}): The query vector. - **limit** (Integer): The maximum number of results to return. ### Return Values - **IndexCreate**: Returns an Integer handle representing the created index. - **IndexSave, IndexLoad, IndexView, IndexDestroy, IndexAdd**: Returns "Void". - **IndexSize, IndexConnectivity, IndexDimensions, IndexCapacity**: Returns an Integer. - **IndexSearch**: Returns a rank-1 integer tensor ({Integer, 1}) containing the keys of the nearest neighbors. ### Quickstart Example ```wolfram lib = If[$OperatingSystem === "Windows", "build\\usearchWFM.dll", If[$OperatingSystem === "MacOSX", "build/usearchWFM.dylib", "build/libusearchWFM.so"] ]; IndexCreate = LibraryFunctionLoad[lib, "IndexCreate", {"UTF8String", "UTF8String", Integer, Integer, Integer, Integer, Integer}, Integer]; IndexSave = LibraryFunctionLoad[lib, "IndexSave", {Integer, "UTF8String"}, "Void"]; IndexLoad = LibraryFunctionLoad[lib, "IndexLoad", {Integer, "UTF8String"}, "Void"]; IndexView = LibraryFunctionLoad[lib, "IndexView", {Integer, "UTF8String"}, "Void"]; IndexDestroy = LibraryFunctionLoad[lib, "IndexDestroy", {Integer}, "Void"]; IndexSize = LibraryFunctionLoad[lib, "IndexSize", {Integer}, Integer]; IndexConnectivity= LibraryFunctionLoad[lib, "IndexConnectivity", {Integer}, Integer]; IndexDimensions = LibraryFunctionLoad[lib, "IndexDimensions", {Integer}, Integer]; IndexCapacity = LibraryFunctionLoad[lib, "IndexCapacity", {Integer}, Integer]; IndexAdd = LibraryFunctionLoad[lib, "IndexAdd", {Integer, Integer, {Real, 1}}, "Void"]; IndexSearch = LibraryFunctionLoad[lib, "IndexSearch", {Integer, {Real, 1}, Integer}, {Integer, 1}]; (* Create an index: metric, quantization, dimensions, capacity, connectivity, expansion_add, expansion_search *) idx = IndexCreate["cos", "f32", 3, 10, 16, 64, 64]; (* Add a vector and search *) vec = {0.2, 0.6, 0.4}; IndexAdd[idx, 42, vec]; keys = IndexSearch[idx, vec, 5]; (* Save, load/view, and cleanup *) IndexSave[idx, "index.usearch"]; IndexLoad[idx, "index.usearch"]; (* or IndexView[idx, "index.usearch"] *) IndexDestroy[idx]; ``` ``` -------------------------------- ### Run USearch Go Example Source: https://github.com/unum-cloud/usearch/blob/main/golang/README.md Command to compile and run the Go example file. ```bash go run example.go ``` -------------------------------- ### Install USearch Python Bindings Locally Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Install USearch locally from source using uv or pip. Ensure you activate the virtual environment before installation. ```sh uv venv --python 3.11 # or your preferred Python version source .venv/bin/activate # to activate the virtual environment uv pip install -e . --force-reinstall # to build locally from source ``` ```sh pip install -e . --force-reinstall ``` -------------------------------- ### Install and Run Swift Format Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Commands to install Swift format using Homebrew and apply it recursively to all files in the project. ```bash brew install swift-format swift-format . -i -r ``` -------------------------------- ### USearch Index Introspection Methods Source: https://github.com/unum-cloud/usearch/blob/main/golang/README.md Go code examples for inspecting the properties of a USearch index, such as dimensions, size, capacity, and checking for key existence. Also includes how to get the library version. ```go dimensions, _ := index.Dimensions() // Get the number of dimensions size, _ := index.Len() // Get the number of vectors capacity, _ := index.Capacity() // Get the capacity containsKey, _ := index.Contains(42) // Check if a key is in the index count, _ := index.Count(42) // Get the count of vectors for a key (multi-vector indexes) version := usearch.Version() // Get the library version string ``` -------------------------------- ### Install USearch on Windows Source: https://github.com/unum-cloud/usearch/blob/main/golang/README.md Run the winlibinstaller.bat script from the main repository in the folder where you will run `go run`. This script installs the USearch library and includes it in the same folder. ```bash .\usearch\winlibinstaller.bat ``` -------------------------------- ### Install Wolfram Engine Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Install the Wolfram Engine using Homebrew. This is a prerequisite for using Wolfram-related features. ```sh brew install --cask wolfram-engine ``` -------------------------------- ### Install Build Dependencies Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Installs necessary build tools and libraries for Ubuntu and macOS. ```sh sudo apt-get update && sudo apt-get install cmake build-essential libjemalloc-dev # Ubuntu brew install libomp llvm # macOS ``` -------------------------------- ### Install USearch for Node.js Source: https://github.com/unum-cloud/usearch/blob/main/javascript/README.md Install the USearch library using npm for Node.js environments. ```sh npm install usearch ``` -------------------------------- ### Install Node Version Manager and Node.js Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Install NVM and a specific Node.js version (e.g., 20) for building JavaScript bindings. ```sh wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash nvm install 20 ``` -------------------------------- ### Install Numba Source: https://github.com/unum-cloud/usearch/blob/main/python/README.md Install the Numba library using pip. ```shell pip install numba ``` -------------------------------- ### USearch Rust SDK Quickstart Source: https://github.com/unum-cloud/usearch/blob/main/rust/README.md Initialize a USearch index with specified options, reserve capacity, add vectors, and perform a search. Ensure dimensions match the metric and data. ```rust use usearch::{Index, IndexOptions, MetricKind, ScalarKind, new_index}; let options = IndexOptions { dimensions: 3, // necessary for most metric kinds metric: MetricKind::IP, // or ::L2sq, ::Cos ... quantization: ScalarKind::BF16, // or ::F32, ::F16, ::E5M2, ::E4M3, ::E3M2, ::E2M3, ::U8, ::I8, ::B1x8 ... connectivity: 0, // zero for auto expansion_add: 0, // zero for auto expansion_search: 0, // zero for auto }; let index: Index = new_index(&options).unwrap(); assert!(index.reserve(10).is_ok()); assert!(index.capacity() >= 10); assert!(index.connectivity() != 0); assert_eq!(index.dimensions(), 3); assert_eq!(index.size(), 0); let first: [f32; 3] = [0.2, 0.1, 0.2]; let second: [f32; 3] = [0.2, 0.1, 0.2]; assert!(index.add(42, &first).is_ok()); assert!(index.add(43, &second).is_ok()); assert_eq!(index.size(), 2); // Read back the tags let results = index.search(&first, 10).unwrap(); assert_eq!(results.keys.len(), 2); ``` -------------------------------- ### Quickstart: Create and Use a USearch Index in Objective-C Source: https://github.com/unum-cloud/usearch/blob/main/objc/README.md Demonstrates creating an index with specified metrics and dimensions, reserving space, adding vectors of different precisions, and performing searches. Note that vectors are cast to float32 during addition and search. ```objectivec #import "USearchIndex.h" // Creating an index with specific parameters USearchIndex *index = [USearchIndex make:USearchMetricIP dimensions:3 connectivity:10 quantization:USearchScalarF32]; // Reserving space for vectors [index reserve:10]; // Adding a double-precision vector (will be cast to float32) double doubleVector[3] = {0.1, 0.2, 0.3}; [index addDouble:44 vector:doubleVector]; // Searching with an integer vector (will be cast to float32) int intQueryVector[3] = {1, 2, 3}; UInt32 count = 5; USearchKey keys[count]; float distances[count]; [index searchSingle:(Float32 const *)intQueryVector count:count keys:keys distances:distances]; // Adding a half-precision vector (requires casting to specified quantization type) void *halfVector = ...; // Assume half-precision data [index addHalf:45 vector:halfVector]; ``` -------------------------------- ### Install USearch Python Package Source: https://github.com/unum-cloud/usearch/blob/main/python/README.md Install the USearch Python package using pip. ```sh pip install usearch ``` -------------------------------- ### Go Mod File Example Source: https://github.com/unum-cloud/usearch/blob/main/golang/README.md Example go.mod file for a USearch Go project. Ensure you specify the correct Go version. ```go module usearch_example go ``` -------------------------------- ### Quickstart USearch Index in C# Source: https://github.com/unum-cloud/usearch/blob/main/csharp/README.md Initialize a USearch index with specified metric, quantization, dimensions, and optional parameters. Add a single vector and perform a search. ```csharp using System.Diagnostics; using Cloud.Unum.USearch; using var index = new USearchIndex( metricKind: MetricKind.Cos, // Choose cosine metric quantization: ScalarKind.Float32, // or Float64, BFloat16, Float16, E5M2, E4M3, E3M2, E2M3, Int8, UInt8 dimensions: 3, // Define the number of dimensions in input vectors connectivity: 16, // How frequent should the connections in the graph be, optional expansionAdd: 128, // Control the recall of indexing, optional expansionSearch: 64 // Control the quality of search, optional ); var vector = new float[] { 0.2f, 0.6f, 0.4f }; index.Add(42, vector); int matches = index.Search(vector, 10, out ulong[] keys, out float[] distances); Trace.Assert(index.Size() == 1); Trace.Assert(matches == 1); Trace.Assert(keys[0] == 42); Trace.Assert(distances[0] <= 0.001f); ``` -------------------------------- ### USearch Java Quickstart Source: https://github.com/unum-cloud/usearch/blob/main/java/README.md Demonstrates basic USearch index creation, adding a vector, and performing a search. Uses COSINE metric and FLOAT32 quantization. Ensure the index is closed properly using try-with-resources. ```java import cloud.unum.usearch.Index; public class Main { public static void main(String[] args) { try (Index index = new Index.Config() .metric(Index.Metric.COSINE) // Or "cos" .quantization(Index.Quantization.FLOAT32) // Or "f32" .dimensions(3) .capacity(100) .build()) { // Add to Index float[] vector = {0.1f, 0.2f, 0.3f}; index.add(42L, vector); // Search long[] keys = index.search(new float[]{0.1f, 0.2f, 0.3f}, 10); for (long key : keys) { System.out.println("Found key: " + key); } } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Quickstart: Create, Add, and Search Vectors Source: https://github.com/unum-cloud/usearch/blob/main/javascript/README.md Initialize an index, add a vector with a BigInt key, and perform a search. Asserts are used to verify index size, keys, and distances. The vector is then removed. ```js const assert = require('node:assert'); const usearch = require('usearch'); const index = new usearch.Index({ metric: 'l2sq', connectivity: 16, dimensions: 3 }); index.add(42n, new Float32Array([0.2, 0.6, 0.4])); const results = index.search(new Float32Array([0.2, 0.6, 0.4]), 10); assert(index.size() === 1); assert.deepEqual(results.keys, new BigUint64Array([42n])); assert.deepEqual(results.distances, new Float32Array([0])); index.remove(42n); ``` -------------------------------- ### Basic Index Creation and Usage Source: https://github.com/unum-cloud/usearch/blob/main/README.md Demonstrates the fundamental steps of creating a USearch index, adding vectors, and performing a search. Ensure the 'usearch' library is installed. ```python import numpy as np from usearch.index import Index index = Index(ndim=3) # Default settings for 3D vectors vector = np.array([0.2, 0.6, 0.4]) # Can be a matrix for batch operations index.add(42, vector) # Add one or many vectors in parallel matches = index.search(vector, 10) # Find 10 nearest neighbors assert matches[0].key == 42 assert matches[0].distance <= 0.001 assert np.allclose(index[42], vector, atol=0.1) # Ensure high tolerance in mixed-precision comparisons ``` -------------------------------- ### Install USearch with SQLite Extensions Source: https://github.com/unum-cloud/usearch/blob/main/sqlite/README.md Install the USearch Python package, which includes the SQLite extensions, using pip. ```sh pip install usearch # brings sqlite extensions ``` -------------------------------- ### Get USearch Go Package Source: https://github.com/unum-cloud/usearch/blob/main/golang/README.md Command to fetch the USearch Go package using `go get`. ```bash go get github.com/unum-cloud/usearch/golang ``` -------------------------------- ### Install USearch via Swift Package Manager Source: https://github.com/unum-cloud/usearch/blob/main/objc/README.md Add the USearch package to your project's dependencies in Package.swift to install the SDK. ```swift dependencies: [ .package(url: "https://github.com/unum-cloud/USearch", .upToNextMajor(from: "2.0.0")) ] ``` -------------------------------- ### Install USearch C# Package Source: https://github.com/unum-cloud/usearch/blob/main/csharp/README.md Add the USearch NuGet package to your C# project using the dotnet CLI. ```sh dotnet add package Cloud.Unum.USearch ``` -------------------------------- ### Install WASI SDK Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Download and extract the WASI SDK for WebAssembly development. This is required for compiling C/C++ code to WebAssembly. ```bash export WASI_VERSION=21 export WASI_VERSION_FULL=${WASI_VERSION}.0 wget https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-${WASI_VERSION}/wasi-sdk-${WASI_VERSION_FULL}-linux.tar.gz tar xvf wasi-sdk-${WASI_VERSION_FULL}-linux.tar.gz ``` -------------------------------- ### Wolfram Mathematica USearch Quickstart Source: https://github.com/unum-cloud/usearch/blob/main/wolfram/README.md Loads the USearch library and binds functions for index creation, saving, loading, viewing, destruction, size, connectivity, dimensions, capacity, adding vectors, and searching. Vectors are passed as rank-1 real tensors. ```wolfram lib = If[$OperatingSystem === "Windows", "build\usearchWFM.dll", If[$OperatingSystem === "MacOSX", "build/usearchWFM.dylib", "build/libusearchWFM.so"]]; IndexCreate = LibraryFunctionLoad[lib, "IndexCreate", {"UTF8String", "UTF8String", Integer, Integer, Integer, Integer, Integer}, Integer]; IndexSave = LibraryFunctionLoad[lib, "IndexSave", {Integer, "UTF8String"}, "Void"]; IndexLoad = LibraryFunctionLoad[lib, "IndexLoad", {Integer, "UTF8String"}, "Void"]; IndexView = LibraryFunctionLoad[lib, "IndexView", {Integer, "UTF8String"}, "Void"]; IndexDestroy = LibraryFunctionLoad[lib, "IndexDestroy", {Integer}, "Void"]; IndexSize = LibraryFunctionLoad[lib, "IndexSize", {Integer}, Integer]; IndexConnectivity= LibraryFunctionLoad[lib, "IndexConnectivity", {Integer}, Integer]; IndexDimensions = LibraryFunctionLoad[lib, "IndexDimensions", {Integer}, Integer]; IndexCapacity = LibraryFunctionLoad[lib, "IndexCapacity", {Integer}, Integer]; IndexAdd = LibraryFunctionLoad[lib, "IndexAdd", {Integer, Integer, {Real, 1}}, "Void"]; IndexSearch = LibraryFunctionLoad[lib, "IndexSearch", {Integer, {Real, 1}, Integer}, {Integer, 1}]; (* Create an index: metric, quantization, dimensions, capacity, connectivity, expansion_add, expansion_search *) idx = IndexCreate["cos", "f32", 3, 10, 16, 64, 64]; (* Add a vector and search *) vec = {0.2, 0.6, 0.4}; IndexAdd[idx, 42, vec]; keys = IndexSearch[idx, vec, 5]; (* Save, load/view, and cleanup *) IndexSave[idx, "index.usearch"]; IndexLoad[idx, "index.usearch"]; (* or IndexView[idx, "index.usearch"] *) IndexDestroy[idx]; ``` -------------------------------- ### Install USearch with CMake Source: https://github.com/unum-cloud/usearch/blob/main/cpp/README.md Fetch and make USearch available in your C++ project using CMake's FetchContent module. ```cmake FetchContent_Declare(usearch GIT_REPOSITORY https://github.com/unum-cloud/USearch.git) FetchContent_MakeAvailable(usearch) ``` -------------------------------- ### Install USearch on macOS Source: https://github.com/unum-cloud/usearch/blob/main/golang/README.md Download and unpack the zip archive, then move the USearch library and include file to their respective system directories. Replace placeholders with your specific release tag, architecture, and USearch version. ```bash wget https://github.com/unum-cloud/USearch/releases/download//usearch_macos__.zip unzip usearch_macos__.zip sudo mv libusearch_c.dylib /usr/local/lib && sudo mv usearch.h /usr/local/include ``` -------------------------------- ### Install USearch on Linux Source: https://github.com/unum-cloud/usearch/blob/main/golang/README.md Download and install the Debian package for USearch on Linux. Ensure you replace the placeholders with your specific release tag, architecture, and USearch version. ```bash wget https://github.com/unum-cloud/USearch/releases/download//usearch_linux__.deb dpkg -i usearch_linux__.deb ``` -------------------------------- ### Lint Python Code with Ruff Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Install linting dependencies using `uv` and run Ruff for code formatting and style checks. ```sh uv pip install -e . --group lint ruff --format=github python ``` -------------------------------- ### Test USearch JavaScript Bindings Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Install TypeScript, compile C++ bindings, generate JavaScript from TypeScript, and run the test suite using npm. ```sh npm install -g typescript # Install TypeScript globally ``` ```sh npm install # Compile `javascript/lib.cpp` ``` ```sh npm run build-js # Generate JS from TS ``` ```sh npm test # Run the test suite ``` -------------------------------- ### Compile USearch to WebAssembly Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Compile USearch to WebAssembly using emscripten, configuring memory and running tests. Includes instructions for installing emscripten. ```sh emcmake cmake -B build -DCMAKE_CXX_FLAGS="${CMAKE_CXX_FLAGS} -s TOTAL_MEMORY=64MB" && emmake make -C build node build/usearch.test.js ``` ```sh git clone https://github.com/emscripten-core/emsdk.git && ./emsdk/emsdk install latest && ./emsdk/emsdk activate latest && source ./emsdk/emsdk_env.sh ``` -------------------------------- ### Include CMake Modules and Set Configuration Paths Source: https://github.com/unum-cloud/usearch/blob/main/CMakeLists.txt Manages CMake module paths and sets up installation directories and configuration file paths for the USearch project. ```cmake # Includes set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH}) include(ExternalProject) # Configuration include(GNUInstallDirs) set(USEARCH_TARGET_NAME ${PROJECT_NAME}) set(USEARCH_CONFIG_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/cmake/${PROJECT_NAME}" CACHE INTERNAL "" ) set(USEARCH_INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_INCLUDEDIR}") set(USEARCH_TARGETS_EXPORT_NAME "${PROJECT_NAME}Targets") set(USEARCH_CMAKE_CONFIG_TEMPLATE "cmake/config.cmake.in") set(USEARCH_CMAKE_CONFIG_DIR "${CMAKE_CURRENT_BINARY_DIR}") set(USEARCH_CMAKE_VERSION_CONFIG_FILE "${USEARCH_CMAKE_CONFIG_DIR}/${PROJECT_NAME}ConfigVersion.cmake") set(USEARCH_CMAKE_PROJECT_CONFIG_FILE "${USEARCH_CMAKE_CONFIG_DIR}/${PROJECT_NAME}Config.cmake") set(USEARCH_CMAKE_PROJECT_TARGETS_FILE "${USEARCH_CMAKE_CONFIG_DIR}/${PROJECT_NAME}Targets.cmake") set(USEARCH_PKGCONFIG_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/pkgconfig") ``` -------------------------------- ### Configure Docker for AWS Lambda Node.js Bindings Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Set up a Dockerfile for AWS Lambda, installing build tools and configuring environment variables for USearch compilation. ```Dockerfile FROM public.ecr.aws/lambda/nodejs:18-x86_64 RUN npm init -y RUN yum install tar git python3 cmake gcc-c++ -y && yum groupinstall "Development Tools" -y # Assuming AWS Linux 2 uses old compilers: ENV USEARCH_USE_NUMKONG 1 ENV NK_TARGET_HASWELL 1 ENV NK_TARGET_SKYLAKE 0 ENV NK_TARGET_ICELAKE 0 ENV NK_TARGET_SAPPHIRE 0 ENV NK_TARGET_NEON 1 ENV NK_TARGET_SVE 0 # For specific PR: # RUN npm install --build-from-source unum-cloud/USearch#pull/302/head # For specific version: # RUN npm install --build-from-source usearch@2.8.8 RUN npm install --build-from-source usearch ``` -------------------------------- ### USearch Integration in a SwiftUI Application Source: https://github.com/unum-cloud/usearch/blob/main/swift/README.md Example of initializing a USearch index within a SwiftUI application's App struct. Note the use of `let _ =` to ignore return values where appropriate. ```swift import SwiftUI import USearch @main struct USearchMobileApp: App { var body: some Scene { WindowGroup { let index = USearchIndex.make(metric: .IP, dimensions: 2, connectivity: 16, quantization: .F32) // or .bf16, .f16, .e5m2, .e4m3, .e3m2, .e2m3, .u8, .i8 let _ = index.reserve(10) let coordinates: Array = [40.177200, 44.503490] let _ = index.add(key: 10, vector: coordinates) VStack { Text("USearch index contains \(index.count) vectors") Spacer() } } } } ``` -------------------------------- ### Gradle Installation and USearch JAR Download Source: https://github.com/unum-cloud/usearch/blob/main/java/README.md Configures Gradle to download the USearch JAR from GitHub releases and include it as a project dependency. Ensure the 'lib' directory exists for the JAR download. ```groovy repositories { mavenCentral() // Custom repository for USearch JAR flatDir { dirs 'lib' } } // Task to download USearch JAR from GitHub releases task downloadUSearchJar { doLast { def usearchVersion = '2.25.2' def usearchUrl = "https://github.com/unum-cloud/USearch/releases/download/v${usearchVersion}/usearch-${usearchVersion}.jar" def usearchFile = file("lib/usearch-${usearchVersion}.jar") usearchFile.parentFile.mkdirs() if (!usearchFile.exists()) { new URL(usearchUrl).withInputStream { i -> usearchFile.withOutputStream { it << i } } println "Downloaded USearch JAR: ${usearchFile.name}" } } } // Make compilation depend on downloading USearch compileJava.dependsOn downloadUSearchJar dependencies { // USearch JAR from local lib directory (downloaded automatically) implementation name: 'usearch', version: '2.25.2', ext: 'jar' } ``` -------------------------------- ### Install Cppyy Source: https://github.com/unum-cloud/usearch/blob/main/python/README.md Install Cppyy using Conda. ```shell conda install -c conda-forge cppyy ``` -------------------------------- ### Initialize and Use USearch Index in C Source: https://github.com/unum-cloud/usearch/blob/main/c/README.md Demonstrates the basic workflow of initializing a USearch index, adding a vector, performing a search, and cleaning up resources. Ensure proper error handling and resource management. ```c #include // For printing. #include // For assertions! #include // For the win 🚀 int main() { // Construct: size_t dimensions = 128; usearch_error_t error = NULL; usearch_init_options_t opts = { .metric_kind = usearch_metric_cos_k, .scalar_kind = usearch_scalar_f16_k, // or f32_k, bf16_k, e5m2_k, e4m3_k, e3m2_k, e2m3_k, i8_k, u8_k .dimensions = dimensions, .expansion_add = 0, // for defaults .expansion_search = 0 // for defaults }; usearch_index_t index = usearch_init(&opts, &error); size_t vectors_count = 1000; usearch_reserve(index, vectors_count, &error); if (error) goto cleanup; // Populate: float vector[dimensions]; // don't forget to fill the vector with data usearch_add(index, 42, &vector[0], usearch_scalar_f32_k, &error); if (error) goto cleanup; // Check up: assert(usearch_size(index, &error) == 1); assert(usearch_capacity(index, &error) == vectors_count); assert(usearch_contains(index, 42, &error)); // Search: usearch_key_t found_keys[10]; usearch_distance_t found_distances[10]; size_t found_count = usearch_search( index, &vector[0], usearch_scalar_f32_k, 10, &found_keys[0], &found_distances[0], &error); cleanup: if (error) fprintf(stderr, "Error: %s\n", error); if (index) usearch_free(index, &error); return error ? 1 : 0; } ``` -------------------------------- ### Index Creation and Basic Operations Source: https://github.com/unum-cloud/usearch/blob/main/javascript/README.md Demonstrates how to create a USearch index with specific configurations, add vectors, perform searches, and remove vectors. ```APIDOC ## Index Creation and Basic Operations ### Description Create a USearch index with specified metric, connectivity, and dimensions. Add vectors associated with unique keys, perform nearest neighbor searches, and remove vectors from the index. ### Method `new usearch.Index(options)` `index.add(key, vector)` `index.search(vector, limit)` `index.remove(key)` ### Parameters #### Index Constructor Options - **metric** (string) - Required - The distance metric to use (e.g., 'l2sq', 'ip'). - **connectivity** (number) - Required - The connectivity of the index graph. - **dimensions** (number) - Required - The dimensionality of the vectors. #### `add` Method Parameters - **key** (BigInt) - Required - The unique identifier for the vector. - **vector** (TypedArray) - Required - The vector to add to the index. #### `search` Method Parameters - **vector** (TypedArray) - Required - The query vector. - **limit** (number) - Required - The maximum number of results to return. #### `remove` Method Parameters - **key** (BigInt) - Required - The key of the vector to remove. ### Response #### `add` Method Response None #### `search` Method Response - **keys** (BigUint64Array) - The keys of the nearest neighbors. - **distances** (Float32Array) - The distances to the nearest neighbors. #### `remove` Method Response None ### Request Example ```javascript const assert = require('node:assert'); const usearch = require('usearch'); const index = new usearch.Index({ metric: 'l2sq', connectivity: 16, dimensions: 3 }); index.add(42n, new Float32Array([0.2, 0.6, 0.4])); const results = index.search(new Float32Array([0.2, 0.6, 0.4]), 10); assert(index.size() === 1); assert.deepEqual(results.keys, new BigUint64Array([42n])); assert.deepEqual(results.distances, new Float32Array([0])); index.remove(42n); ``` ``` -------------------------------- ### Build and Test Go Bindings Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Commands to compile the C library, copy necessary files to the Go directory, and run Go tests. Assumes C library is built with specific flags. ```sh cmake -B build_release -D USEARCH_BUILD_LIB_C=1 -D USEARCH_BUILD_TEST_C=1 -D USEARCH_USE_NUMKONG=1 -D USEARCH_USE_OPENMP=1 cmake --build build_release --config Release -j cp build_release/libusearch_c.so golang/ # or .dylib to install the library on macOS cp c/usearch.h golang/ # to make the header available to Go cd golang && LD_LIBRARY_PATH=. go test -v ; cd .. ``` -------------------------------- ### Cross-Compile for Arm64 on x86_64 Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Install necessary tools and set environment variables for cross-compiling to Arm64. Ensure you have the correct cross-build-essential packages installed. ```sh sudo apt-get update sudo apt-get install -y clang lld make crossbuild-essential-arm64 crossbuild-essential-armhf export CC="clang" export CXX="clang++" export AR="llvm-ar" export NM="llvm-nm" export RANLIB="llvm-ranlib" export TARGET_ARCH="aarch64-linux-gnu" # Or "x86_64-linux-gnu" export BUILD_ARCH="arm64" # Or "amd64" cmake -D CMAKE_BUILD_TYPE=Release \ -D CMAKE_C_COMPILER_TARGET=${TARGET_ARCH} \ -D CMAKE_CXX_COMPILER_TARGET=${TARGET_ARCH} \ -D CMAKE_SYSTEM_NAME=Linux \ -D CMAKE_SYSTEM_PROCESSOR=${BUILD_ARCH} \ -B build_artifacts cmake --build build_artifacts --config Release ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Build a Docker image for USearch and run it. This is a quick way to test the containerized application. ```bash docker build -t unum/usearch . && docker run unum/usearch ``` -------------------------------- ### C++ Benchmark Help Information Source: https://github.com/unum-cloud/usearch/blob/main/BENCHMARKS.md Displays the synopsis and available options for the C++ benchmark tool. Use this to understand configurable parameters for benchmarking. ```txt SYNOPSIS build_profile/bench_cpp [--vectors ] [--queries ] [--neighbors ] [-o ] [-b] [-j ] [-c ] [--expansion-add ] [--expansion-search ] [--rows-skip ] [--rows-take ] [--dtype ] [--metric ] [-h] OPTIONS --vectors .[fhbd]bin, .i8bin, .u8bin, .f32bin file path to construct the index --queries .[fhbd]bin, .i8bin, .u8bin, .f32bin file path to query the index --neighbors .ibin file path with ground truth -o, --output .usearch output file path -b, --big Will switch to uint40_t for neighbors lists with over 4B entries -j, --threads Uses all available cores by default -c, --connectivity Index granularity --expansion-add Affects indexing depth --expansion-search Affects search depth --rows-skip Number of vectors to skip --rows-take Number of vectors to take --dtype Quantization type: f64, f32, bf16, f16, e5m2, e4m3, e3m2, e2m3, i8, u8, b1 --metric Distance metric: ip, l2sq, cos, hamming, tanimoto, sorensen, haversine -h, --help Print this help information on this tool and exit ``` -------------------------------- ### Add NuGet Source Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Add the official NuGet package source for USearch. This is a prerequisite for installing USearch packages. ```sh dotnet nuget add source https://api.nuget.org/v3/index.json -n nuget.org ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/unum-cloud/usearch/blob/main/CONTRIBUTING.md Run this command before building for the first time to pull in NumKong and other dependencies. ```sh git submodule update --init --recursive ``` -------------------------------- ### Basic USearch Index Operations in C++ Source: https://github.com/unum-cloud/usearch/blob/main/cpp/README.md Demonstrates initializing a dense index, reserving space, adding a vector with a key, and performing a search. The search results can be iterated to access key and distance. ```cpp #include #include using namespace unum::usearch; int main(int argc, char **argv) { metric_punned_t metric(3, metric_kind_t::l2sq_k, scalar_kind_t::f32_k); // If you plan to store more than 4 Billion entries - use `index_dense_big_t`. // Or directly instantiate the template variant you need - `index_dense_gt`. index_dense_t index = index_dense_t::make(metric); float vec[3] = {0.1, 0.3, 0.2}; index.reserve(10); // Pre-allocate memory for 10 vectors index.add(42, &vec[0]); // Pass a key and a vector auto results = index.search(&vec[0], 5); // Pass a query and limit number of results for (std::size_t i = 0; i != results.size(); ++i) // You can access the following properties of every match: // results[i].element.key, results[i].element.vector, results[i].distance; std::printf("Found matching key: %zu", results[i].member.key); return 0; } ``` -------------------------------- ### Get Index Metadata and Restore Index Source: https://github.com/unum-cloud/usearch/blob/main/python/README.md Shows how to retrieve metadata from a saved index file and restore an index from disk. ```python Index.metadata('index.usearch') -> IndexMetadata Index.restore('index.usearch', view=False) -> Index ``` -------------------------------- ### Get, Rename, and Remove Vectors in C Source: https://github.com/unum-cloud/usearch/blob/main/c/README.md Demonstrates retrieving a specific vector, renaming its key, and then removing it. Use with caution for frequent updates. ```c float recovered_vector[dimensions]; size_t count_retrieved = usearch_get(index, 42, 1, &recovered_vector[0], usearch_scalar_f32_k, &error); assert(count_retrieved <= 1); size_t count_renamed = usearch_rename(index, 42, 43, &error); size_t count_removed = usearch_remove(index, 43, &error); assert(count_renamed == count_removed); ``` -------------------------------- ### Basic USearch Index Creation and Usage in Swift Source: https://github.com/unum-cloud/usearch/blob/main/swift/README.md Demonstrates creating a USearch index, adding vectors, performing searches, and retrieving vectors by key. Supports Float32 and Float64 vectors; Float16 support is OS and hardware dependent. ```swift let index = USearchIndex.make(metric: .Cos, dimensions: 3, connectivity: 8) let vectorA: [Float32] = [0.3, 0.5, 1.2] // `Float32` and `Float64` are always supported let vectorB: [Float32] = [0.4, 0.2, 1.2] // `Float16` support depends on the OS and hardware index.add(key: 42, vector: vectorA) // Pass full arrays or slices index.add(key: 43, vector: vectorB) let results = index.search(vector: vectorA, count: 10) assert(results.0[0] == 42) let retrieved: [[Float32]]? = index.get(key: 42) assert(retrieved![0] == vectorA) ``` -------------------------------- ### Download SpaceV 100M Dataset from Hugging Face Source: https://github.com/unum-cloud/usearch/blob/main/BENCHMARKS.md Downloads the 100 million vector SpaceV dataset from Hugging Face. Ensure you have `wget` installed. ```sh mkdir -p datasets/spacev_100M/ && \ wget -nc https://huggingface.co/datasets/unum-cloud/ann-spacev-100m/resolve/main/ids.100M.i32bin -P datasets/spacev_100M/ && wget -nc https://huggingface.co/datasets/unum-cloud/ann-spacev-100m/resolve/main/base.100M.i8bin -P datasets/spacev_100M/ && wget -nc https://huggingface.co/datasets/unum-cloud/ann-spacev-100m/resolve/main/query.30K.i8bin -P datasets/spacev_100M/ && wget -nc https://huggingface.co/datasets/unum-cloud/ann-spacev-100m/resolve/main/groundtruth.30K.i32bin -P datasets/spacev_100M/ && wget -nc https://huggingface.co/datasets/unum-cloud/ann-spacev-100m/resolve/main/groundtruth.30K.f32bin -P datasets/spacev_100M/ ``` -------------------------------- ### Define Build Options Source: https://github.com/unum-cloud/usearch/blob/main/CMakeLists.txt Configures various build options for USearch, such as installation, OpenMP support, hardware acceleration, memory allocation, and specific build targets. ```cmake # Options option(USEARCH_INSTALL "Install CMake targets" OFF) option(USEARCH_USE_OPENMP "Use OpenMP for a thread pool" OFF) option(USEARCH_USE_NUMKONG "Use NumKong hardware-accelerated metrics" OFF) option(USEARCH_USE_JEMALLOC "Use JeMalloc for faster memory allocations" OFF) option(USEARCH_BUILD_TEST_CPP "Compile a native unit test in C++" ${USEARCH_IS_MAIN_PROJECT}) option(USEARCH_BUILD_BENCH_CPP "Compile a native benchmark in C++" ${USEARCH_IS_MAIN_PROJECT}) option(USEARCH_BUILD_LIB_C "Compile a native library for the C 99 interface" OFF) option(USEARCH_BUILD_TEST_C "Compile a test for the C 99 interface" OFF) option(USEARCH_BUILD_JNI "Compile JNI library for Java bindings" OFF) option(USEARCH_BUILD_WOLFRAM "Compile Wolfram Language bindings" OFF) option(USEARCH_BUILD_SQLITE "Compile separate SQLite extension" OFF) ``` -------------------------------- ### Advanced Index Configuration Source: https://github.com/unum-cloud/usearch/blob/main/README.md Shows how to configure a USearch index with various parameters like dimensions, metric, data type, and performance tuning options. Recommended for modern CPUs. ```python index = Index( ndim=3, # Define the number of dimensions in input vectors metric='cos', # Choose 'l2sq', 'ip', 'haversine' or other metric, default = 'cos' dtype='bf16', # Store as 'f64', 'f32', 'bf16', 'f16', 'e5m2', 'e4m3', 'e3m2', 'e2m3', 'u8', 'i8', 'b1'..., default = None connectivity=16, # Optional: Limit number of neighbors per graph node expansion_add=128, # Optional: Control the recall of indexing expansion_search=64, # Optional: Control the quality of the search multi=False, # Optional: Allow multiple vectors per key, default = False ) ```