12.10 PGvector

45 阅读6分钟

PGvector

本节将指导您设置 PGvector VectorStore 来存储文档嵌入(embeddings)并执行相似性搜索。

PGvector 是 PostgreSQL 的开源扩展,支持存储和搜索机器学习生成的嵌入。它提供了不同的功能,让用户能够识别精确和近似最近邻。它旨在与 PostgreSQL 的其他功能无缝协作,包括索引和查询。

Prerequisites(先决条件)

首先,您需要访问启用了 vectorhstoreuuid-ossp 扩展的 PostgreSQL 实例。

提示: 您可以通过 Docker ComposeTestcontainers 将 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 是默认的嵌入维度
);

CREATE INDEX ON vector_store USING HNSW (embedding vector_cosine_ops);

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

接下来,如果需要,为 EmbeddingModel 提供 API 密钥,用于生成由 PgVectorStore 存储的嵌入。

Auto-Configuration(自动配置)

注意: Spring AI 自动配置和启动器模块的构件名称发生了重大变化。请参考 升级说明 了解更多信息。

然后向您的项目中添加 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'
}

向量存储实现可以为您初始化所需的架构,但您必须通过在适当的构造函数中指定 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 添加到您的构建文件中。参考 构件仓库 部分将 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 # 可选:每批的最大文档数

提示: 如果您通过 Docker ComposeTestcontainers 将 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());

Configuration properties(配置属性)

您可以在 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_DISTANCENEGATIVE_INNER_PRODUCT 以获得最佳性能COSINE_DISTANCE
spring.ai.vectorstore.pgvector.dimensions嵌入维度。如果未明确指定,PgVectorStore 将从提供的 EmbeddingModel 中检索维度。维度在表创建时设置到嵌入列上。如果您更改维度,您也必须重新创建 vector_store 表-
spring.ai.vectorstore.pgvector.remove-existing-vector-store-table在启动时删除现有的 vector_storefalse
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

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

Metadata filtering(元数据过滤)

您可以在 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 路径表达式,以实现高效的元数据过滤。

Manual Configuration(手动配置)

您也可以手动配置 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>

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

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

@Bean
public VectorStore vectorStore(JdbcTemplate jdbcTemplate, EmbeddingModel embeddingModel) {
    return PgVectorStore.builder(jdbcTemplate, embeddingModel)
        .dimensions(1536)                    // 可选:默认为模型维度或 1536
        .distanceType(COSINE_DISTANCE)       // 可选:默认为 COSINE_DISTANCE
        .indexType(HNSW)                     // 可选:默认为 HNSW
        .initializeSchema(true)              // 可选:默认为 false
        .schemaName("public")                // 可选:默认为 "public"
        .vectorTableName("vector_store")     // 可选:默认为 "vector_store"
        .maxDocumentBatchSize(10000)         // 可选:默认为 10000
        .build();
}

Run Postgres & PGVector DB locally(本地运行 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

Accessing the Native Client(访问原生客户端)

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
}

原生客户端让您能够访问可能未通过 VectorStore 接口暴露的 PostgreSQL 特定功能和操作。