PGvector

本节将引导你如何设置PGvectorVectorStore用于存储文档嵌入并进行相似性搜索。spring-doc.cadn.net.cn

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

前提条件

首先你需要访问启用的 PostgreSQL 实例向量,hstoreUUID-OSSP扩展。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索引。

接下来,如果需要,需为嵌入模型生成存储的嵌入的API密钥PgVectorStore.spring-doc.cadn.net.cn

自动配置

春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明spring-doc.cadn.net.cn

然后把 PgVectorStore 启动启动依赖添加到你的项目中:spring-doc.cadn.net.cn

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

或者去你的Gradlebuild.gradle构建文件。spring-doc.cadn.net.cn

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

向量存储实现可以帮你初始化所需的模式,但你必须通过指定初始化模式在适当的构造函数中进行布尔值,或通过设置…​initialize-schema=trueapplication.properties文件。spring-doc.cadn.net.cn

这是个突破性的变革!在早期版本的 Spring AI 中,这种模式初始化是默认的。

向量存储还需要嵌入模型实例用于计算文档的嵌入。 你可以选择其中一种可用的嵌入模型实现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>

或者去你的Gradlebuild.gradle构建文件。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。 请参阅“遗物仓库”部分,将Maven Central和/或快照仓库添加到你的构建文件中。

连接并配置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

属性 描述 默认值

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

最近邻搜索索引类型。选项包括没有- 精确最近邻搜索,IVFFlat- 索引将向量划分为列表,然后搜索与查询向量最近的列表子集。它构建时间更快,内存消耗更少,但查询性能较低(在速度和召回权衡方面)。新南威尔士大学- 创建多层图。它构建时间较慢,内存占用比IVFFlat多,但查询性能更好(在速度和召回权衡方面)。没有像IVFFlat那样的训练步骤,所以索引可以在没有任何数据的情况下创建。spring-doc.cadn.net.cn

新南威尔士大学spring-doc.cadn.net.cn

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

搜索距离类型。默认COSINE_DISTANCE.但如果矢量归一化为长度,你可以用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 将从提供的维度中检索嵌入模型.维度设置为表上嵌入列的创建。如果你更改了尺寸,也得重新创建vector_store表。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.pgvector.remove-existing-vector-store-table(Spring)-向量-存储-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

公共spring-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-文档-批次-大小spring-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());

或者程序化地使用滤波。表达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路径表达式,以实现高效的元数据过滤。

手动配置

你可以手动配置PgVectorStore. 为此你需要添加PostgreSQL连接,Jdbc模板对你的项目进行自动配置依赖: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的物料清单添加到你的构建文件中。

要在你的应用中配置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 DB

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 实现提供了对底层原生 JDBC 客户端的访问(Jdbc模板)通过getNativeClient()方法: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