Gets the expected vector dimensions for this service instance
The expected dimensions, or null if no vectors loaded yet
Gets the current number of vectors in the service
The number of vectors currently loaded
Adds a new vector or updates an existing one based on whether the key already exists. If the key does not exist, a new entry is created. If the key already exists, the vector and/or metadata are updated in place.
The unique identifier for the vector
The vector/embedding array
Optionalmetadata: TMetadataOptional metadata to associate with the vector
True if an existing vector was updated, false if a new vector was added
// First call creates the entry
const wasUpdate = service.AddOrUpdateVector('doc1', [0.1, 0.2, 0.3], { title: 'Doc 1' });
console.log(wasUpdate); // false (new entry)
// Second call updates the existing entry
const wasUpdate2 = service.AddOrUpdateVector('doc1', [0.4, 0.5, 0.6], { title: 'Doc 1 v2' });
console.log(wasUpdate2); // true (updated)
Adds or updates a single vector in the service
The unique identifier for the vector
The vector/embedding array
Optionalmetadata: TMetadataOptional metadata to associate with the vector
Calculates the average between-cluster distance for a clustering result. Higher values indicate better cluster separation.
Measures how far apart different clusters are from each other. Also known as cluster separation.
The clustering result
Optionalmetric: DistanceMetricDistance metric to use
Average between-cluster distance (0-1, higher is better)
Calculates distance/similarity between two vectors using the specified metric. All metrics are normalized to 0-1 range where 1 indicates highest similarity.
First vector
Second vector
Optionalmetric: DistanceMetricThe metric to use
Normalized similarity score (0-1)
ProtectedCosineProtectedCalculates cosine similarity between two vectors using the formula: similarity = (A · B) / (||A|| × ||B||)
Cosine similarity measures the cosine of the angle between two vectors in multi-dimensional space. It tells us how similar two vectors are regardless of their magnitude (length).
Text embeddings encode semantic meaning as vectors. Cosine similarity is ideal because:
cosine_similarity = dot_product(A, B) / (magnitude(A) * magnitude(B))
Where:
- dot_product(A, B) = Σ(a[i] * b[i]) for all i
- magnitude(A) = √(Σ(a[i]²)) for all i
First vector (e.g., embedding of document A)
Second vector (e.g., embedding of document B)
Cosine similarity score between -1 and 1
// Two identical vectors have similarity of 1
const similarity1 = CosineSimilarity([1, 2, 3], [1, 2, 3]); // ≈ 1.0
// Perpendicular vectors have similarity of 0
const similarity2 = CosineSimilarity([1, 0], [0, 1]); // = 0.0
// Opposite vectors have similarity of -1
const similarity3 = CosineSimilarity([1, 2], [-1, -2]); // = -1.0
Performs DBSCAN (Density-Based Spatial Clustering of Applications with Noise) clustering.
DBSCAN groups together points that are closely packed together (high density), marking points in low-density regions as outliers. Unlike K-Means, it doesn't require specifying the number of clusters beforehand.
✅ Unknown number of clusters ✅ Non-spherical clusters ✅ Varying cluster densities ✅ Need to identify outliers ✅ Noise in the data ❌ High-dimensional sparse data ❌ Clusters of vastly different densities
Maximum distance between two vectors to be considered neighbors
Minimum number of points to form a dense region
Optionalmetric: DistanceMetricDistance metric to use
Optionalfilter: (metadata: TMetadata) => booleanOptional filter to pre-filter vectors by metadata before clustering
Clustering results with outliers identified
// epsilon=0.3 means similarity must be > 0.7
const result = service.DBSCANCluster(0.3, 3, 'cosine');
console.log(`Found ${result.clusters.size} clusters`);
console.log(`Outliers: ${result.outliers?.length || 0}`);
// Cluster only active items
const activeResult = service.DBSCANCluster(
0.3,
3,
'cosine',
(metadata) => metadata.status === 'Active'
);
ProtectedDotProtectedCalculates dot product similarity between two vectors, normalized to 0-1 range.
Dot product (inner product) measures both direction AND magnitude alignment. Unlike cosine similarity, it rewards vectors that point the same way AND have similar magnitudes.
dot_product = Σ(a[i] × b[i])
normalized = (tanh(dot_product / scale) + 1) / 2
✅ Magnitude is meaningful (popularity, importance, quantity) ✅ Pre-normalized vectors with semantic magnitude ✅ Weighted feature comparisons ✅ Collaborative filtering with implicit feedback ❌ Vectors with different scales ❌ When only direction matters (use cosine)
First vector
Second vector
Normalized similarity score (0-1, where 1 = high similarity)
Finds the optimal number of clusters using the elbow method. Tests different values of k and returns their inertias.
A technique to find the optimal number of clusters by plotting inertia vs k. The "elbow" point where inertia stops decreasing rapidly suggests the optimal k.
Minimum number of clusters to test
Maximum number of clusters to test
Optionalmetric: DistanceMetricDistance metric to use
Map of k values to inertias
ProtectedEuclideanProtectedCalculates Euclidean distance between two vectors, normalized to 0-1 range.
Euclidean distance is the "straight-line" distance between two points in space. It's what you'd measure with a ruler in the physical world.
distance = √(Σ(a[i] - b[i])²)
normalized_similarity = 1 / (1 + distance)
✅ Continuous numeric features where magnitude matters ✅ Physical measurements and specifications ✅ When you need true geometric distance ❌ High-dimensional sparse data (use cosine instead) ❌ Text embeddings (use cosine for better results)
First vector
Second vector
Normalized similarity score (0-1, where 1 = identical)
Exports all vectors as an array of VectorEntry objects. Useful for persistence or transferring data.
Array of all vector entries
Finds all vectors with similarity above a threshold
The vector to search for similar items
Minimum similarity threshold (0-1)
Optionalmetric: DistanceMetricThe distance metric to use
Optionalfilter: (metadata: TMetadata) => booleanOptional filter to pre-filter vectors by metadata before similarity calculation
Array of search results sorted by similarity
// Find all highly similar items (similarity > 0.8)
const similar = service.FindAboveThreshold(queryVector, 0.8);
// Find all items with Jaccard similarity > 0.5
const matches = service.FindAboveThreshold(features, 0.5, 'jaccard');
// Find all similar items in a specific category
const categoryMatches = service.FindAboveThreshold(
queryVector,
0.7,
'cosine',
(metadata) => metadata.status === 'Active'
);
Finds the centroid (mean) of a set of vectors.
A centroid is the mean position of all vectors in a group. It represents the "center" of the cluster in vector space.
Array of vectors to find centroid of
The centroid vector
Finds the K nearest neighbors to a query vector using the specified similarity metric
The vector to search for similar items
OptionaltopK: numberNumber of nearest neighbors to return
Optionalthreshold: numberOptional minimum similarity threshold (0-1)
Optionalmetric: DistanceMetricThe distance metric to use
Optionalfilter: (metadata: TMetadata) => booleanOptional filter to pre-filter vectors by metadata before similarity calculation
Array of search results sorted by similarity (highest first)
// Default cosine similarity
const nearestItems = service.FindNearest(queryEmbedding, 5);
// Using Euclidean distance for numeric features
const similarProducts = service.FindNearest(productFeatures, 10, undefined, 'euclidean');
// With threshold - only return items with similarity > 0.7
const highSimilarity = service.FindNearest(queryVector, 10, 0.7, 'cosine');
// Using Jaccard for categorical data
const similarUsers = service.FindNearest(userPreferences, 5, undefined, 'jaccard');
// Filter by metadata before searching (efficient pre-filtering)
const agentNotes = service.FindNearest(
queryVector,
5,
0.5,
'cosine',
(metadata) => metadata.agentId === 'agent-123'
);
Finds vectors similar to an existing vector identified by its key. The source vector itself is excluded from the results.
The key of the source vector
OptionaltopK: numberNumber of similar vectors to return
Optionalthreshold: numberOptional minimum similarity threshold (0-1)
Optionalmetric: DistanceMetricThe distance metric to use
Optionalfilter: (metadata: TMetadata) => booleanOptional filter to pre-filter vectors by metadata before similarity calculation
Array of similar vectors sorted by similarity
// Find items similar to 'product123'
const similarProducts = service.FindSimilar('product123', 5);
// Find highly similar items (similarity > 0.8)
const verySimilar = service.FindSimilar('product123', 10, 0.8);
// Find similar items using Euclidean distance
const similar = service.FindSimilar('product123', 5, undefined, 'euclidean');
// Find similar items filtered by category
const similarInCategory = service.FindSimilar(
'product123',
5,
0.7,
'cosine',
(metadata) => metadata.category === 'Electronics'
);
Find similar golden queries using weighted cosine similarity
Calculates similarity for each field separately, then combines with weights. ALWAYS returns topK results, even if below threshold (threshold is informational).
Embeddings for the user's query (one per field)
Array of golden queries with their embeddings
Number of most similar queries to return (default: 5)
Array of top-K most similar golden queries with scores
ProtectedHammingProtectedCalculates Hamming distance between two vectors, normalized to similarity score.
Hamming distance counts the number of positions where two vectors differ. Originally designed for error detection in telecommunications, it's useful for comparing categorical data or binary strings.
hamming_distance = count(a[i] ≠ b[i])
similarity = 1 - (hamming_distance / vector_length)
✅ Categorical data comparison ✅ Binary feature vectors ✅ Error detection and correction ✅ Fixed-length codes or identifiers ❌ Continuous numeric features ❌ When magnitude of difference matters
For continuous values, this uses exact equality. Consider binning continuous values first if approximate matching is needed.
First vector
Second vector
Normalized similarity (0-1, where 1 = identical)
ProtectedJaccardProtectedCalculates Jaccard similarity between two vectors treated as sets.
Jaccard similarity (Jaccard index) measures the similarity between two sets as the size of their intersection divided by the size of their union. For vectors, non-zero elements are treated as "present" in the set.
jaccard = |A ∩ B| / |A ∪ B|
where A and B are sets of non-zero indices
✅ Binary or categorical data (presence/absence) ✅ Sparse vectors where zeros mean "not present" ✅ Set membership comparisons ✅ When magnitude doesn't matter, only presence ❌ Continuous numeric features ❌ Dense embeddings
This implementation treats 0 as absence and any non-zero as presence. This is suitable for sparse representations where 0 explicitly means "not in set".
First vector (treated as set)
Second vector (treated as set)
Jaccard similarity (0-1, where 1 = identical sets)
Performs K-Means clustering on the loaded vectors. Uses K-Means++ initialization for better starting centroids.
K-Means divides vectors into K clusters by minimizing within-cluster variance. Each vector is assigned to the nearest centroid, and centroids are iteratively updated.
✅ Known or estimated number of clusters ✅ Spherical, well-separated clusters ✅ Similar cluster sizes ✅ Need interpretable centroids ❌ Non-spherical clusters ❌ Varying cluster densities ❌ Unknown number of clusters
Number of clusters
OptionalmaxIterations: numberMaximum iterations before stopping
Optionalmetric: DistanceMetricDistance metric to use
Optionaltolerance: numberConvergence tolerance
Clustering results with assignments and centroids
Loads vectors into memory. Can accept either an array of VectorEntry objects or a Map where keys are identifiers and values are vector arrays.
The vectors to load
// Load from array
service.LoadVectors([
{ key: 'doc1', vector: [0.1, 0.2], metadata: { title: 'Document 1' } },
{ key: 'doc2', vector: [0.3, 0.4], metadata: { title: 'Document 2' } }
]);
// Load from Map
const vectorMap = new Map();
vectorMap.set('doc1', [0.1, 0.2]);
vectorMap.set('doc2', [0.3, 0.4]);
service.LoadVectors(vectorMap);
ProtectedManhattanProtectedCalculates Manhattan distance between two vectors, normalized to 0-1 range.
Manhattan distance (also called L1 distance, city block distance, or taxicab distance) measures the distance between two points by summing the absolute differences of their coordinates. Like navigating a city grid where you can only move along streets.
distance = Σ|a[i] - b[i]|
normalized_similarity = 1 / (1 + distance)
✅ Grid-based movement systems ✅ When outliers should have linear (not squared) impact ✅ Discrete movements or changes ✅ Each dimension represents independent cost/distance ❌ Smooth gradients needed ❌ True geometric distance required
First vector
Second vector
Normalized similarity score (0-1, where 1 = identical)
Calculates the Silhouette Score for a clustering result. Measures how similar a point is to its own cluster compared to other clusters.
A measure of how appropriate the clustering is, combining both cohesion and separation. Ranges from -1 to 1, where:
The clustering result
Optionalmetric: DistanceMetricDistance metric to use
Silhouette score (-1 to 1, higher is better)
Calculates the cosine similarity between two vectors identified by their keys
Key of the first vector
Key of the second vector
Cosine similarity score between 0 and 1
Updates an existing vector entry in-place, allowing partial updates to the vector data, metadata, or both without removing and re-adding the entry. Unlike AddVector, this method requires the key to already exist and will throw if it does not.
This is useful when you need to:
The unique identifier of the vector to update. Must already exist.
The fields to update. At least one of vector or metadata must be provided.
Optionalmetadata?: TMetadataNew metadata to replace the existing metadata.
Optionalvector?: number[]New vector/embedding to replace the existing one. Must match the expected dimensions of the service.
True if the update was applied successfully
// Update only the vector (e.g., after re-embedding content)
service.UpdateVector('doc123', { vector: newEmbedding });
// Update only metadata (e.g., status changed)
service.UpdateVector('doc123', { metadata: { title: 'Updated Title', status: 'reviewed' } });
// Update both vector and metadata atomically
service.UpdateVector('doc123', {
vector: newEmbedding,
metadata: { title: 'Updated Title', version: 2 }
});
Calculates the average within-cluster distance for a clustering result. Lower values indicate tighter, more cohesive clusters.
Measures how close points are to other points in the same cluster. Also known as cluster cohesion or compactness.
The clustering result
Optionalmetric: DistanceMetricDistance metric to use
Average within-cluster distance (0-1, lower is better)
SimilaritySearch class Finds most similar golden queries using weighted cosine similarity across multiple fields