Recursive AI

Cosine or Euclidean vector search in C#

OneIndex is a free, open-source search library for .NET from Recursive AI. MIT or Apache-2.0, preview, runs in-process.

Leave Metric out to use cosine, which compares directions. Set it to Euclidean to measure the gap between points.

Terminal
dotnet add package RecursiveAI.OneIndex --prerelease

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using OneIndex;
using OneIndex.Vectors;
 
using var index = SearchIndex.InMemory<Point>();
index.Upsert(new Point { Id = "same-direction",
    Angle = [3, 0], Gap = [3, 0] });
index.Upsert(new Point { Id = "shorter-gap",
    Angle = [1, 1], Gap = [1, 1] });
index.Commit();
 
float[] query = [1, 0];
var cosine = index.SearchVector(p => p.Angle,
    query, 1).Single();
var euclidean = index.SearchVector(p => p.Gap,
    query, 1).Single();
Console.WriteLine("Cosine: "
    + cosine.Document.Id);
Console.WriteLine("Euclidean: "
    + euclidean.Document.Id);
 
public class Point
{
    [SearchId]
    public string Id { get; set; } = "";
 
    [Vector(Dimensions = 2,
        Metric = VectorMetric.Cosine)]
    public float[] Angle { get; set; } = [];
 
    [Vector(Dimensions = 2,
        Metric = VectorMetric.Euclidean)]
    public float[] Gap { get; set; } = [];
}

The same query picks a different point for each field:

Text
Cosine: same-direction
Euclidean: shorter-gap

Both fields get the same two input vectors. The OneIndex package includes the source generator that maps Point using the attributes shown above; there’s no separate generator package to install.

OneIndex rejects a vector containing NaN or infinity with ArgumentException, whether you add it to the index or use it as a query.

Paste the code above into Program.cs of a new dotnet new console project and dotnet run, or unzip the example and dotnet run.

Variations

To compare unnormalized dot products instead of cosine, replace the Angle field’s attribute with this one:

C#
[Vector(Dimensions = 2,
    Metric = VectorMetric.DotProduct)]

The first result is still same-direction with these points (dot products of 3 and 1). Rename the Cosine: output label if you keep this change.

The short answer

Set Metric = VectorMetric.Cosine or Metric = VectorMetric.Euclidean in the [Vector] attribute. The metric belongs to the field, not the SearchVector call. If you leave it out, OneIndex uses cosine. To compare two metrics, you can index the same values in two fields as above; in an application that needs only one metric, keep only the field you search.

When should you use cosine similarity vs. Euclidean distance?

Use cosine when direction represents similarity and a difference in length shouldn’t change the match. In the example, [3, 0] and [1, 0] lie on the same ray, so cosine treats them as equally aligned. The vector [1, 1] points in a different direction, even though it’s only one unit away. Euclidean distance keeps the coordinates as supplied and prefers that closer point over [3, 0], which is two units away.

For data such as points with coordinates in the same units, Euclidean distance preserves the geometric gap you might want to search by. For embeddings, start with the metric specified by the model you use. If both sides are already unit vectors, expanding the squared distance gives 1 + 1 − 2 × cosine, so the two metrics rank pairs the same in exact arithmetic. That relationship doesn’t hold for the inputs in this example, which have different lengths.

What’s the difference between dot product and cosine similarity?

Cosine is the dot product of vectors scaled to length one. OneIndex normalizes both the indexed vectors and the query for a cosine field. DotProduct uses the values you supply, so increasing a candidate’s magnitude can increase its similarity if the dot product is positive. For example, with the query [1, 0], the raw dot product of [3, 0] is 3, while [1, 0] gives 1. Cosine treats those two candidates alike. A zero vector is a special case: OneIndex leaves it at zero and gives it a cosine score of 0.5.

How do cosine, dot product, and Euclidean distance become search scores?

OneIndex returns a score where larger means nearer, not the raw distance. According to the vector docs, cosine uses (1 + cos) / 2, clamped to 0–1, and Euclidean uses 1 / (1 + d²) for distance d. Dot product uses 1 + dot for a nonnegative dot product or 1 / (1 − dot) otherwise. For example, the two Euclidean scores here are 1 / 5 and 1 / 2. They preserve the distance ranking but aren’t probabilities. Don’t carry a numerical cutoff from one metric to another just because both return a field called Score.

All oneindex recipes