Home

pgvector: Embeddings and vector similarity

pgvector is a PostgreSQL extension for vector similarity search. It can also be used for storing embeddings.

Learn more about Supabase's AI & Vector offering.

Concepts#

Vector similarity#

Vector similarity refers to a measure of the similarity between two related items. For example, if you have a list of products, you can use vector similarity to find similar products. To do this, you need to convert each product into a "vector" of numbers, using a mathematical model. You can use a similar model for text, images, and other types of data. Once all of these vectors are stored in the database, you can use vector similarity to find similar items.

Embeddings#

This is particularly useful if you're building on top of OpenAI's GPT-3. You can create and store embeddings which match the GPT model you're using.

Usage#

Enable the extension#

  1. Go to the Database page in the Dashboard.
  2. Click on Extensions in the sidebar.
  3. Search for "vector" and enable the extension.

Usage#

Create a table to store vectors#


_10
create table posts (
_10
id serial primary key,
_10
title text not null,
_10
body text not null,
_10
embedding vector(1536)
_10
);

Storing a vector / embedding#

In this example we'll generate a vector using the OpenAI API client, then store it in the database using the Supabase client.


_17
const title = 'First post!'
_17
const body = 'Hello world!'
_17
_17
// Generate a vector using OpenAI
_17
const embeddingResponse = await openai.createEmbedding({
_17
model: 'text-embedding-ada-002',
_17
input: body,
_17
})
_17
_17
const [{ embedding }] = embeddingResponse.data.data
_17
_17
// Store the vector in Postgres
_17
const { data, error } = await supabase.from('posts').insert({
_17
title,
_17
body,
_17
embedding,
_17
})

More pgvector and Supabase resources#