PGvector
本小节将引导你完成PGvector的设置VectorStore
以存储文档嵌入并执行相似性搜索。
PGvector 是 PostgreSQL 的开源扩展,支持存储和搜索机器学习生成的嵌入。它提供了不同的功能,让用户可以识别精确和近似的最近邻。它旨在与其他 PostgreSQL 功能无缝协作,包括索引和查询。
前提条件
首先,您需要访问启用的 PostgreSQL 实例vector
,hstore
和uuid-ossp
扩展。
您可以通过 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 索引。 |
接下来,如果需要,EmbeddingModel 的 API 密钥用于生成由PgVectorStore
.
自动配置
Spring AI 自动配置、入门模块的工件名称发生了重大变化。 有关更多信息,请参阅升级说明。 |
然后将 PgVectorStore 引导Starters依赖项添加到您的项目中:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-pgvector</artifactId>
</dependency>
或 Gradlebuild.gradle
构建文件。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-pgvector'
}
矢量存储实现可以为您初始化所需的架构,但您必须通过指定initializeSchema
布尔值或通过…initialize-schema=true
在application.properties
文件。
这是一个重大变化!在早期版本的 Spring AI 中,默认情况下会发生此模式初始化。 |
矢量存储还需要一个EmbeddingModel
实例来计算文档的嵌入。
您可以选择一个可用的 EmbeddingModel 实现。
例如,若要使用 OpenAI EmbeddingModel,请向项目添加以下依赖项:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
或 Gradlebuild.gradle
构建文件。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
请参阅依赖项管理部分,将 Spring AI BOM 添加到构建文件中。 请参阅 Artifact Repositories 部分,将 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 矢量存储。
属性 | 描述 | 默认值 |
---|---|---|
|
最近邻搜索索引类型。选项包括 |
高净资产体系 |
|
搜索距离类型。默认为 |
COSINE_DISTANCE |
|
嵌入维度。如果未显式指定,PgVectorStore 将从提供的 |
- |
|
删除现有的 |
false |
|
是否初始化所需的架构 |
false |
|
矢量存储架构名称 |
|
|
矢量存储表名称 |
|
|
启用架构和表名验证,以确保它们是有效的现有对象。 |
false |
|
单个批次中要处理的最大文档数。 |
10000 |
如果配置自定义架构和/或表名称,请考虑通过将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 路径表达式,以实现高效的元数据过滤。 |
手动配置
您可以手动配置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 实现提供对底层本机 JDBC 客户端 (JdbcTemplate
) 通过getNativeClient()
方法:
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
接口。