pgvector:嵌入和向量相似性
pgvector 是一个用于向量相似性搜索的 Postgres 扩展。它也可以用于存储 embeddings。
了解更多关于 Supabase 的 AI & 向量 产品。
🌐 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
如果你正在使用大型语言模型构建 AI 应用,这尤其有用。你可以为检索增强生成(RAG)创建并存储嵌入。
🌐 This is particularly useful if you're building AI applications with large language models. You can create and store embeddings for retrieval augmented generation (RAG).
用法 #
🌐 Usage
启用扩展 #
🌐 Enable the extension
- 在仪表板中转到数据库页面。
- 点击侧边栏的 扩展。
- 搜索“vector”并启用扩展。
用法 #
🌐 Usage
创建一个用于存储向量的表 #
🌐 Create a table to store vectors
1create table posts (2 id serial primary key,3 title text not null,4 body text not null,5 embedding extensions.vector(384)6);存储向量/嵌入 #
🌐 Storing a vector / embedding
在这个例子中,我们将使用 Transformer.js 生成一个向量,然后使用 Supabase 客户端将其存储到数据库中。
🌐 In this example we'll generate a vector using Transformer.js, then store it in the database using the Supabase client.
1import { pipeline } from '@xenova/transformers'2const generateEmbedding = await pipeline('feature-extraction', 'Supabase/gte-small')34const title = 'First post!'5const body = 'Hello world!'67// Generate a vector using Transformers.js8const output = await generateEmbedding(body, {9 pooling: 'mean',10 normalize: true,11})1213// Extract the embedding output14const embedding = Array.from(output.data)1516// Store the vector in Postgres17const { data, error } = await supabase.from('posts').insert({18 title,19 body,20 embedding,21})具体使用案例 #
🌐 Specific usage cases
带过滤的查询 #
🌐 Queries with filtering
如果你使用 IVFFlat 或 HNSW 索引,并且天真地根据另一列的值来过滤结果,你可能会得到比请求的行数更少的返回结果。
🌐 If you use an IVFFlat or HNSW index and naively filter the results based on the value of another column, you may get fewer rows returned than requested.
例如,下面的查询可能返回少于 5 行,即使数据库中存在对应的 5 行。这是因为嵌入索引可能不会返回 5 行符合过滤条件的记录。
🌐 For example, the following query may return fewer than 5 rows, even if 5 corresponding rows exist in the database. This is because the embedding index may not return 5 rows matching the filter.
1SELECT * FROM items WHERE category_id = 123 ORDER BY embedding <-> '[3,1,2]' LIMIT 5;要获取确切的请求行数,请使用迭代搜索继续扫描索引,直到找到足够的结果。
🌐 To get the exact number of requested rows, use iterative search to continue scanning the index until enough results are found.
更多 pgvector 和 Supabase 资源 #
🌐 More pgvector and Supabase resources