Skip to content

Commit

Permalink
Improved Entity Framework Core examples - #23 [skip ci]
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Oct 17, 2023
1 parent 7d1cb88 commit daf2ce9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 15 deletions.
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,14 +250,16 @@ Also supports `MaxInnerProduct` and `CosineDistance`
Get the distance

```csharp
public class Neighbor
{
public int Id { get; set; }
public double Distance { get; set; }
}
var items = await ctx.Items
.Select(x => new { Entity = x, Distance = x.Embedding!.L2Distance(embedding) })
.ToListAsync();
```

Get items within a certain distance

var neighbors = await ctx.Items
.Select(x => new Neighbor { Id = x.Id, Distance = x.Embedding!.L2Distance(embedding) })
```csharp
var items = await ctx.Items
.Where(x => x.Embedding!.L2Distance(embedding) < 5)
.ToListAsync();
```

Expand Down
16 changes: 8 additions & 8 deletions tests/Pgvector.Tests/EntityFrameworkCoreTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,6 @@ public class Item
public Vector? Embedding { get; set; }
}

public class Neighbor
{
public int Id { get; set; }
public double Distance { get; set; }
}

public class EntityFrameworkCoreTests
{
[Fact]
Expand Down Expand Up @@ -69,11 +63,17 @@ 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.Id)
.Where(x => x.Embedding!.L2Distance(embedding) < 1.5)
.ToListAsync();
Assert.Equal(new int[] { 1, 3 }, items.Select(v => v.Id).ToArray());

var neighbors = await ctx.Items
.OrderBy(x => x.Embedding!.L2Distance(embedding))
.Select(x => new Neighbor { Id = x.Id, Distance = x.Embedding!.L2Distance(embedding) })
.Select(x => new { Entity = x, Distance = x.Embedding!.L2Distance(embedding) })
.ToListAsync();
Assert.Equal(new int[] { 1, 3, 2 }, neighbors.Select(v => v.Id).ToArray());
Assert.Equal(new int[] { 1, 3, 2 }, neighbors.Select(v => v.Entity.Id).ToArray());
Assert.Equal(new double[] { 0, 1, Math.Sqrt(3) }, neighbors.Select(v => v.Distance).ToArray());
}
}

0 comments on commit daf2ce9

Please sign in to comment.