MariaDB 向量存储

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

MariaDB Vector 是 MariaDB 11.7 的一部分,支持通过机器学习生成的嵌入进行存储和搜索。 它通过向量索引提供高效的向量相似度搜索功能,同时支持余弦相似度和欧氏距离度量。spring-doc.cadn.net.cn

前提条件

自动配置

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

Spring AI 为 MariaDB 向量商店提供了 Spring Boot 自动配置。 要启用它,请在项目的 Maven 中添加以下依赖pom.xml文件:spring-doc.cadn.net.cn

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

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

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-mariadb'
}
请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。

向量存储实现可以帮你初始化所需的模式,但你必须通过指定初始化模式在适当的构造函数中进行布尔值,或通过设置…​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>
请参阅“遗物仓库”部分,将Maven Central和/或快照仓库添加到你的构建文件中。

现在你可以自动接线MariaDBVectorStore在你的申请中: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 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-doc.cadn.net.cn

spring:
  datasource:
    url: jdbc:mariadb://localhost/db
    username: myUser
    password: myPassword
  ai:
    vectorstore:
      mariadb:
        initialize-schema: true
        distance-type: COSINE
        dimensions: 1536
如果你通过 Docker ComposeTestcontainers 运行 MariaDB Vector 作为 Spring Boot 开发服务, 你不需要配置URL、用户名和密码,因为它们是Spring Boot自动配置的。

性质以spring.ai.vectorstore.mariadb.*用于配置MariaDBVectorStore:spring-doc.cadn.net.cn

属性 描述 默认值

spring.ai.vectorstore.mariadb.initialize-schemaspring-doc.cadn.net.cn

是否初始化所需的模式spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

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

搜索距离类型。用余弦(默认)或欧 氏.如果矢量归一化为长度1,你可以用欧 氏为了表现最佳。spring-doc.cadn.net.cn

余弦spring-doc.cadn.net.cn

spring.ai.vectorstore.mariadb.dimensionsspring-doc.cadn.net.cn

嵌入维度。如果未明确指定,将从提供的维度中检索嵌入模型.spring-doc.cadn.net.cn

1536spring-doc.cadn.net.cn

spring.ai.vectorstore.mariadb.remove-existing-vector-store-table(Spring片)spring-doc.cadn.net.cn

启动时删除现有的矢量存储表。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.vectorstore.mariadb.schema-namespring-doc.cadn.net.cn

向量存储模式名称spring-doc.cadn.net.cn

spring-doc.cadn.net.cn

spring.ai.vectorstore.mariadb.table-namespring-doc.cadn.net.cn

向量存储表名称spring-doc.cadn.net.cn

vector_storespring-doc.cadn.net.cn

spring.ai.vectorstore.mariadb.schema-validationspring-doc.cadn.net.cn

支持模式和表名验证,确保它们是有效且存在的对象。spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

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

手动配置

你可以手动配置 MariaDB 向量存储,而不是使用 Spring Boot 的自动配置。 为此,你需要在项目中添加以下依赖关系:spring-doc.cadn.net.cn

<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的物料清单添加到你的构建文件中。

然后创建MariaDBVectorStore使用构建图纸的豆子:spring-doc.cadn.net.cn

@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 Vector store。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());
这些过滤表达式会自动转换为等效的 MariaDB JSON 路径表达式。

相似度评分

MariaDB 向量存储会自动计算通过相似性搜索返回的文档的相似度评分。 这些评分为每份文档与你的搜索查询匹配度提供了标准化的衡量标准。spring-doc.cadn.net.cn

得分计算

相似度分数采用以下公式计算得分 = 1.0 - 距离哪里:spring-doc.cadn.net.cn

这意味着距离较小(更相似)的文档得分会更高,使结果更直观易解读。spring-doc.cadn.net.cn

访问分数

你可以通过getScore()方法:spring-doc.cadn.net.cn

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);
}

搜索结果排序

搜索结果按相似度自动排序(最高分先)。 这确保了最相关的文件出现在搜索结果的顶部。spring-doc.cadn.net.cn

距离元数据

除了相似度评分外,原始距离值仍可在文档元数据中获得:spring-doc.cadn.net.cn

for (Document doc : results) {
    double score = doc.getScore();
    float distance = (Float) doc.getMetadata().get("distance");

    System.out.println("Score: " + score + ", Distance: " + distance);
}

相似阈值

在搜索请求中使用相似度阈值时,请指定该阈值为分数值(0.01.0)而非距离:spring-doc.cadn.net.cn

List<Document> results = vectorStore.similaritySearch(
    SearchRequest.builder()
        .query("Spring AI")
        .topK(10)
        .similarityThreshold(0.8)  // Only return documents with score >= 0.8
        .build());

这使得阈值保持一致且直观——阈值越高,搜索越受限,只返回高度相似的文档。spring-doc.cadn.net.cn

访问本地客户端

MariaDB 向量存储实现提供了对底层原生 JDBC 客户端的访问(Jdbc模板)通过getNativeClient()方法:spring-doc.cadn.net.cn

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接口。spring-doc.cadn.net.cn