PGvector

设置PGvector 0以存储文档嵌入并执行相似性搜索。spring-doc.cadn.net.cn

PostgreSQL扩展库PGvector是一个允许在机器学习生成的嵌入中存储和搜索的开源扩展。它提供了不同的能力,让用户识别精确和近似最近邻居。它设计为与PostgreSQL的其他功能无缝工作,包括索引和查询。spring-doc.cadn.net.cn

前提条件

第一个需要访问一个启用vectorhstoreuuid-ossp扩展的PostgreSQL实例。spring-doc.cadn.net.cn

你可以通过 Docker ComposeTestcontainers 在Spring Boot中运行Postgres数据库。作为替代方案,setup local Postgres/PGVector 附录展示了如何在本地使用Docker容器设置Postgres/PGVector数据库。

在启动时,如果显式启用了一个关于表结构的初始化功能,0会尝试安装必要的数据库扩展,并创建一个带有索引的1号表,如果不存在的话。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);
将0替换为实际嵌入维度,如果使用不同的维度。PGvector最多支持2000个维度用于HNSW索引。

下一步,如果需要,生成存储在0处的嵌入模型的API密钥:嵌入模型spring-doc.cadn.net.cn

自动配置

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。spring-doc.cadn.net.cn

然后在你的项目中添加Postgrel向量数据库启动依赖项:spring-doc.cadn.net.cn

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

或者添加到您的Gradle 构建脚本文件中。spring-doc.cadn.net.cn

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

The vector store implementation can initialize the required schema for you, but you must opt-in by specifying the initializeSchema boolean in the appropriate constructor or by setting …​initialize-schema=true in the application.properties file.spring-doc.cadn.net.cn

这是一个破坏性变更!在早期版本的 Spring AI 中,此模式初始化是默认进行的。

The Vector Store also requires a EmbeddingModel实例来计算文档的嵌入。 你可以选择一个可用的嵌入模型实现spring-doc.cadn.net.cn

例如,要使用大模型,在你的项目中添加以下依赖项:spring-doc.cadn.net.cn

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

或者添加到您的Gradle 构建脚本文件中。spring-doc.cadn.net.cn

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

连接到并配置 PgVectorStore,您需要提供有关您实例的访问细节。 春 Boot 提供了一个简单的配置。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 Compose或测试容器中运行PGvector作为Spring Boot开发服务, 由于Spring Boot会自动配置URL、用户名和密码,因此无需进行任何配置。
查看配置参数列表以了解默认值和配置选项。

现在,您可以在应用中自动注入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

属性 描述 默认值

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

最近邻搜索索引类型。选项包括:NONE - 精确最近邻搜索,IVFFlat - 索引将向量划分为列表,然后对查询向量进行搜索时只检查这些列表的一部分。其构建时间更快且占用内存更少,但查询性能(以速度与召回率的权衡)较低。HNSW - 创建多层图。其构建时间更长且占用内存更多,但查询性能(以速度与召回率的权衡)较高。没有像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会从提供的`0`获取维度。维度设置为嵌入列在表创建时。如果您更改了维度,您还需要重新创建向量存储表。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

向量存储的schema名称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到你的构建文件中。

要配置PostgreSQL向量数据库,您可以在应用中使用以下配置: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

访问原生客户端

PG向量存储实现通过(0)方法提供了对底层的 JDBC JDBC客户端的访问。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