跳到主要内容

MariaDB 向量存储

DeepSeek V3 中英对照 MariaDB Vector Store

本节将指导您如何设置 MariaDBVectorStore 来存储文档嵌入并执行相似性搜索。

MariaDB Vector 是 MariaDB 11.7 的一部分,它使得存储和搜索由机器学习生成的嵌入成为可能。它通过向量索引提供了高效的向量相似性搜索能力,支持余弦相似度和欧几里得距离度量。

先决条件

自动配置

Spring AI 为 MariaDB Vector Store 提供了 Spring Boot 自动配置。要启用它,请将以下依赖项添加到项目的 Maven pom.xml 文件中:

<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mariadb-store-spring-boot-starter</artifactId>
</dependency>
xml

或者到你的 Gradle build.gradle 构建文件中。

dependencies {
implementation 'org.springframework.ai:spring-ai-mariadb-store-spring-boot-starter'
}
groovy
提示

请参考 依赖管理 部分,将 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-openai-spring-boot-starter</artifactId>
</dependency>
xml

:::提示
请参阅 Repositories 部分,将 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());
java

配置属性

要连接到 MariaDB 并使用 MariaDBVectorStore,你需要提供实例的访问详细信息。可以通过 Spring Boot 的 application.yml 提供一个简单的配置:

spring:
datasource:
url: jdbc:mariadb://localhost:3306/your_database
username: your_username
password: your_password
yaml

在这个配置中,url 是你的 MariaDB 实例的连接地址,usernamepassword 是用于连接数据库的用户名和密码。确保将这些值替换为你实际使用的数据库连接信息。

spring:
datasource:
url: jdbc:mariadb://localhost/db
username: myUser
password: myPassword
ai:
vectorstore:
mariadb:
initialize-schema: true
distance-type: COSINE
dimensions: 1536
yaml
提示

如果你通过 Docker ComposeTestcontainers 将 MariaDB Vector 作为 Spring Boot 开发服务运行,你无需配置 URL、用户名和密码,因为它们由 Spring Boot 自动配置。

spring.ai.vectorstore.mariadb.* 开头的属性用于配置 MariaDBVectorStore

属性描述默认值
spring.ai.vectorstore.mariadb.initialize-schema是否初始化所需的 schemafalse
spring.ai.vectorstore.mariadb.distance-type搜索距离类型。使用 COSINE(默认)或 EUCLIDEAN。如果向量被归一化为长度 1,可以使用 EUCLIDEAN 以获得最佳性能。COSINE
spring.ai.vectorstore.mariadb.dimensions嵌入维度。如果未明确指定,将从提供的 EmbeddingModel 中检索维度。1536
spring.ai.vectorstore.mariadb.remove-existing-vector-store-table在启动时删除现有的向量存储表。false
spring.ai.vectorstore.mariadb.schema-name向量存储 schema 名称null
spring.ai.vectorstore.mariadb.table-name向量存储表名称vector_store
spring.ai.vectorstore.mariadb.schema-validation启用 schema 和表名验证,以确保它们是有效且存在的对象。false
提示

如果你配置了自定义的 schema 和/或表名,考虑通过设置 spring.ai.vectorstore.mariadb.schema-validation=true 来启用 schema 验证。这可以确保名称的正确性,并降低 SQL 注入攻击的风险。

手动配置

除了使用 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>
xml
提示

请参考 依赖管理 部分,将 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")));
}
java

元数据过滤

你可以利用通用的、可移植的 元数据过滤器 与 MariaDB Vector 存储结合使用。

例如,你可以使用文本表达式语言:

vectorStore.similaritySearch(
SearchRequest.builder()
.query("The World")
.topK(TOP_K)
.similarityThreshold(SIMILARITY_THRESHOLD)
.filterExpression("author in ['john', 'jill'] && article_type == 'blog'").build());
java

或者通过使用 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());
java
备注

这些过滤器表达式会自动转换为等价的 MariaDB JSON 路径表达式。

访问原生客户端

MariaDB Vector Store 实现通过 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
}
java

原生客户端使您能够访问可能未通过 VectorStore 接口暴露的 MariaDB 特定功能和操作。