Skip to content

Commit

Permalink
Added L1Distance function for EF Core
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed May 17, 2024
1 parent e3bb664 commit 97d9601
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Pgvector.EntityFrameworkCore/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## 0.2.1 (unreleased)

- Added support for compiled models
- Added `L1Distance` function

## 0.2.0 (2023-11-24)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@ public static double MaxInnerProduct(this Vector a, Vector b)

public static double CosineDistance(this Vector a, Vector b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(CosineDistance)));

public static double L1Distance(this Vector a, Vector b)
=> throw new InvalidOperationException(CoreStrings.FunctionOnClient(nameof(L1Distance)));
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ private class VectorDbFunctionsTranslator : IMethodCallTranslator
typeof(Vector),
})!;

private static readonly MethodInfo _methodL1Distance = typeof(VectorDbFunctionsExtensions)
.GetRuntimeMethod(nameof(VectorDbFunctionsExtensions.L1Distance), new[]
{
typeof(Vector),
typeof(Vector),
})!;

public VectorDbFunctionsTranslator(
ISqlExpressionFactory sqlExpressionFactory,
IRelationalTypeMappingSource typeMappingSource
Expand All @@ -71,6 +78,7 @@ IRelationalTypeMappingSource typeMappingSource
_ when ReferenceEquals(method, _methodL2Distance) => "<->",
_ when ReferenceEquals(method, _methodMaxInnerProduct) => "<#>",
_ when ReferenceEquals(method, _methodCosineDistance) => "<=>",
_ when ReferenceEquals(method, _methodL1Distance) => "<+>",
_ => null
};

Expand Down
3 changes: 3 additions & 0 deletions tests/Pgvector.CSharp.Tests/EntityFrameworkCoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ public async Task Main()
items = await ctx.Items.OrderBy(x => x.Embedding!.CosineDistance(embedding)).Take(5).ToListAsync();
Assert.Equal(3, items[2].Id);

items = await ctx.Items.OrderBy(x => x.Embedding!.L1Distance(embedding)).Take(5).ToListAsync();
Assert.Equal(new int[] { 1, 3, 2 }, items.Select(v => v.Id).ToArray());

items = await ctx.Items
.OrderBy(x => x.Id)
.Where(x => x.Embedding!.L2Distance(embedding) < 1.5)
Expand Down

0 comments on commit 97d9601

Please sign in to comment.