PGvector

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

PGvector 是一个开源的 PostgreSQL 扩展,它使得存储和搜索机器学习生成的嵌入变得可能。它提供了不同的功能,让用户能够识别精确和近似的最近邻居。它旨在与其他 PostgreSQL 特性无缝配合,包括索引和查询。

先决条件

首先,您需要访问启用了 vector、hstore 和 uuid-ossp 扩展的 PostgreSQL 实例。

《设置本地 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 替换为实际的嵌入维度。

接下来,如果需要,为 EmbeddingClient 生成由 PgVectorStore 存储的嵌入的 API 密钥。

依赖关系

User wants HTML fragments translated from English to Chinese, ensuring correct formatting.这里是翻译后的HTML片段:

然后将 PgVectorStore 启动器依赖项添加到您的项目中:

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

或者添加到您的 Gradle build.gradle 构建文件中。

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

矢量存储还需要一个 EmbeddingClient 实例来计算文档的嵌入。您可以选择其中一个可用的 EmbeddingClient 实现

例如,要使用 OpenAI EmbeddingClient,请将以下依赖项添加到您的项目中:

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

或者添加到您的 Gradle build.gradle 构建文件中。

dependencies {
    implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter'
}
请参阅 Dependency Management 部分,将 Spring AI BOM 添加到您的构建文件中。请参阅 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
		dimension: 1536
查看 配置参数 列表,了解默认值和配置选项。

现在,您可以在应用程序中自动连接 PgVector Store 并使用它

请检查并告诉我是否符合您的要求。
@Autowired 向量存储 vectorStore;

// ...

List <Document> 文档列表 = List.of(
    new Document("Spring AI 真棒!! Spring AI 真棒!! Spring AI 真棒!! Spring AI 真棒!! Spring AI 真棒!!", Map.of("meta1", "meta1")),
    new Document("世界很大,拯救就在转角处"),
    new Document("你向前走着面对过去,向后转向未来。", Map.of("meta2", "meta2")));

// 将文档添加到 PGVector
vectorStore.add(List.of(文档));

// 检索与查询相似的文档
List<Document> 结果 = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5));

手动配置

你可以手动配置 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, EmbeddingClient embeddingClient) {
	return new PgVectorStore(jdbcTemplate, embeddingClient);
}

元数据过滤

您可以利用PgVector存储的通用、便携的元数据过滤器

例如,您可以使用文本表达式语言:

vectorStore.similaritySearch(
    SearchRequest.defaults()
    .withQuery("The World")
    .withTopK(TOP_K)
    .withSimilarityThreshold(SIMILARITY_THRESHOLD)
    .withFilterExpression("author in ['john', 'jill'] && article_type == 'blog'"));

或者以编程方式使用Filter.Expression DSL:

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.defaults()
    .withQuery("The World")
    .withTopK(TOP_K)
    .withSimilarityThreshold(SIMILARITY_THRESHOLD)
    .withFilterExpression(b.and(
        b.in("john", "jill"),
        b.eq("article_type", "blog")).build()));
这些过滤表达式将被转换为等效的PgVector过滤器。

PgVectorStore 属性

您可以在您的Spring Boot配置中使用以下属性来定制 PGVector 向量存储。

属性 描述 默认值

spring.ai.vectorstore.pgvector.index-type

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

HNSW

spring.ai.vectorstore.pgvector.distance-type

搜索距离类型。默认为 COSINE_DISTANCE。但如果向量被归一化为长度为 1,则可以使用 EUCLIDEAN_DISTANCENEGATIVE_INNER_PRODUCT 来获得最佳性能。

COSINE_DISTANCE

spring.ai.vectorstore.pgvector.dimension

嵌入维度。如果未明确指定,则 PgVectorStore 将从提供的 EmbeddingClient 中检索维度。维度设置为表创建时的嵌入列。如果更改维度,则还必须重新创建 vector_store 表。

-

spring.ai.vectorstore.pgvector.remove-existing-vector-store-table

在启动时删除现有的 vector_store 表。

false

在本地运行Postgres和PGVector DB

docker run -it --rm --name postgres -p 5432:5432 -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres ankane/pgvector

你可以像这样连接到该服务器:

psql -U postgres -h localhost -p 5432