PGvector
本节将引导你如何设置PGvectorVectorStore用于存储文档嵌入并进行相似性搜索。
PGvector 是 PostgreSQL 的一个开源扩展,支持在机器学习生成的嵌入上存储和搜索。它提供了多种功能,使用户能够识别精确邻和近似最近邻。它设计为与其他 PostgreSQL 功能无缝协作,包括索引和查询。
前提条件
首先你需要访问启用的 PostgreSQL 实例向量,hstore和UUID-OSSP扩展。
| 你可以通过 Docker Compose 或 Testcontainers 运行 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 is the default embedding dimension ); CREATE INDEX ON vector_store USING HNSW (embedding vector_cosine_ops);
替换1536如果你使用不同的维度,则使用实际嵌入维数。PGvector 最多支持2000维的HNSW索引。 |
接下来,如果需要,需为嵌入模型生成存储的嵌入的API密钥PgVectorStore.
自动配置
|
春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明。 |
然后把 PgVectorStore 启动启动依赖添加到你的项目中:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-pgvector</artifactId>
</dependency>
或者去你的Gradlebuild.gradle构建文件。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-pgvector'
}
向量存储实现可以帮你初始化所需的模式,但你必须通过指定初始化模式在适当的构造函数中进行布尔值,或通过设置…initialize-schema=true在application.properties文件。
| 这是个突破性的变革!在早期版本的 Spring AI 中,这种模式初始化是默认的。 |
向量存储还需要嵌入模型实例用于计算文档的嵌入。
你可以选择其中一种可用的嵌入模型实现。
例如,要使用 OpenAI EmbeddingModel,可以在你的项目中添加以下依赖关系:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
或者去你的Gradlebuild.gradle构建文件。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-openai'
}
连接并配置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 # Optional: Maximum number of documents per batch
| 如果你通过 Docker Compose 或 Testcontainers 运行 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());
配置属性
你可以在 Spring Boot 配置中使用以下属性来自定义 PGVector 矢量存储。
| 属性 | 描述 | 默认值 |
|---|---|---|
|
最近邻搜索索引类型。选项包括 |
新南威尔士大学 |
|
搜索距离类型。默认 |
COSINE_DISTANCE |
|
嵌入维度。如果未明确指定,PgVectorStore 将从提供的维度中检索 |
- |
|
删除现有的 |
false |
|
是否初始化所需的模式 |
false |
|
向量存储模式名称 |
|
|
向量存储表名称 |
|
|
支持模式和表名验证,确保它们是有效且存在的对象。 |
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());
或者程序化地使用滤波。表达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路径表达式,以实现高效的元数据过滤。 |
手动配置
你可以手动配置PgVectorStore.
为此你需要添加PostgreSQL连接,Jdbc模板对你的项目进行自动配置依赖:
<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,你可以使用以下设置:
@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
你可以这样连接到这个服务器:
psql -U postgres -h localhost -p 5432
访问本地客户端
PGVector Store 实现提供了对底层原生 JDBC 客户端的访问(Jdbc模板)通过getNativeClient()方法:
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接口。