/pgvector-go

pgvector support for Go

Primary LanguageGoMIT LicenseMIT

pgvector-go

pgvector support for Go

Supports pgx, pg, and Bun

Build Status

Getting Started

Run:

go get github.com/pgvector/pgvector-go

Import the package:

import "github.com/pgvector/pgvector-go"

And follow the instructions for your database library:

pgx

Insert a vector

_, err := conn.Exec(ctx, "INSERT INTO items (embedding) VALUES ($1)", pgvector.NewVector([]float32{1, 2, 3}))

Get the nearest neighbors to a vector

rows, err := conn.Query(ctx, "SELECT id FROM items ORDER BY embedding <-> $1 LIMIT 5", pgvector.NewVector([]float32{1, 2, 3}))

See a full example

pg

Add a vector column

type Item struct {
    Embedding pgvector.Vector `pg:"type:vector(3)"`
}

Insert a vector

item := Item{
    Embedding: pgvector.NewVector([]float32{1, 2, 3}),
}
_, err := db.Model(&item).Insert()

Get the nearest neighbors to a vector

var items []Item
err := db.Model(&items).OrderExpr("embedding <-> ?", pgvector.NewVector([]float32{1, 2, 3})).Limit(5).Select()

See a full example

Bun

Add a vector column

type Item struct {
    Embedding pgvector.Vector `bun:"type:vector(3)"`
}

Insert a vector

item := Item{
    Embedding: pgvector.NewVector([]float32{1, 2, 3}),
}
_, err := db.NewInsert().Model(&item).Exec(ctx)

Get the nearest neighbors to a vector

var items []Item
err := db.NewSelect().Model(&items).OrderExpr("embedding <-> ?", pgvector.NewVector([]float32{1, 2, 3})).Limit(5).Scan(ctx)

See a full example

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

To get started with development:

git clone https://github.com/pgvector/pgvector-go.git
cd pgvector-go
go mod tidy
createdb pgvector_go_test
go test ./...