PgVectore的使用
一、PgVector的安裝
參照博客
:https://blog.csdn.net/u012953777/article/details/147013691?spm=1001.2014.3001.5501
二、PgVector的使用
1、創建表與插入數據?
- ??定義向量字段??:
CREATE TABLE items (id SERIAL PRIMARY KEY,embedding VECTOR(768), -- 768維向量(如BERT模型輸出)metadata JSONB
);
- ??插入向量數據??
INSERT INTO items (embedding, metadata) VALUES ('[0.1, 0.3, ..., 0.8]', '{"title": "文檔1"}'),('[0.4, 0.2, ..., 0.7]', '{"title": "文檔2"}');
2、 索引優化?
pgvector 支持兩種索引類型,針對不同場景優化:
HNSW 索引?
- 適用場景??:高查詢速度,適合靜態數據(較少更新)。
- ??創建索引??:
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops)WITH (m = 16, ef_construction = 64);
- m:每層的最大鄰居數(默認16,范圍4-100)
- ef_construction:構建時的搜索范圍(默認100,影響構建速度和精度)
IVFFlat 索引??
??適用場景??:快速構建,適合動態數據(頻繁更新)。
??創建索引??:
CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops)WITH (lists = 100);
運算符類選擇??
vector_l2_ops
:歐氏距離(L2)
vector_ip_ops
:內積相似度
vector_cosine_ops
:余弦相似度
3、相似性搜索?
- ??基礎查詢??:
SELECT * FROM items
ORDER BY embedding <-> '[0.5, 0.1, ..., 0.9]' -- 按L2距離排序
LIMIT 10;
- 動態調整搜索參數??(HNSW):
SET hnsw.ef_search = 200; -- 擴大搜索范圍以提高召回率
- 余弦相似度查詢??:
SELECT id, 1 - (embedding <=> '[0.3, ..., 0.2]') AS cosine_similarity
FROM items
ORDER BY cosine_similarity DESC
LIMIT 5;
4、性能優化技巧??
-
??索引構建時機??:在數據導入后創建索引,避免頻繁更新導致重建。
-
??參數調優??:
- ??HNSW??:增大 ef_construction 和 ef_search 提高精度,但會降低速度
- ?IVFFlat??:增加 lists 提升準確性,但增加內存占用
-
?歸一化處理??:使用余弦相似度前,確保向量已歸一化(模長為1)
5、高級用法?
混合搜索(向量 + 條件過濾)?
SELECT * FROM items
WHERE metadata->>'category' = '科技'
ORDER BY embedding <=> '[0.2, ..., 0.6]'
LIMIT 10;
分頁查詢?
SELECT * FROM items
ORDER BY embedding <-> '[0.7, ..., 0.1]'
OFFSET 20 LIMIT 10;
6、維護操作?
- 重建索引??:
REINDEX INDEX items_hnsw_index;
- ??更新索引參數??:
ALTER INDEX items_hnsw_index SET (ef_construction = 128);
7、注意事項??
?* ?維度限制??:pgvector 支持最高 ??16,000 維??。
?* ?內存管理??:大規模數據需確保足夠內存,尤其是IVFFlat索引。
?* ?數據一致性??:頻繁更新時,IVFFlat可能需要定期重建索引。