Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions conceptual/EFCore.PG/mapping/vector-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Vector Search

Vector search finds items whose vectors are close to a query vector. For example, an embedding model can represent text or images as vectors, allowing a search to find semantically similar items rather than just matching keywords. The query vector and stored vectors must be produced by the same embedding model.

PostgreSQL supports vector search through the [pgvector extension](https://github.com/pgvector/pgvector). The [pgvector .NET library](https://github.com/pgvector/pgvector-dotnet#entity-framework-core) provides EF Core integration, including vector types and distance functions.

## Setup

Install the [Pgvector.EntityFrameworkCore](https://www.nuget.org/packages/Pgvector.EntityFrameworkCore) package. Version 0.3.0 supports EF Core 9, 10 and 11. For EF Core 8, use version 0.2.2 and its [setup instructions](https://github.com/pgvector/pgvector-dotnet/blob/efcore-v0.2.2/README.md#entity-framework-core); the setup below is for version 0.3.0.

Configure the plugin when configuring your context:

```csharp
using Microsoft.EntityFrameworkCore;
using Pgvector.EntityFrameworkCore;

optionsBuilder.UseNpgsql("<connection string>", o => o.UseVector());
```

If you use an [external NpgsqlDataSource](../index.md#using-an-external-npgsqldatasource), configure vector support on the data source as well:

```csharp
using Npgsql;

var dataSourceBuilder = new NpgsqlDataSourceBuilder("<connection string>");
dataSourceBuilder.UseVector();
var dataSource = dataSourceBuilder.Build();

optionsBuilder.UseNpgsql(dataSource, o => o.UseVector());
```

Install the pgvector extension on your PostgreSQL server. To have EF migrations enable it in your database, add the following to your context:

```csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasPostgresExtension("vector");
}
```

## Model and query

Define a vector property with the number of dimensions used by your embedding model:

```csharp
using System.ComponentModel.DataAnnotations.Schema;
using Pgvector;

public class Item
{
public int Id { get; set; }
public string Name { get; set; } = null!;

[Column(TypeName = "vector(3)")]
public Vector? Embedding { get; set; }
}
```

The following query orders items by Euclidean (L2) distance to a query embedding and returns the five closest. The three-dimensional vector is only an example; use an embedding generated by your model in a real application.

```csharp
using Pgvector.EntityFrameworkCore;

var embedding = new Vector(new float[] { 1, 1, 1 });
var items = await context.Set<Item>()
.OrderBy(i => i.Embedding!.L2Distance(embedding))
.Take(5)
.Select(i => new { i.Id, i.Name })
.ToListAsync();
```

The distance is computed in PostgreSQL; the projection avoids retrieving the stored vectors. pgvector also supports other distance metrics and approximate nearest-neighbor indexes; see the [pgvector documentation](https://github.com/pgvector/pgvector) and [EF Core examples](https://github.com/pgvector/pgvector-dotnet#entity-framework-core).

> [!WARNING]
> By default, EF loads vector properties when materializing entities, even if you only need the other properties. Embeddings can be large, so this can unnecessarily transfer and allocate substantial amounts of data. Disable automatic loading as shown [below](#avoiding-loading-vectors), or project only the properties you need.

## Avoiding loading vectors

Starting with EF Core 11, you can disable automatic loading of a vector property when entities are queried:

```csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasPostgresExtension("vector");
modelBuilder.Entity<Item>().Property(i => i.Embedding).Metadata.IsAutoLoaded = false;
}
```

The property can still be used in server-side queries, such as the distance calculation above. It is not populated on materialized entities, and an unloaded property is excluded from updates unless modified. To retrieve a vector, project it separately, for example `Select(i => new { i.Id, i.Embedding })`. Selecting it alongside an entity does not populate that entity's property, nor does returning its column from `FromSql` ([EF Core issue](https://github.com/dotnet/efcore/issues/39398)).

In EF Core 8, 9 and 10, `IsAutoLoaded` is not available. Instead, use projections like the example above to retrieve only the properties you need; queries that materialize an entity still load its vector property.
2 changes: 2 additions & 0 deletions conceptual/EFCore.PG/toc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@
href: mapping/nts.md
- name: Full text search
href: mapping/full-text-search.md
- name: Vector search
href: mapping/vector-search.md
- name: NodaTime
href: mapping/nodatime.md
- name: Arrays
Expand Down