PGvector
本节将指导您如何设置 PGvector VectorStore
以存储文档嵌入
并执行相似性搜索
。
PGvector 是一个针对 PostgreSQL 的开源扩展,它使得存储和搜索由机器学习生成的嵌入向量成为可能。该扩展提供了多种功能,让用户能够识别精确及近似的最近邻。其设计旨在与 PostgreSQL 的其他特性无缝协作,包括索引和查询功能。
先决条件
首先,您需要访问已启用 vector
、hstore
和 uuid-ossp
扩展的 PostgreSQL 实例。
您可以通过
Docker Compose
或Testcontainers
作为 Spring Boot 开发服务运行 PGvector 数据库。此外, 本地 Postgres/PGVector 设置 附录展示了如何使用 Docker 容器在本地设置数据库。
启动时,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
替换为实际值。对于 HNSW 索引,PGvector 最多支持 2000
个维度。
接下来,若需使用,获取一个 EmbeddingModel 的 API 密钥,以生成由 PgVectorStore
存储的嵌入向量。
自动配置
然后在您的项目中添加 PgVectorStore 启动器依赖项:
<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'
}
向量存储实现可以为您初始化所需的架构,但您必须通过在适当的构造函数中指定 initializeSchema 布尔值,或在 application.properties
文件中设置...initialize-schema=true
来选择启用。
向量存储还需要一个 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'
}
要连接并配置 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
现在,您可以在应用程序中自动配置 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 向量存储。
属性 (Property) | 描述 (Description) | 默认值 (Default value) |
---|---|---|
spring.ai.vectorstore.pgvector.index-type |
最近邻搜索索引类型。选项为 NONE - 精确最近邻搜索,IVFFlat - 将向量划分为列表,然后搜索最接近查询向量的列表子集(构建时间更快且使用更少内存,但查询性能较低),HNSW - 创建多层图(构建时间更慢且使用更多内存,但查询性能更好)。无需像 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 |
是否初始化所需的模式 (Schema)。 | false |
spring.ai.vectorstore.pgvector.schema-name |
向量存储模式 (Schema) 名称。 | 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 |
元数据过滤
您可以利用通用且可移植的 元数据过滤器 与 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());
手动配置
你可以选择手动配置 PgVectorStore
,而非依赖 Spring Boot 的自动配置。为此,你需要在项目中添加 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>
要在您的应用程序中配置 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 数据库
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 接口公开。
最后编辑:Jeebiz 更新时间:2025-09-28 09:15