如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

PGvector

本节将指导您设置 PGvector VectorStore 以存储文档嵌入并执行相似性搜索。spring-doc.cadn.net.cn

PGvector 是一个用于 PostgreSQL 的开源扩展,它支持存储和搜索机器学习生成的嵌入向量。它提供了多种功能,让用户能够识别精确和近似的最近邻。它被设计为与其他 PostgreSQL 功能无缝协作,包括索引和查询。spring-doc.cadn.net.cn

前置条件

首先,您需要访问启用了 vectorhstoreuuid-ossp 扩展的 PostgreSQL 实例。spring-doc.cadn.net.cn

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

在启动时,PgVectorStore 将尝试安装所需的数据库扩展,并在不存在的情况下创建带有索引的所需 vector_store 表。spring-doc.cadn.net.cn

你也可以像下面这样手动操作:spring-doc.cadn.net.cn

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-doc.cadn.net.cn

Auto-Configuration

Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。spring-doc.cadn.net.cn

然后将 PgVectorStore Starters依赖项添加到您的项目中:spring-doc.cadn.net.cn

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

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

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

向量存储实现可以为您初始化所需的模式,但您必须通过在适当的构造函数中指定initializeSchema布尔值或在application.properties文件中设置…​initialize-schema=true来选择加入。spring-doc.cadn.net.cn

这是一个破坏性变更!在早期版本的 Spring AI 中,此架构初始化是默认发生的。

向量存储还需要一个 EmbeddingModel 实例来计算文档的嵌入向量。 您可以选择其中一个可用的 EmbeddingModel 实现spring-doc.cadn.net.cn

例如,要使用 OpenAI EmbeddingModel,请将以下依赖项添加到您的项目中:spring-doc.cadn.net.cn

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

请将以下内容添加到您的Gradle build.gradle 构建文件中。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
参考 依赖管理 部分,将 Spring AI BOM 添加到您的构建文件中。 参考 构件仓库 部分,将 Maven Central 和/或 Snapshot 仓库添加到您的构建文件中。

要连接并配置 PgVectorStore,您需要提供实例的访问详细信息。 可以通过 Spring Boot 的 application.yml 提供简单的配置。spring-doc.cadn.net.cn

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 ComposeTestcontainers 将 PGvector 作为 Spring Boot 开发服务运行, 您不需要配置 URL、用户名和密码,因为它们由 Spring Boot 自动配置。
查看 配置参数 列表以了解默认值和配置选项。

现在您可以在您的应用程序中自动装配 VectorStore 并使用它spring-doc.cadn.net.cn

@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-doc.cadn.net.cn

<property> </property> <description> </description> 默认值

spring.ai.vectorstore.pgvector.index-typespring-doc.cadn.net.cn

最近邻搜索索引类型。选项包括 NONE - 精确最近邻搜索,IVFFlat - 索引将向量划分为列表,然后搜索与查询向量最接近的列表子集。它的构建时间更快,内存使用量比 HNSW 更少,但查询性能较低(在速度-召回率权衡方面)。HNSW - 创建多层图。它的构建时间比 IVFFlat 更慢,内存使用量更大,但查询性能更好(在速度-召回率权衡方面)。与 IVFFlat 不同,它没有训练步骤,因此可以在表中没有任何数据的情况下创建索引。spring-doc.cadn.net.cn

HNSWspring-doc.cadn.net.cn

spring.ai.vectorstore.pgvector.distance-typespring-doc.cadn.net.cn

搜索距离类型。默认为 COSINE_DISTANCE。但如果向量归一化为长度 1,您可以使用 EUCLIDEAN_DISTANCENEGATIVE_INNER_PRODUCT 以获得最佳性能。spring-doc.cadn.net.cn

COSINE_DISTANCEspring-doc.cadn.net.cn

spring.ai.vectorstore.pgvector.dimensionsspring-doc.cadn.net.cn

嵌入维度。如果没有明确指定,PgVectorStore 将从提供的 EmbeddingModel 中检索维度。维度在创建表时设置到嵌入列。如果您更改维度,您还需要重新创建 vector_store 表。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.pgvector.remove-existing-vector-store-tablespring-doc.cadn.net.cn

启动时删除现有的 vector_store 表。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.vectorstore.pgvector.initialize-schemaspring-doc.cadn.net.cn

是否初始化所需的模式spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.vectorstore.pgvector.schema-namespring-doc.cadn.net.cn

向量存储模式名称spring-doc.cadn.net.cn

publicspring-doc.cadn.net.cn

spring.ai.vectorstore.pgvector.table-namespring-doc.cadn.net.cn

向量存储表名spring-doc.cadn.net.cn

vector_storespring-doc.cadn.net.cn

spring.ai.vectorstore.pgvector.schema-validationspring-doc.cadn.net.cn

启用模式和表名验证,以确保它们是有效且存在的对象。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.vectorstore.pgvector.max-document-batch-sizespring-doc.cadn.net.cn

单个批次中要处理的最大文档数。spring-doc.cadn.net.cn

10000spring-doc.cadn.net.cn

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

元数据过滤

您可以在 PgVector 存储中使用通用的、可移植的 元数据过滤器spring-doc.cadn.net.cn

例如,您可以使用文本表达式语言:spring-doc.cadn.net.cn

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:spring-doc.cadn.net.cn

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 自动配置依赖项添加到您的项目中:spring-doc.cadn.net.cn

<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,您可以使用以下设置:spring-doc.cadn.net.cn

@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

您可以像这样连接到此服务器:spring-doc.cadn.net.cn

psql -U postgres -h localhost -p 5432

访问原生客户端

PGVector Store 实现通过 JdbcTemplate 方法提供对底层原生 JDBC 客户端(JdbcTemplate)的访问:spring-doc.cadn.net.cn

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 接口公开。spring-doc.cadn.net.cn