Supported Distance Metrics in VelesDB: A Complete Guide to Vector Similarity Search

VelesDB supports five distance metrics—Cosine, Euclidean, DotProduct, Hamming, and Jaccard—each implemented in crates/velesdb-core/src/distance.rs with SIMD acceleration for nanosecond-scale vector search.

The cyberlife-coder/velesdb repository provides a high-performance vector database engine where choosing the correct distance metric is critical for search accuracy and performance. The DistanceMetric enum defines how vector similarity is calculated, with each variant optimized for specific data types and machine learning workflows.

Overview of the DistanceMetric Enum

The core abstraction resides in crates/velesdb-core/src/distance.rs, where the DistanceMetric enum provides a unified interface for all similarity calculations. Each variant implements three key behaviors:

  • calculate – Dispatches to SIMD-optimized primitives in simd_native.rs for the actual mathematical computation
  • higher_is_better – Returns a boolean flag indicating whether larger values indicate greater similarity
  • sort_results – Orders search results correctly based on the metric's semantics (ascending for distance, descending for similarity)

This design ensures that regardless of which metric you select, the engine applies the correct sorting logic and leverages hardware acceleration for vectors up to 1536 dimensions.

The Five Supported Distance Metrics

Cosine Similarity

Cosine measures the cosine of the angle between two vectors, computed as 1 - cosine_distance. Higher scores indicate greater similarity.

Use Cosine when working with normalized embeddings where vector direction matters more than magnitude. This is the standard choice for text embeddings (BERT, OpenAI embeddings) and image feature vectors that have been L2-normalized. Since the metric ignores magnitude, it prevents longer documents or brighter images from dominating similarity scores.

Euclidean Distance

Euclidean calculates the L2 norm (straight-line distance) between vectors in multidimensional space. Lower values indicate closer similarity.

Select Euclidean for spatial data and raw sensor readings where absolute magnitude and geometric distance are meaningful. Geographic coordinates, 3D point clouds, and unnormalized numerical features benefit from Euclidean distance because it penalizes large absolute differences in any dimension. Unlike Cosine, it considers the magnitude of the vectors.

Dot Product

DotProduct computes the inner product of two vectors. Higher values indicate stronger similarity, making it ideal for Maximum Inner Product Search (MIPS).

Apply DotProduct to unnormalized vectors where larger values explicitly indicate stronger signals. Recommendation systems frequently use this metric—when user and item embeddings are trained such that their interaction strength scales with the dot product value. Unlike Cosine, DotProduct rewards both alignment and magnitude, making it suitable for confidence-weighted similarity.

Hamming Distance

Hamming counts the number of positions at which corresponding bits differ between two binary vectors. Lower values indicate greater similarity.

Use Hamming for binary embeddings and locality-sensitive hashing (LSH) outputs. When vectors represent compact binary codes (e.g., from semantic hashing or perceptual hashing algorithms), Hamming distance efficiently measures dissimilarity by counting bit flips. This metric is computationally inexpensive and works exclusively with bit-string representations.

Jaccard Similarity

Jaccard measures the intersection-over-union of non-zero elements between sparse vectors. Higher values indicate greater overlap.

Select Jaccard for sparse, set-like vectors such as tag clouds, one-hot encodings, or bag-of-words representations with high dimensionality but low density. When your data represents sets (e.g., user interests, document keywords), Jaccard ignores the magnitude of values and focuses solely on the proportion of shared non-zero dimensions.

Implementation Details: SIMD Optimization and Sorting

The DistanceMetric enum provides more than simple mathematical formulas—it orchestrates hardware-accelerated execution and result ordering.

The calculate Method

The calculate method in crates/velesdb-core/src/distance.rs (lines 66-73) dispatches to SIMD-optimized primitives implemented in simd_native.rs. This guarantees nanosecond-scale latency even for high-dimensional vectors like 768-dimensional BERT embeddings or 1536-dimensional OpenAI embeddings.

The higher_is_better Flag

Each metric implements higher_is_better (lines 76-83) to inform the search engine whether similarity increases with the metric value. Cosine, DotProduct, and Jaccard return true (descending sort), while Euclidean and Hamming return false (ascending sort).

The sort_results Method

The sort_results method (lines 85-105) applies the higher_is_better semantics to order search results correctly, ensuring that the most similar vectors appear first regardless of the underlying mathematical direction.

Practical Usage Examples

Selecting and applying a metric in VelesDB requires only importing the DistanceMetric enum and calling its methods:

use velesdb_core::distance::DistanceMetric;

// Select the appropriate metric for your data
let metric = DistanceMetric::Cosine;  // For normalized text embeddings

// Compute similarity between two vectors
let vector_a = vec![0.1_f32, 0.2, 0.3, 0.4];
let vector_b = vec![0.1_f32, 0.2, 0.25, 0.35];
let similarity_score = metric.calculate(&vector_a, &vector_b);

println!("Similarity: {:.4}", similarity_score);

To sort search results according to the metric's semantics:

// Sample search results: (id, raw_metric_value)
let mut results = vec![
    (1u64, 0.85_f32),
    (2, 0.60),
    (3, 0.92),
];

// Automatically sorts descending for Cosine (higher_is_better=true)
metric.sort_results(&mut results);
println!("Ranked results: {:?}", results);

Switching metrics for different data types requires only changing the enum variant:

// For geographic coordinates or sensor data
let metric = DistanceMetric::Euclidean;
let distance = metric.calculate(&coords_a, &coords_b); // Lower values indicate closer points

// For binary hashes
let metric = DistanceMetric::Hamming;
let diff_count = metric.calculate(&hash_a, &hash_b); // Counts differing bits

All metrics leverage SIMD acceleration through the simd_native module, ensuring consistent nanosecond-scale performance across all variants.

Summary

  • Five distance metrics are available in cyberlife-coder/velesdb through the DistanceMetric enum defined in crates/velesdb-core/src/distance.rs.
  • Cosine suits normalized embeddings where direction matters; Euclidean fits spatial data requiring magnitude sensitivity; DotProduct serves recommendation systems with unnormalized vectors.
  • Hamming optimizes binary embeddings and LSH hashes; Jaccard measures set overlap for sparse tag-like vectors.
  • The calculate method dispatches to SIMD-optimized implementations in simd_native.rs, while higher_is_better and sort_results ensure correct result ordering regardless of metric semantics.

Frequently Asked Questions

What is the default distance metric in VelesDB?

VelesDB does not enforce a default metric; you must explicitly specify a DistanceMetric variant when creating indexes or performing searches. Most users select Cosine for text embeddings and Euclidean for spatial data, but the choice depends entirely on your vector characteristics and whether they are normalized.

How do I choose between Cosine and DotProduct similarity?

Use Cosine when your vectors are L2-normalized (unit length) and you want to measure directional alignment independent of magnitude. Choose DotProduct for unnormalized vectors where the magnitude carries meaningful signal strength, such as in recommendation systems where higher dot products indicate stronger user-item affinity.

Does VelesDB support Manhattan (L1) distance?

Currently, VelesDB implements Euclidean (L2), Cosine, DotProduct, Hamming, and Jaccard metrics. Manhattan (L1) distance is not available in the current DistanceMetric enum defined in crates/velesdb-core/src/distance.rs. For Manhattan distance, you would need to normalize your data to Euclidean space or implement a custom metric wrapper.

Are all distance metrics equally performant in VelesDB?

Yes, all metrics leverage the same SIMD acceleration infrastructure through simd_native.rs, achieving nanosecond-scale latency for high-dimensional vectors. The computational cost is roughly equivalent across Cosine, Euclidean, and DotProduct because they share similar vectorized arithmetic patterns. Hamming and Jaccard have specialized bit-wise and set-wise optimizations but maintain comparable performance characteristics for their respective data types.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →