Installing the pgvector and pgvectorscale extensions
If not already installed, install thevector and vectorscale extensions on your database.
Creating the table for storing embeddings using pgvector
Vectors inside of the database are stored in regular tables usingvector columns. The vector column type is provided by the pgvector extension. A common way to store vectors is alongside the data they are embedding. For example, to store embeddings for documents, a common table structure is:
contents column) and the embedded vector.
You may ask why not just add an embedding column to the document table? The answer is that there is a limit on the length of text an embedding can encode and so there needs to be a one-to-many relationship between the full document and its embeddings.
The above table is just an illustration, it’s totally fine to have a table without a foreign key and/or without a metadata column. The important thing is to have a column with the data being embedded and the vector in the same row, enabling you to return the raw data for a given similarity search query
The vector type can specify an optional number of dimensions (1,538) in the example above). If specified, it enforces the constraint that all vectors in the column have that number of dimensions. A plain VECTOR (without specifying the number of dimensions) column is also possible and allows a variable number of dimensions.
Query the vector embeddings
The canonical query is:<=> operator). Other distance functions are available, see the discussion.
The available distance types and their operators are:
If you are using an index, you need to make sure that the distance function used in index creation is the same one used during query (see below). This is important because if you create your index with one distance function but query with another, your index cannot be used to speed up the query.
Indexing the vector data using indexes provided by pgvector and pgvectorscale
Indexing helps speed up similarity queries of the basic form:ORDER BY contains a distance measure against a constant or a pseudo-constant.
Note that if performing a query without an index, you always get an exact result, but the query is slow (it has to read all of the data you store for every query). With an index, your queries are an order-of-magnitude faster, but the results are approximate (because there are no known indexing techniques that are exact see here for more).
Nevertheless, there are excellent approximate algorithms. There are 3 different indexing algorithms available on : StreamingDiskANN, HNSW, and ivfflat. Below is the trade-offs between these algorithms:
You can see benchmarks in the blog.
For most use cases, the StreamingDiskANN index is recommended.
Each of these indexes has a set of build-time options for controlling the speed/accuracy trade-off when creating the index and an additional query-time option for controlling accuracy during a particular query.
You can see the details of each index below.
StreamingDiskANN index
The StreamingDiskANN index is a graph-based algorithm that was inspired by the DiskANN algorithm. You can read more about it in How We Made as Fast as Pinecone for Vector Data. To create an index nameddocument_embedding_idx on table document_embedding having a vector column named embedding, with cosine distance metric, run:
<=> operator in your queries. StreamingDiskANN also supports L2 distance:
<-> operator in queries.
These examples create the index with smart defaults for all parameters not listed. These should be the right values for most cases. But if you want to delve deeper, the available parameters are below.
StreamingDiskANN index build-time parameters
These parameters can be set when an index is created.
An example of how to set the
num_neighbors parameter is:
StreamingDiskANN query-time parameters
You can also set two parameters to control the accuracy vs. query speed trade-off at query time. We suggest adjustingdiskann.query_rescore to fine-tune accuracy.
You can set the value by using
SET before executing a query. For example:
LOCAL which will
be reset after the end of the transaction:
StreamingDiskANN index-supported queries
You need to use the cosine-distance embedding measure (<=>) in your ORDER BY clause. A canonical query would be:
pgvector HNSW
Pgvector provides a graph-based indexing algorithm based on the popular HNSW algorithm. To create an index nameddocument_embedding_idx on table document_embedding having a vector column named embedding, run:
vector_cosine_ops. There are also “ops” classes for Euclidean distance and negative inner product:
Pgvector HNSW also includes several index build-time and query-time parameters.
pgvector HNSW index build-time parameters
These parameters can be set at index build time:
An example of how to set the m parameter is:
pgvector HNSW query-time parameters
You can also set a parameter to control the accuracy vs. query speed trade-off at query time. The parameter is calledhnsw.ef_search. This parameter specifies the size of the dynamic candidate list used during search. Defaults to 40. Higher values improve query accuracy while making the query slower.
You can set the value by running:
LOCAL:
pgvector HNSW index-supported queries
You need to use the distance operator (<=>, <->, or <#>) matching the ops class you used during index creation in your ORDER BY clause. A canonical query would be:
pgvector ivfflat
Pgvector provides a clustering-based indexing algorithm. The blog post describes how it works in detail. It provides the fastest index-build speed but the slowest query speeds of any indexing algorithm. To create an index nameddocument_embedding_idx on table document_embedding having a vector column named embedding, run:
vector_cosine_ops. There are also “ops” classes for Euclidean distance and negative inner product:
Note: ivfflat should never be created on empty tables because it needs to cluster data, and that only happens when an index is first created, not when new rows are inserted or modified. Also, if your table undergoes a lot of modifications, you need to rebuild this index occasionally to maintain good accuracy. See the blog post for details.
Pgvector ivfflat has a
lists index parameter that should be set. See the next section.
pgvector ivfflat index build-time parameters
Pgvector has alists parameter that should be set as follows:
For datasets with less than one million rows, use lists = rows / 1000.
For datasets with more than one million rows, use lists = sqrt(rows).
It is generally advisable to have at least 10 clusters.
You can use the following code to simplify creating ivfflat indexes:
pgvector ivfflat query-time parameters
You can also set a parameter to control the accuracy vs. query speed tradeoff at query time. The parameter is calledivfflat.probes. This parameter specifies the number of clusters searched during a query. It is recommended to set this parameter to sqrt(lists) where lists is the parameter used above during index creation. Higher values improve query accuracy while making the query slower.
You can set the value by running:
LOCAL:
pgvector ivfflat index-supported queries
You need to use the distance operator (<=>, <->, or <#>) matching the ops class you used during index creation in your ORDER BY clause. A canonical query would be: