MariaDB 向量存储
本节将引导您设置 MariaDBVectorStore
来存储文档嵌入并执行相似性搜索。
MariaDB Vector 是 MariaDB 11.7 的一部分,它支持存储和搜索机器学习生成的嵌入。
它使用向量索引提供高效的向量相似性搜索功能,支持余弦相似度(cosine similarity)和欧几里得距离(Euclidean distance)度量。
先决条件
-
一个正在运行的 MariaDB (11.7+) 实例。以下选项可用:
-
如果需要,用于 EmbeddingModel 的 API 密钥,以生成
MariaDBVectorStore
存储的嵌入。
自动配置
Spring AI 自动配置、启动器模块的工件名称发生了重大变化。 请参阅 升级说明 获取更多信息。 |
Spring AI 为 MariaDB 向量存储提供了 Spring Boot 自动配置。
要启用它,请将以下依赖项添加到您的项目的 Maven pom.xml
文件中:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-mariadb</artifactId>
</dependency>
或添加到您的 Gradle build.gradle
构建文件中。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-mariadb'
}
请参阅 依赖管理 部分,将 Spring AI BOM 添加到您的构建文件中。 |
向量存储实现可以为您初始化所需的模式,但您必须通过在适当的构造函数中指定 initializeSchema
布尔值或在 application.properties
文件中设置 …initialize-schema=true
来选择启用。
这是一个重大更改!在早期版本的 Spring AI 中,此模式初始化是默认发生的。 |
此外,您还需要一个配置好的 EmbeddingModel
bean。
有关更多信息,请参阅 EmbeddingModel 部分。
例如,要使用 OpenAI EmbeddingModel,请添加以下依赖项:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
请参阅 工件仓库 部分,将 Maven Central 和/或 Snapshot 仓库添加到您的构建文件中。 |
现在您可以在应用程序中自动装配 MariaDBVectorStore
:
@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 MariaDB
vectorStore.add(documents);
// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());
配置属性
要连接到 MariaDB 并使用 MariaDBVectorStore
,您需要提供实例的访问详细信息。
一个简单的配置可以通过 Spring Boot 的 application.yml
提供:
spring:
datasource:
url: jdbc:mariadb://localhost/db
username: myUser
password: myPassword
ai:
vectorstore:
mariadb:
initialize-schema: true
distance-type: COSINE
dimensions: 1536
如果您通过 Docker Compose 或 Testcontainers 将 MariaDB Vector 作为 Spring Boot 开发服务运行,则无需配置 URL、用户名和密码,因为它们由 Spring Boot 自动配置。 |
以 spring.ai.vectorstore.mariadb.*
开头的属性用于配置 MariaDBVectorStore
:
属性 | 描述 | 默认值 |
---|---|---|
|
是否初始化所需的模式 |
|
|
搜索距离类型。使用 |
|
|
嵌入维度。如果未明确指定,将从提供的 |
|
|
在启动时删除现有向量存储表。 |
|
|
向量存储模式名称 |
|
|
向量存储表名称 |
|
|
启用模式和表名验证,以确保它们是有效且存在的对象。 |
|
如果您配置自定义模式和/或表名,请考虑通过设置 |
手动配置
除了使用 Spring Boot 自动配置之外,您还可以手动配置 MariaDB 向量存储。 为此,您需要将以下依赖项添加到您的项目中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mariadb-store</artifactId>
</dependency>
请参阅 依赖管理 部分,将 Spring AI BOM 添加到您的构建文件中。 |
然后使用构建器模式创建 MariaDBVectorStore
bean:
@Bean
public VectorStore vectorStore(JdbcTemplate jdbcTemplate, EmbeddingModel embeddingModel) {
return MariaDBVectorStore.builder(jdbcTemplate, embeddingModel)
.dimensions(1536) // Optional: defaults to 1536
.distanceType(MariaDBDistanceType.COSINE) // Optional: defaults to COSINE
.schemaName("mydb") // Optional: defaults to null
.vectorTableName("custom_vectors") // Optional: defaults to "vector_store"
.contentFieldName("text") // Optional: defaults to "content"
.embeddingFieldName("embedding") // Optional: defaults to "embedding"
.idFieldName("doc_id") // Optional: defaults to "id"
.metadataFieldName("meta") // Optional: defaults to "metadata"
.initializeSchema(true) // Optional: defaults to false
.schemaValidation(true) // Optional: defaults to false
.removeExistingVectorStoreTable(false) // Optional: defaults to false
.maxDocumentBatchSize(10000) // Optional: defaults to 10000
.build();
}
// This can be any EmbeddingModel implementation
@Bean
public EmbeddingModel embeddingModel() {
return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("OPENAI_API_KEY")));
}
元数据过滤
您可以利用通用的、可移植的 元数据过滤器 与 MariaDB 向量存储。
例如,您可以使用文本表达式语言:
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());
这些过滤器表达式会自动转换为等效的 MariaDB JSON 路径表达式。 |
相似度分数
MariaDB 向量存储会自动计算从相似性搜索返回的文档的相似度分数。 这些分数提供了一种标准化度量,表示每个文档与您的搜索查询的匹配程度。
分数计算
相似度分数使用公式 score = 1.0 - distance
计算,其中:
-
分数:一个介于
0.0
和1.0
之间的值,其中1.0
表示完美相似,0.0
表示不相似 -
距离:使用配置的距离类型(
COSINE
或EUCLIDEAN
)计算的原始距离值
这意味着距离较小(更相似)的文档将获得更高的分数,使结果更直观易懂。
访问分数
您可以通过 getScore()
方法访问每个文档的相似度分数:
List<Document> results = vectorStore.similaritySearch(
SearchRequest.builder()
.query("Spring AI")
.topK(5)
.build());
for (Document doc : results) {
double score = doc.getScore(); // Value between 0.0 and 1.0
System.out.println("Document: " + doc.getText());
System.out.println("Similarity Score: " + score);
}
访问原生客户端
MariaDB 向量存储实现通过 getNativeClient()
方法提供对底层原生 JDBC 客户端 (JdbcTemplate
) 的访问:
MariaDBVectorStore vectorStore = context.getBean(MariaDBVectorStore.class);
Optional<JdbcTemplate> nativeClient = vectorStore.getNativeClient();
if (nativeClient.isPresent()) {
JdbcTemplate jdbc = nativeClient.get();
// Use the native client for MariaDB-specific operations
}
原生客户端使您能够访问 MariaDB 特定的功能和操作,这些功能和操作可能不会通过 VectorStore
接口公开。