跳到主要内容
版本:2.0.1

PGvector

QWen 3.8 中英对照 PGvector

本节将指导您配置 PGvector VectorStore,以存储文档嵌入并执行相似性搜索。

PGvector 是 PostgreSQL 的一个开源扩展,支持存储和检索由机器学习生成的嵌入向量。它提供多种功能,使用户能够识别精确最近邻和近似最近邻。该扩展旨在与 PostgreSQL 的其他特性(包括索引和查询)无缝协作。

先决条件​

首先,你需要一个启用了 vector、hstore 和 uuid-ossp 扩展的 PostgreSQL 实例的访问权限。

提示

你可以将 PGvector 数据库作为 Spring Boot 开发服务,通过 Docker Compose 或 Testcontainers 运行。另外,在本地设置 Postgres/PGVector 附录介绍了如何使用 Docker 容器在本地设置数据库。

在启动时明确启用模式初始化功能的情况下,如果 vector_store 表及其索引不存在,PgVectorStore 将尝试安装所需的数据库扩展,并创建带有索引的 vector_store 表。

你也可以手动进行如下操作:

CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS hstore;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TABLE IF NOT EXISTS vector_store (
id uuid DEFAULT uuid_generate_v4() PRIMARY KEY,
content text,
metadata json,
embedding vector(1536) // 1536 is the default embedding dimension
);

CREATE INDEX ON vector_store USING HNSW (embedding vector_cosine_ops);
提示

如果您使用不同的维度,请将 1536 替换为实际的嵌入维度。PGvector 对 HNSW 索引最多支持 2000 个维度。

接下来,如果有需要,请提供一个用于 EmbeddingModel 的 API 密钥,以生成由 PgVectorStore 存储的 embeddings。

自动配置​

备注

Spring AI 的自动配置以及 starter 模块的 artifact 名称发生了重大变更。更多信息请参考 升级说明。

然后在您的项目中添加 PgVectorStore boot starter 依赖:

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-pgvector</artifactId>
</dependency>

或者你的 Gradle build.gradle 构建文件中。

dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-pgvector'
}

向量存储实现可以为你初始化所需的 schema,但你必须通过以下任一方式明确选择启用:在相应的构造函数中指定 initializeSchema 布尔值,或在 application.properties 文件中设置 …​initialize-schema=true。

备注

这是一项破坏性变更!在早期版本的 Spring AI 中,此模式初始化操作会默认执行。

Vector Store 还需要一个 EmbeddingModel 实例来计算文档的嵌入。您可以从可用的 EmbeddingModel 实现 中选择一个。

例如,若要使用 OpenAI EmbeddingModel,请将以下依赖项添加到您的项目中:

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>

或添加到您的 Gradle build.gradle 构建文件中。

dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
提示

请参见 依赖管理 章节,将 Spring AI BOM 添加到您的构建文件中。请参见 构件仓库 章节,将 Maven Central 和/或 Snapshot 仓库添加到您的构建文件中。

要连接并配置 PgVectorStore,需要提供实例的访问信息。可以通过 Spring Boot 的 application.yml 文件提供简单配置。

spring:
datasource:
url: jdbc:postgresql://localhost:5432/postgres
username: postgres
password: postgres
ai:
vectorstore:
pgvector:
index-type: HNSW
distance-type: COSINE_DISTANCE
dimensions: 1536
max-document-batch-size: 10000 # Optional: Maximum number of documents per batch
提示

如果您通过 Docker Compose 或 Testcontainers 以 Spring Boot 开发服务的方式运行 PGvector,则无需手动配置 URL、用户名和密码,因为它们已由 Spring Boot 自动配置。

提示

查看配置参数列表,以了解默认值和配置选项。

现在你可以在应用程序中自动装配 VectorStore 并使用它。

@Autowired VectorStore vectorStore;

// ...

List<Document> documents = List.of(
new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
new Document("The World is Big and Salvation Lurks Around the Corner"),
new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));

// Add the documents to PGVector
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

配置属性​

您可以在 Spring Boot 配置中使用以下属性来自定义 PGVector 向量存储。

属性描述默认值
spring.ai.vectorstore.pgvector.index-type最近邻搜索索引类型。选项包括 NONE - 精确最近邻搜索,IVFFlat - 索引将向量划分为列表,然后搜索与查询向量最接近的那些列表的子集。与 HNSW 相比,它的构建时间更短,使用的内存更少,但查询性能较低(在速度与召回率的权衡方面)。HNSW - 创建一个多层图。与 IVFFlat 相比,它的构建时间更长,使用的内存更多,但查询性能更好(在速度与召回率的权衡方面)。与 IVFFlat 不同,它没有训练步骤,因此可以在表中没有任何数据的情况下创建索引。HNSW
spring.ai.vectorstore.pgvector.distance-type搜索距离类型。默认为 COSINE_DISTANCE。但如果向量被归一化为长度 1,则可以使用 EUCLIDEAN_DISTANCE 或 NEGATIVE_INNER_PRODUCT 以获得最佳性能。COSINE_DISTANCE
spring.ai.vectorstore.pgvector.dimensions嵌入维度。如果未显式指定,PgVectorStore 将从提供的 EmbeddingModel 中获取维度。在创建表时,维度会设置在嵌入列上。如果更改维度,则必须重新创建 vector_store 表。-
spring.ai.vectorstore.pgvector.remove-existing-vector-store-table在启动时删除现有的 vector_store 表。false
spring.ai.vectorstore.pgvector.initialize-schema是否初始化所需的架构false
spring.ai.vectorstore.pgvector.schema-name向量存储架构名称public
spring.ai.vectorstore.pgvector.table-name向量存储表名称vector_store
spring.ai.vectorstore.pgvector.schema-validation启用架构和表名验证,以确保它们是有效且已存在的对象。false
spring.ai.vectorstore.pgvector.max-document-batch-size单批处理的最大文档数量。10000
提示

如果您配置了自定义模式(schema)和/或表名,建议通过设置 spring.ai.vectorstore.pgvector.schema-validation=true 来启用模式验证。这可以确保名称的正确性,并降低 SQL 注入攻击的风险。

元数据过滤​

你可以在 PgVector 存储中使用通用的可移植元数据过滤器。

例如,你可以使用文本表达式语言:

vectorStore.similaritySearch(
SearchRequest.builder()
.query("The World")
.topK(TOP_K)
.similarityThreshold(SIMILARITY_THRESHOLD)
.filterExpression("author in ['john', 'jill'] && article_type == 'blog'").build());

或者通过编程方式使用 Filter.Expression DSL:

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.builder()
.query("The World")
.topK(TOP_K)
.similarityThreshold(SIMILARITY_THRESHOLD)
.filterExpression(b.and(
b.in("author","john", "jill"),
b.eq("article_type", "blog")).build()).build());
备注

这些过滤表达式会被转换为 PostgreSQL JSON 路径表达式,以实现高效的元数据过滤。

手动配置​

您也可以不使用 Spring Boot 自动配置,而是手动配置 PgVectorStore。为此,您需要向项目中添加 PostgreSQL 连接和 JdbcTemplate 自动配置的依赖项:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-pgvector-store</artifactId>
</dependency>
提示

请参考 依赖管理 部分,将 Spring AI BOM 添加到您的构建文件中。

要在你的应用程序中配置 PgVector,可以使用以下设置:

@Bean
public VectorStore vectorStore(JdbcTemplate jdbcTemplate, EmbeddingModel embeddingModel) {
return PgVectorStore.builder(jdbcTemplate, embeddingModel)
.dimensions(1536) // Optional: defaults to model dimensions or 1536
.distanceType(COSINE_DISTANCE) // Optional: defaults to COSINE_DISTANCE
.indexType(HNSW) // Optional: defaults to HNSW
.initializeSchema(true) // Optional: defaults to false
.schemaName("public") // Optional: defaults to "public"
.vectorTableName("vector_store") // Optional: defaults to "vector_store"
.maxDocumentBatchSize(10000) // Optional: defaults to 10000
.build();
}

本地运行 Postgres & PGVector DB​

docker run -it --rm --name postgres -p 5432:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres pgvector/pgvector

您可以按以下方式连接到该服务器:

psql -U postgres -h localhost -p 5432

访问原生客户端​

PGVector Store 实现通过 getNativeClient() 方法提供了对底层原生 JDBC 客户端(JdbcTemplate)的访问:

PgVectorStore vectorStore = context.getBean(PgVectorStore.class);
Optional<JdbcTemplate> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
JdbcTemplate jdbc = nativeClient.get();
// Use the native client for PostgreSQL-specific operations
}

原生客户端为您提供对 PostgreSQL 特定功能和操作的访问权限,而这些功能和操作可能不会通过 VectorStore 接口暴露。