前言
在向量搜索中,召回率是一个关键指标,它衡量搜索结果的相关性。然而,提高召回率往往会牺牲其他指标,如索引大小或查询延迟。为了平衡这些权衡,混合搜索技术应运而生。本文将介绍如何在 PostgreSQL 中结合 pgvector 实现混合搜索,并探讨其对搜索结果的影响。
前提条件
必须使用PostgreSQL中的 pgvector 插件和 tsearch2 函数。请先检查一下,你所使用的PostgreSQL 是否支持。
什么是混合搜索?
混合搜索是将向量相似性搜索与其他搜索方法(如全文搜索)相结合的一种技术。它通过多种搜索方法对同一数据进行搜索,对每种方法的结果进行排序,然后合并所有结果以确定最终排名。混合搜索的目标是提高搜索结果的质量,即提高召回率。
在混合搜索中,互惠排序融合(RRF)是一种常用的评分方法。RRF 通过加权评分系统,根据排名对结果进行评分。公式如下:
1.0 / (result_search_1_rank + rrf_k) +
1.0 / (result_search_2_rank + rrf_k)
其中,rrf_k
是一个常数,用于控制权重。较小的 rrf_k
值会赋予排名较高的项目更大的权重。
PostgreSQL 中的全文搜索
PostgreSQL 提供了多种全文搜索方法,如 tsearch2 和 pg_trgm,以及扩展如 pg_bigm 和 PGroonga。在本文中,我们将使用 tsearch2 函数,并结合 GIN 索引和 ts_rank_cd 结果排序方法。
示例:在 PostgreSQL 中构建混合搜索
数据准备
我们使用 Python 的 faker
库生成随机文本数据,并使用 multi-qa-MiniLM-L6-cos-v1
句子转换器模型计算向量嵌入。以下是 Python 代码:
from faker import Faker
import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformerfake = Faker()
sentences = [fake.sentence(nb_words=50) for i in range(0, 50_000)]model = SentenceTransformer('multi-qa-MiniLM-L6-cos-v1')
embeddings = model.encode(sentences)conn = psycopg.connect(dbname="<YOUR DATABASE>", autocommit=True)
cur = conn.cursor()with cur.copy("COPY products (description, embedding) FROM STDIN WITH (FORMAT BINARY)") as copy:copy.set_types(["text", "vector"])for content, embedding in zip(sentences, embeddings):copy.write_row((content, embedding))cur.close()
conn.close()
数据库设置
在 PostgreSQL 中,我们需要创建表和索引:
-- 创建扩展
CREATE EXTENSION vector;-- 创建表
CREATE TABLE products (id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,description text NOT NULL,embedding vector(384) NOT NULL
);-- 创建 RRF 评分函数
CREATE OR REPLACE FUNCTION rrf_score(rank int, rrf_k int DEFAULT 50)
RETURNS numeric
LANGUAGE SQL
IMMUTABLE PARALLEL SAFE
AS $$SELECT COALESCE(1.0 / ($1 + $2), 0.0);
$$;-- 创建全文搜索索引
CREATE INDEX ON productsUSING GIN (to_tsvector('english', description));-- 创建向量搜索索引
CREATE INDEX ON productsUSING hnsw(embedding vector_cosine_ops) WITH (ef_construction=256);
搜索实现
单独的向量相似性搜索
SELECT id, description, rank() OVER (ORDER BY $1 <=> embedding) AS rank
FROM products
ORDER BY $1 <=> embedding
LIMIT 10;
单独的全文搜索
SELECTid,description,rank() OVER (ORDER BY ts_rank_cd(to_tsvector(description), plainto_tsquery('travel computer')) DESC) AS rank
FROM products
WHEREplainto_tsquery('english', 'travel computer') @@ to_tsvector('english', description)
ORDER BY rank
LIMIT 10;
混合搜索
SELECTsearches.id,searches.description,sum(rrf_score(searches.rank)) AS score
FROM ((SELECTid,description,rank() OVER (ORDER BY $1 <=> embedding) AS rankFROM productsORDER BY $1 <=> embeddingLIMIT 40)UNION ALL(SELECTid,description,rank() OVER (ORDER BY ts_rank_cd(to_tsvector(description), plainto_tsquery('travel computer')) DESC) AS rankFROM productsWHEREplainto_tsquery('english', 'travel computer') @@ to_tsvector('english', description)ORDER BY rankLIMIT 40)
) searches
GROUP BY searches.id, searches.description
ORDER BY score DESC
LIMIT 10;
性能分析
通过 EXPLAIN ANALYZE
,我们可以看到 PostgreSQL 在混合搜索中同时使用了向量索引和全文搜索索引。以下是执行计划的输出:
Limit (cost=789.66..789.69 rows=10 width=365) (actual time=8.516..8.519 rows=10 loops=1)-> Sort (cost=789.66..789.86 rows=80 width=365) (actual time=8.515..8.518 rows=10 loops=1)Sort Key: (sum(COALESCE((1.0 / (("*SELECT* 1".rank + 50))::numeric), 0.0))) DESCSort Method: top-N heapsort Memory: 32kB-> GroupAggregate (cost=785.53..787.93 rows=80 width=365) (actual time=8.435..8.495 rows=79 loops=1)Group Key: "*SELECT* 1".id, "*SELECT* 1".description-> Sort (cost=785.53..785.73 rows=80 width=341) (actual time=8.430..8.436 rows=80 loops=1)Sort Key: "*SELECT* 1".id, "*SELECT* 1".descriptionSort Method: quicksort Memory: 53kB-> Append (cost=84.60..783.00 rows=80 width=341) (actual time=0.877..8.414 rows=80 loops=1)-> Subquery Scan on "*SELECT* 1" (cost=84.60..125.52 rows=40 width=341) (actual time=0.877..0.949 rows=40 loops=1)-> Limit (cost=84.60..125.12 rows=40 width=349) (actual time=0.876..0.945 rows=40 loops=1)-> WindowAgg (cost=84.60..50736.60 rows=50000 width=349) (actual time=0.876..0.942 rows=40 loops=1)-> Index Scan using products_embeddings_hnsw_idx on products (cost=84.60..49861.60 rows=50000 width=341) (actual time=0.872..0.919 rows=40 loops=1)Order By: (embedding <=> '<redacted>'::vector)-> Subquery Scan on "*SELECT* 2" (cost=656.58..657.08 rows=40 width=341) (actual time=7.448..7.458 rows=40 loops=1)-> Limit (cost=656.58..656.68 rows=40 width=345) (actual time=7.447..7.453 rows=40 loops=1)-> Sort (cost=656.58..656.89 rows=124 width=345) (actual time=7.447..7.449 rows=40 loops=1)Sort Key: (rank() OVER (?))Sort Method: top-N heapsort Memory: 44kB-> WindowAgg (cost=588.18..652.66 rows=124 width=345) (actual time=7.357..7.419 rows=139 loops=1)-> Sort (cost=588.18..588.49 rows=124 width=337) (actual time=7.355..7.363 rows=139 loops=1)Sort Key: (ts_rank_cd(to_tsvector(products_1.description), plainto_tsquery('travel computer'::text))) DESCSort Method: quicksort Memory: 79kB-> Bitmap Heap Scan on products products_1 (cost=30.38..583.87 rows=124 width=337) (actual time=0.271..7.323 rows=139 loops=1)Recheck Cond: ('''travel'' & ''comput'''::tsquery @@ to_tsvector('english'::regconfig, description))Heap Blocks: exact=138-> Bitmap Index Scan on products_description_gin_idx (cost=0.00..30.35 rows=124 width=0) (actual time=0.186..0.186 rows=139 loops=1)Index Cond: (to_tsvector('english'::regconfig, description) @@ '''travel'' & ''comput'''::tsquery)
Planning Time: 0.193 ms
Execution Time: 8.553 ms
从执行计划可以看出,PostgreSQL 在混合搜索中同时使用了向量索引和全文搜索索引,查询效率较高。
为什么会使用这样的方案,rerank模型不香吗?
我们自己使用spring ai 框架搭建的大模型应用平台的底层推理引擎是 ollama,因此我们重度依赖ollama 所提供的推理能力,然而ollama 并不支持rerank模型的服务,为了解决召回重排的问题,在不进一步增大部署实施难度的情况下,采用了混合检索的方案进行简化。
其次通过架构的讨论,在算力不强的环境下,能够尽量压榨PostgreSQL 的能力,提高召回,也是压缩成本的一个考虑。
spring ai 官方也将提供类似方案进行重排
已经在 spring ai 1.1.x 的pull request 中有大神实现了类似的方案。
https://github.com/spring-projects/spring-ai/pull/1097
后续在我们自己平台上的进一步使用计划
本文展示了如何在 PostgreSQL 中结合 pgvector 实现混合搜索,并通过示例验证了其可行性。然而,这只是一个起点。未来的工作包括:
- 评估混合搜索的性能:在更大的数据集上测试混合搜索的召回率、查询延迟和每秒查询次数(QPS),并与单独的向量搜索进行对比。
- 优化参数:调整
rrf_k
等参数,以找到最佳的混合搜索策略。 - 探索其他全文搜索算法:分析 PostgreSQL 中不同的全文搜索算法(如 pg_trgm、pg_bigm 等)对混合搜索结果的影响。
混合搜索为提升搜索结果的相关性提供了一种有效的途径。通过结合向量相似性搜索和全文搜索的优势,我们可以在不显著增加查询延迟的情况下,提高搜索结果的召回率。