### Run Example Project Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Navigate to the examples directory, create a database for the example, and run the example application. ```sh cd examples/Loading createdb pgvector_example dotnet run ``` -------------------------------- ### Setup Development Environment Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Clone the repository, navigate to the project directory, create a test database, and run the unit tests. ```sh git clone https://github.com/pgvector/pgvector-dotnet.git cd pgvector-dotnet createdb pgvector_dotnet_test dotnet test ``` -------------------------------- ### Add Pgvector Package Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Install the Pgvector NuGet package using the dotnet CLI. ```sh dotnet add package Pgvector ``` -------------------------------- ### Add Dapper Package Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Install the Dapper integration package for pgvector. ```sh dotnet add package Pgvector.Dapper ``` -------------------------------- ### Add Entity Framework Core Package Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Install the Entity Framework Core integration package for pgvector. ```sh dotnet add package Pgvector.EntityFrameworkCore ``` -------------------------------- ### Get Vector as Array (C#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Converts a Vector object back into a float array. ```csharp var arr = vec.ToArray(); ``` -------------------------------- ### Get SparseVector Dimensions (C#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Retrieves the total number of dimensions for a SparseVector. ```csharp var dim = vec.Dimensions; ``` -------------------------------- ### Get SparseVector Non-Zero Values (C#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Retrieves an array containing the values of the non-zero elements in a SparseVector. ```csharp var values = vec.Values; ``` -------------------------------- ### Get Vector Distance with Entity Framework Core Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Calculate the distance between vectors using Entity Framework Core. ```csharp var items = await ctx.Items .Select(x => new { Entity = x, Distance = x.Embedding!.L2Distance(embedding) }) .ToListAsync(); ``` -------------------------------- ### Get SparseVector Non-Zero Indices (C#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Retrieves an array containing the indices of the non-zero elements in a SparseVector. ```csharp var indices = vec.Indices; ``` -------------------------------- ### Create NpgsqlDataSource with Vector Support (F#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Builds an NpgsqlDataSource and enables vector support. Ensure you have a valid connection string. ```fsharp let dataSourceBuilder = new NpgsqlDataSourceBuilder(connString) dataSourceBuilder.UseVector() use dataSource = dataSourceBuilder.Build() ``` -------------------------------- ### Enable Vector Extension (F#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Executes a SQL command to create the vector extension if it doesn't already exist. ```fsharp dataSource |> Sql.fromDataSource |> Sql.query "CREATE EXTENSION IF NOT EXISTS vector" |> Sql.executeNonQuery ``` -------------------------------- ### Create NpgsqlDataSource with Vector Support (Visual Basic) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Builds an NpgsqlDataSource and enables vector support. Ensure you have a valid connection string. ```vb Dim dataSourceBuilder As New NpgsqlDataSourceBuilder(connString) dataSourceBuilder.UseVector() Dim dataSource = dataSourceBuilder.Build() Dim conn = dataSource.OpenConnection() ``` -------------------------------- ### Import Entity Framework Core Library Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Import the necessary namespace for Entity Framework Core integration. ```csharp using Pgvector.EntityFrameworkCore; ``` -------------------------------- ### Configure Dapper and NpgsqlDataSource Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Configure Dapper to handle vector types and set up the NpgsqlDataSource with vector support. ```csharp SqlMapper.AddTypeHandler(new VectorTypeHandler()); var dataSourceBuilder = new NpgsqlDataSourceBuilder(connString); dataSourceBuilder.UseVector(); await using var dataSource = dataSourceBuilder.Build(); var conn = dataSource.OpenConnection(); ``` -------------------------------- ### Import Dapper Library Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Import the necessary namespace for Dapper integration. ```csharp using Pgvector.Dapper; ``` -------------------------------- ### Create Npgsql Data Source with Vector Support Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Build an Npgsql data source and enable vector type support. This is a prerequisite for using vector types with Npgsql. ```csharp var dataSourceBuilder = new NpgsqlDataSourceBuilder(connString); dataSourceBuilder.UseVector(); await using var dataSource = dataSourceBuilder.Build(); var conn = dataSource.OpenConnection(); ``` -------------------------------- ### Enable Vector Extension (Visual Basic) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Executes a SQL command to create the vector extension if it doesn't already exist and reloads types. ```vb Using cmd As New NpgsqlCommand("CREATE EXTENSION IF NOT EXISTS vector", conn) cmd.ExecuteNonQuery() End Using conn.ReloadTypes() ``` -------------------------------- ### Enable Vector Extension in PostgreSQL Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Execute a SQL command to create the 'vector' extension in your PostgreSQL database if it doesn't already exist. Ensure to reload types after enabling the extension. ```csharp await using (var cmd = new NpgsqlCommand("CREATE EXTENSION IF NOT EXISTS vector", conn)) { await cmd.ExecuteNonQueryAsync(); } conn.ReloadTypes(); ``` -------------------------------- ### Configure Entity Framework Core Connection Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Configure the DbContext to use PostgreSQL with the vector extension enabled. ```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseNpgsql("connString", o => o.UseVector()); } ``` -------------------------------- ### Import Pgvector Library (F#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Imports the necessary Pgvector namespace for F# usage. ```fsharp open Pgvector ``` -------------------------------- ### Enable Vector Extension with Entity Framework Core Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Configure the DbContext to enable the PostgreSQL vector extension. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasPostgresExtension("vector"); } ``` -------------------------------- ### Create Items Table (F#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Creates a SQL table named 'items' with an 'id' and an 'embedding' column of type vector. ```fsharp dataSource |> Sql.fromDataSource |> Sql.query "CREATE TABLE items (id serial PRIMARY KEY, embedding vector(3))" |> Sql.executeNonQuery ``` -------------------------------- ### Add Approximate HNSW Index (F#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Creates a HNSW (Hierarchical Navigable Small World) index on the 'embedding' column for efficient nearest neighbor searches. ```fsharp dataSource |> Sql.fromDataSource |> Sql.query "CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)" |> Sql.executeNonQuery ``` -------------------------------- ### Query Nearest Neighbors with Entity Framework Core Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Retrieve the nearest neighbors using Entity Framework Core and the L2Distance method. ```csharp var embedding = new Vector(new float[] { 1, 1, 1 }); var items = await ctx.Items .OrderBy(x => x.Embedding!.L2Distance(embedding)) .Take(5) .ToListAsync(); foreach (Item item in items) { if (item.Embedding != null) { Console.WriteLine(item.Embedding); } } ``` -------------------------------- ### Create Dapper Items Table Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Create a SQL table with a vector column using Dapper. ```csharp conn.Execute("CREATE TABLE items (id serial PRIMARY KEY, embedding vector(3))"); ``` -------------------------------- ### Create HalfVector from Array (C#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Initializes a HalfVector object from a Half array. Cast values to Half if necessary. ```csharp var vec = new HalfVector(new Half[] { (Half)1, (Half)2, (Half)3 }); ``` -------------------------------- ### Create Items Table (Visual Basic) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Creates a SQL table named 'items' with an 'id' and an 'embedding' column of type vector. ```vb Using cmd As New NpgsqlCommand("CREATE TABLE items (id serial PRIMARY KEY, embedding vector(3))", conn) cmd.ExecuteNonQuery() End Using ``` -------------------------------- ### Create SparseVector from Dictionary (C#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Initializes a SparseVector object from a dictionary mapping indices to non-zero float values. Specify the total number of dimensions. ```csharp var dictionary = new Dictionary(); dictionary.Add(0, 1); dictionary.Add(2, 2); dictionary.Add(4, 3); var vec = new SparseVector(dictionary, 6); ``` -------------------------------- ### Create SparseVector from Array (C#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Initializes a SparseVector object from a float array, where non-zero elements are preserved. ```csharp var vec = new SparseVector(new float[] { 1, 0, 2, 0, 3, 0 }); ``` -------------------------------- ### Query Nearest Neighbors (F#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Selects items from the 'items' table, ordering by the nearest neighbors to a given embedding. Results are mapped to an 'Item' record. ```fsharp type Item = { Id: int Embedding: Vector } dataSource |> Sql.fromDataSource |> Sql.query "SELECT * FROM items ORDER BY embedding <-> @embedding LIMIT 5" |> Sql.parameters [ "embedding", Sql.parameter parameter ] |> Sql.execute (fun read -> { Id = read.int "id" Embedding = read.fieldValue "embedding" }) |> printfn "%A" ``` -------------------------------- ### Add Approximate HNSW Index (Visual Basic) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Creates a HNSW (Hierarchical Navigable Small World) index on the 'embedding' column for efficient nearest neighbor searches. ```vb Using cmd As New NpgsqlCommand("CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)", conn) cmd.ExecuteNonQuery() End Using ``` -------------------------------- ### Create Vector from Array (C#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Initializes a Vector object from a float array. ```csharp var vec = new Vector(new float[] { 1, 2, 3 }); ``` -------------------------------- ### Query Nearest Neighbors (Visual Basic) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Selects items from the 'items' table, ordering by the nearest neighbors to a given embedding. Reads and prints the first column of each row. ```vb Using cmd As New NpgsqlCommand("SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5", conn) Dim embedding As New Vector(New Single() {1, 1, 1}) cmd.Parameters.AddWithValue(embedding) Using reader As NpgsqlDataReader = cmd.ExecuteReader() While reader.Read() Console.WriteLine(reader.GetValue(0)) End While End Using End Using ``` -------------------------------- ### Add Approximate Nearest Neighbor (HNSW) Index Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Create an HNSW index on the 'embedding' column to speed up nearest neighbor searches. Use 'vector_l2_ops' for Euclidean distance. ```csharp await using (var cmd = new NpgsqlCommand("CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)", conn)) { await cmd.ExecuteNonQueryAsync(); } ``` -------------------------------- ### Enable Vector Extension with Dapper Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Ensure the vector extension is enabled in the database and reload types for Dapper. ```csharp conn.Execute("CREATE EXTENSION IF NOT EXISTS vector"); conn.ReloadTypes(); ``` -------------------------------- ### Create Table with Vector Column Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Define a SQL table with a primary key and a column of type 'vector' with a specified dimension. This sets up the schema for storing vector embeddings. ```csharp await using (var cmd = new NpgsqlCommand("CREATE TABLE items (id serial PRIMARY KEY, embedding vector(3))", conn)) { await cmd.ExecuteNonQueryAsync(); } ``` -------------------------------- ### Query Items Within Distance with Entity Framework Core Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Retrieve items within a specified distance using Entity Framework Core. ```csharp var items = await ctx.Items .Where(x => x.Embedding!.L2Distance(embedding) < 5) .ToListAsync(); ``` -------------------------------- ### Find Nearest Neighbors with Vector Distance Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Query the 'items' table to find the nearest neighbors to a given vector using the '<->' operator for Euclidean distance. Results are limited to 5. ```csharp await using (var cmd = new NpgsqlCommand("SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5", conn)) { var embedding = new Vector(new float[] { 1, 1, 1 }); cmd.Parameters.AddWithValue(embedding); await using (var reader = await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { Console.WriteLine(reader.GetValue(0)); } } } ``` -------------------------------- ### Insert Vector with Entity Framework Core Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Insert a new vector into the items table using Entity Framework Core. ```csharp ctx.Items.Add(new Item { Embedding = new Vector(new float[] { 1, 1, 1 }) }); ctx.SaveChanges(); ``` -------------------------------- ### Define Entity Framework Core Model Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Define a C# model class with a vector column for Entity Framework Core. ```csharp public class Item { public int Id { get; set; } [Column(TypeName = "vector(3)")] public Vector? Embedding { get; set; } } ``` -------------------------------- ### Query Nearest Neighbors with Dapper Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Retrieve the nearest neighbors to a given vector using Dapper and the '<->' operator. ```csharp var embedding = new Vector(new float[] { 1, 1, 1 }); var items = conn.Query("SELECT * FROM items ORDER BY embedding <-> @embedding LIMIT 5", new { embedding }); foreach (Item item in items) { Console.WriteLine(item.Embedding); } ``` -------------------------------- ### Insert Vector with Dapper Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Insert a new vector into the items table using Dapper. ```csharp var embedding = new Vector(new float[] { 1, 1, 1 }); conn.Execute(@"INSERT INTO items (embedding) VALUES (@embedding)", new { embedding }); ``` -------------------------------- ### Define Dapper Item Class Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Define a C# class to represent items with a vector embedding for Dapper. ```csharp public class Item { public int Id { get; set; } public Vector? Embedding { get; set; } } ``` -------------------------------- ### Insert Vector into Items Table (F#) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Inserts a new row into the 'items' table with a specified vector embedding. Uses a parameterized query. ```fsharp let embedding = new Vector([| 1f; 1f; 1f |]) let parameter = new NpgsqlParameter("", embedding) dataSource |> Sql.fromDataSource |> Sql.query "INSERT INTO items (embedding) VALUES (@embedding)" |> Sql.parameters [ "embedding", Sql.parameter parameter ] |> Sql.executeNonQuery ``` -------------------------------- ### Add Approximate Index with Entity Framework Core Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Add an approximate nearest neighbor index (HNSW or IVFFlat) to the vector column using Entity Framework Core. ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasIndex(i => i.Embedding) .HasMethod("hnsw") .HasOperators("vector_l2_ops") .HasStorageParameter("m", 16) .HasStorageParameter("ef_construction", 64); // or modelBuilder.Entity() .HasIndex(i => i.Embedding) .HasMethod("ivfflat") .HasOperators("vector_l2_ops") .HasStorageParameter("lists", 100); } ``` -------------------------------- ### Add Approximate Index with Dapper Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Add an approximate nearest neighbor index (HNSW or IVFFlat) to the vector column using Dapper. ```csharp conn.Execute("CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)"); // or conn.Execute("CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)"); ``` -------------------------------- ### Insert Vector into Items Table (Visual Basic) Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Inserts a new row into the 'items' table with a specified vector embedding. Uses a parameterized query. ```vb Using cmd As New NpgsqlCommand("INSERT INTO items (embedding) VALUES ($1)", conn) Dim embedding As New Vector(New Single() {1, 1, 1}) cmd.Parameters.AddWithValue(embedding) cmd.ExecuteNonQuery() End Using ``` -------------------------------- ### Insert Vector into Table Source: https://github.com/pgvector/pgvector-dotnet/blob/master/README.md Insert a new row into the 'items' table, providing a vector embedding as a parameter. The Vector type from Pgvector is used to represent the embedding. ```csharp await using (var cmd = new NpgsqlCommand("INSERT INTO items (embedding) VALUES ($1)", conn)) { var embedding = new Vector(new float[] { 1, 1, 1 }); cmd.Parameters.AddWithValue(embedding); await cmd.ExecuteNonQueryAsync(); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.