PGvector
本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。 |
本节将指导你设置 PGvector VectorStore
用于存储文档嵌入并执行相似性搜索。
PGvector 是 PostgreSQL 的开源扩展,支持存储和搜索机器学习生成的嵌入。它提供多种功能,允许用户识别精确和近似的最近邻。该扩展设计为与其他 PostgreSQL 特性(包括索引和查询)无缝协作。
先决条件
首先需要访问已启用 vector
、hstore
和 uuid-ossp
扩展的 PostgreSQL 实例。
你可以通过 Docker Compose 或 Testcontainers 将 PGvector 数据库作为 Spring Boot 开发服务运行。另外,《本地设置 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 替换为你实际使用的嵌入维度。PGvector 最多支持 2000 个 HNSW 索引维度。
|
接下来,如需生成 PgVectorStore
存储的嵌入向量,需为 EmbeddingModel 配置 API Key。
自动配置
Spring AI 的自动配置及 starter 模块的构件名称发生重大变更。详情请查阅 升级说明。 |
然后在项目中添加 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 中该模式初始化默认为自动执行。 |
向量存储还需一个 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 添加至构建文件,并参考 “Artifact 仓库 ” 部分添加 Maven Central 和/或 Snapshot Repositories 至构建配置。 |
要连接并配置 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 将 PGvector 作为 Spring Boot 开发服务运行,则无需配置 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 向量存储。
属性 | 说明 | 默认值 |
---|---|---|
|
最近邻搜索索引类型。选项包括 |
HNSW |
|
搜索距离类型。默认为 |
COSINE_DISTANCE |
|
嵌入维度。若未显式指定, |
- |
|
启动时删除现有的 |
false |
|
是否初始化所需 Schema。 |
false |
|
向量存储 Schema 名称。 |
|
|
向量存储表名称。 |
|
|
启用 Schema 和表名称验证,确保它们是有效且已存在的对象。 |
false |
|
单批次处理的最大文档数量。 |
10000 |
如果配置了自定义 Schema 和/或表名称,建议通过设置 spring.ai.vectorstore.pgvector.schema-validation=true 启用 Schema 验证。这可确保名称的正确性并降低 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 数据库
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 存储实现通过 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
接口暴露。