Skip to content

infinity.vectordb

Provides a persistent vector database for semantic search and similarity matching (e.g. with embeddings of AI models), shared by all threads of one infinity instance.

A search compares the query vector with all stored vectors (using SIMD instructions and optionally several threads). If IVF (inverted file index) is enabled, the vectors are grouped into clusters as soon as a namespace contains at least 1000 vectors, and a search only compares the vectors of the clusters nearest to the query vector (approximate search). The similarity is the dot product of the vectors; with normalize enabled, this is the cosine similarity.

Each namespace is stored in the folder vectordb/<namespace>/ next to the folder containing the INFINITY.JS executable (e.g. dist/bin/vectordb/documents/ for dist/bin/win-x64/infinity.exe). Vectors are stored as 32-bit floating point numbers and written to the data file immediately, the index files are written by flush() and close(). If a namespace was not closed properly, its index is rebuilt from the data file on the next open().

Module: infinity.vectordb

Example:

infinity.loadModule('infinity.vectordb');

infinity.vectordb.open('documents', 4, 10000, 2, 0.2, true, infinity.vectordb.deleteStrategy.firstId, false, 0, 1);

infinity.vectordb.add('documents', 1, [0.1, 0.5, 0.3, 0.8]);
infinity.vectordb.add('documents', 2, [0.9, 0.1, 0.0, 0.2]);
infinity.vectordb.add('documents', 3, [0.2, 0.4, 0.3, 0.9]);

console.debug(infinity.vectordb.count('documents'));
//3

let results = infinity.vectordb.search('documents', [0.1, 0.5, 0.3, 0.7], 0.8, 10);

for (let i = 0; i < results.length; i++) {
  console.debug('ID: ' + results[i].id + ', similarity: ' + results[i].similarity);
}

infinity.vectordb.close('documents');

Enums

deleteStrategy

Specifies which vector is removed when the maximum number of items is reached and a new vector is added.

Values:

  • firstId: 0

    Removes the vector with the lowest ID.

  • randomId: 1

    Removes a random vector.

Example:

infinity.vectordb.open('documents', 384, 10000, 2, 0.2, true, infinity.vectordb.deleteStrategy.randomId, false, 0, 1);

Interfaces

resultArray

Extends: Array<{id: number, similarity: number}>

An array of search results of search(), sorted by similarity (highest first). id is the ID of the matched vector, similarity the dot product of the query vector and the matched vector (with normalize enabled the cosine similarity: 1 = identical direction, 0 = unrelated, -1 = opposite).


stringArray

Extends: Array<string>

An array of strings.


vectorArray

Extends: Array<number>

An array of numbers representing a vector. The length must match the dimensions specified when opening the namespace.


Functions

add()

Adds or updates a vector in the specified namespace. If a vector with the same ID already exists, it is replaced. If the namespace already contains maxItems vectors, vectors are removed according to the deleteStrategy given in open(). The namespace must be open; IDs less than 1 are ignored.

Signature:

add( namespace: string, id: number, vector: infinity.vectordb.vectorArray ): void

Parameters:

  • namespace: string

    The namespace of the vector database.

  • id: number

    A unique, positive integer identifier for this vector (e.g. a document ID).

  • vector: infinity.vectordb.vectorArray

    The vector to add. Must have exactly the number of dimensions specified when opening the namespace, otherwise an error is thrown.

Example:

infinity.vectordb.add('documents', 1001, embedding);

clear()

Removes all vectors from the specified namespace. The namespace stays open.

Signature:

clear( namespace: string ): void

Parameters:

  • namespace: string

    The namespace of the vector database to clear.

Example:

infinity.vectordb.clear('documents');

close()

Closes the specified namespace and writes the index files. Should be called before the program ends.

Signature:

close( namespace: string ): void

Parameters:

  • namespace: string

    The namespace of the vector database to close.

Example:

infinity.vectordb.close('documents');

count()

Returns the number of vectors stored in the specified namespace, or 0 if the namespace is not open.

Signature:

count( namespace: string ): number

Parameters:

  • namespace: string

    The namespace of the vector database.

Return type: number

Example:

console.debug(infinity.vectordb.count('documents'));

flush()

Writes the index files of the specified namespace without closing it. If the ratio of removed to stored vectors has reached compactThreshold (see open()), the data file is compacted.

Signature:

flush( namespace: string ): void

Parameters:

  • namespace: string

    The namespace of the vector database to flush.

Example:

infinity.vectordb.flush('documents');

open()

Opens the specified namespace, creating it if it does not exist. If the namespace is already open, the call has no effect (the parameters are not changed).

Signature:

open( namespace: string, dimensions: number, maxItems: number, parallelSearchThreads: number, compactThreshold: number, normalize: boolean, deleteStrategy: infinity.vectordb.deleteStrategy, ivfEnabled: boolean, ivfNumClusters: number, ivfNProbe: number ): void

Parameters:

  • namespace: string

    The name of the vector database.

  • dimensions: number

    The number of dimensions of the vectors (e.g. 384 or 1024, depending on the embedding model). All vectors must have exactly this many elements. Must not be changed for an existing namespace.

  • maxItems: number

    The maximum number of vectors to store. When this limit is reached, adding a new vector removes an existing one according to deleteStrategy. 0 means no limit.

  • parallelSearchThreads: number

    The number of threads used for a search. Values greater than 1 are only used if the namespace contains at least 1024 vectors and no IVF index is used.

  • compactThreshold: number

    The ratio of removed to stored vectors at which flush() compacts the data file (e.g. 0.2 for 20 %).

  • normalize: boolean

    If true, all vectors (including the query vectors of search()) are normalized to unit length, so the similarity is the cosine similarity. Must not be changed for an existing namespace.

  • deleteStrategy: infinity.vectordb.deleteStrategy

    Specifies which vector is removed when maxItems is reached.

  • ivfEnabled: boolean

    Enables the IVF index (clustering) for faster, approximate searches on large datasets. The index is built as soon as the namespace contains at least 1000 vectors; until then all vectors are searched.

  • ivfNumClusters: number

    The number of IVF clusters. 0 computes the number automatically (square root of the number of vectors, between 16 and 256). Only used when ivfEnabled is true.

  • ivfNProbe: number

    The number of clusters nearest to the query vector that are searched. Higher values are more accurate but slower. Values less than 1 are treated as 1. Only used when ivfEnabled is true.

Example:

infinity.loadModule('infinity.vectordb');

infinity.vectordb.open(
  'documents',  // namespace
  384,          // dimensions
  100000,       // maximum number of vectors
  2,            // parallel search threads
  0.2,          // compact the data file at 20 % removed vectors
  true,         // normalize vectors (cosine similarity)
  infinity.vectordb.deleteStrategy.firstId,
  true,         // enable IVF
  0,            // number of clusters: automatic
  5             // search the 5 nearest clusters
);

purge()

Deletes all files and the folder of the specified namespace. Only works if the namespace is closed, otherwise the call has no effect.

Signature:

purge( namespace: string ): void

Parameters:

  • namespace: string

    The namespace of the vector database to delete.

Example:

infinity.vectordb.close('documents');
infinity.vectordb.purge('documents');

remove()

Removes a vector from the specified namespace by its ID.

Signature:

remove( namespace: string, id: number ): void

Parameters:

  • namespace: string

    The namespace of the vector database.

  • id: number

    The ID of the vector to remove.

Example:

infinity.vectordb.remove('documents', 1001);

search()

Searches for vectors similar to the given query vector and returns their IDs, sorted by similarity (highest first). Returns an empty array if the namespace is not open.

Signature:

search( namespace: string, vector: infinity.vectordb.vectorArray, threshold: number, maxResults?: number ): infinity.vectordb.resultArray

Parameters:

  • namespace: string

    The namespace of the vector database to search.

  • vector: infinity.vectordb.vectorArray

    The query vector. Must have the same number of dimensions as the namespace, otherwise an error is thrown.

  • threshold: number

    The minimum similarity. Only vectors with a similarity greater than or equal to this value are returned.

  • maxResults: number, optional

    The maximum number of results. 0 or omitted returns all vectors above the threshold.

Return type: infinity.vectordb.resultArray

Example:

let results = infinity.vectordb.search('documents', queryEmbedding, 0.7, 10);

for (let i = 0; i < results.length; i++) {
  console.debug('ID: ' + results[i].id + ', similarity: ' + (results[i].similarity * 100).toFixed(1) + '%');
}

splitText()

Splits a text into chunks of at most chunkSize characters, e.g. to create embeddings for longer documents. The text is split recursively at the first separator that produces small enough parts (by default: blank lines, line breaks, sentence ends, commas, spaces and finally single characters); neighboring chunks overlap by up to chunkOverlap characters (if chunkOverlap is greater than 0, at least the last part of the previous chunk, e.g. a sentence, is repeated). The chunks are returned in text order, separators stay at the end of the part before them (except spaces).

Signature:

splitText( text: string, chunkSize?: number, chunkOverlap?: number, separators?: infinity.vectordb.stringArray ): infinity.vectordb.stringArray

Parameters:

  • text: string

    The text to split.

  • chunkSize: number, optional

    The maximum length of a chunk in characters. Must be greater than 0. Default is 1000.

  • chunkOverlap: number, optional

    The number of characters by which neighboring chunks overlap. Must be less than chunkSize. Default is 200.

  • separators: infinity.vectordb.stringArray, optional

    The separators to split at, in order of priority. Default is ['\r\n\r\n', '\n\n', '\r\n', '\n', '. ', '! ', '? ', '; ', ', ', ' ', ''].

Return type: infinity.vectordb.stringArray

Example:

let chunks = infinity.vectordb.splitText(text, 500, 100);

for (let i = 0; i < chunks.length; i++) {
  infinity.vectordb.add('documents', docId * 1000 + i, getEmbedding(chunks[i]));
}

Integration with AI Models

Example of a semantic search with embeddings from an HTTP API:

infinity.loadModule('infinity.http');
infinity.loadModule('infinity.vectordb');

infinity.vectordb.open('embeddings', 384, 100000, 2, 0.2, true,
  infinity.vectordb.deleteStrategy.firstId, true, 0, 5);

let client = new infinity.http.client();

function getEmbedding(text: string): number[] {
  // Call your embedding API
  client.contentType = 'application/json';
  let response = client.post('https://api.example.com/embeddings', JSON.stringify({text: text}));

  return JSON.parse(response).embedding;
}

function indexDocument(docId: number, text: string): void {
  infinity.vectordb.add('embeddings', docId, getEmbedding(text));
}

function semanticSearch(query: string, limit: number): infinity.vectordb.resultArray {
  return infinity.vectordb.search('embeddings', getEmbedding(query), 0.7, limit);
}

try {
  indexDocument(1, 'INFINITY.JS is a persistent JavaScript server runtime.');
  console.debug(semanticSearch('JavaScript server', 10));
} finally {
  client.free();
  infinity.vectordb.close('embeddings');
}