|
此版本仍在开发中,尚未被视为稳定版。为了获取最新的快照版本,请使用Spring AI 1.1.3! |
PGvector
设置PGvector 0以存储文档嵌入并执行相似性搜索。
PostgreSQL扩展库PGvector是一个允许在机器学习生成的嵌入中存储和搜索的开源扩展。它提供了不同的能力,让用户识别精确和近似最近邻居。它设计为与PostgreSQL的其他功能无缝工作,包括索引和查询。
前提条件
第一个需要访问一个启用vector、hstore和uuid-ossp扩展的PostgreSQL实例。
| 你可以通过 Docker Compose 或 Testcontainers 在Spring Boot中运行Postgres数据库。作为替代方案,setup local Postgres/PGVector 附录展示了如何在本地使用Docker容器设置Postgres/PGVector数据库。 |
在启动时,如果显式启用了一个关于表结构的初始化功能,0会尝试安装必要的数据库扩展,并创建一个带有索引的1号表,如果不存在的话。
可选的,你可以手动这样操作,比如
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密钥:嵌入模型。
自动配置
|
There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。 |
然后在你的项目中添加Postgrel向量数据库启动依赖项:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-pgvector</artifactId>
</dependency>
或者添加到您的Gradle 构建脚本文件中。
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 AI 中,此模式初始化是默认进行的。 |
The Vector Store also requires a EmbeddingModel实例来计算文档的嵌入。
你可以选择一个可用的嵌入模型实现。
例如,要使用大模型,在你的项目中添加以下依赖项:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
或者添加到您的Gradle 构建脚本文件中。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
连接到并配置 PgVectorStore,您需要提供有关您实例的访问细节。
春 Boot 提供了一个简单的配置。
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并使用它
@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向量存储。
| 属性 | 描述 | 默认值 |
|---|---|---|
|
最近邻搜索索引类型。选项包括: |
HNSW |
|
搜索距离类型。默认值为 |
COSINE_DISTANCE |
|
嵌入维度。如果没有显式指定,则PgVectorStore会从提供的`0`获取维度。维度设置为嵌入列在表创建时。如果您更改了维度,您还需要重新创建向量存储表。 |
- |
|
删除启动时现有的 |
false |
|
是否初始化所需的模式 |
false |
|
向量存储的schema名称 |
|
|
向量存储表名 |
|
|
允许对表名和结构进行验证,以确保它们是有效的和存在的对象。 |
false |
|
在一个批次中处理的最大文档数量。 |
10000 |
如果配置了自定义模式和/或表名,考虑启用模式验证,通过设置 spring.ai.vectorstore.pgvector.schema-validation=true 来启用。
这确保了名称的正确性并降低了 SQL 注入攻击的风险。 |
元数据过滤
你可以使用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 路径表达式,以实现高效的元数据过滤。 |
手动配置
而不是使用Spring Boot默认配置,你可以手动配置PgVectorStore。
为此,你需要添加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到你的构建文件中。 |
要配置PostgreSQL向量数据库,您可以在应用中使用以下配置:
@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
你可以像下面这样连接到这个服务器:
psql -U postgres -h localhost -p 5432
访问原生客户端
PG向量存储实现通过(0)方法提供了对底层的 JDBC JDBC客户端的访问。
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接口无法暴露的操作和功能。