此版本仍在开发中,尚未被视为稳定版。为了获取最新的快照版本,请使用Spring AI 1.1.3spring-doc.cadn.net.cn

MariaDB 向量存储

本节将引导您完成配置MariaDBVectorStore以存储文档嵌入并执行相似性搜索的过程。spring-doc.cadn.net.cn

MariaDB 向量 是 MariaDB 11.7 的一部分,支持存储和搜索机器学习生成的嵌入向量。 它通过向量索引提供高效的向量相似性搜索功能,支持余弦相似性和欧几里得距离两种度量方式。spring-doc.cadn.net.cn

前提条件

自动配置

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。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>

或者添加到您的Gradle 构建脚本文件中。spring-doc.cadn.net.cn

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

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-doc.cadn.net.cn

这是一个破坏性变更!在早期版本的 Spring AI 中,此模式初始化是默认进行的。

此外,您还需要配置一个EmbeddingModel的豆。有关详细信息,请参阅EmbeddingModel部分。spring-doc.cadn.net.cn

For example, to use the OpenAI的嵌入模型, add the following dependency:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
引用 Artifact 仓库 部分,以在构建文件中添加 Maven Central 和/或 Snapshot 仓库。

现在,您可以通过代码自动注入应用中的0: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
If you run MariaDB Vector as a Docker Compose or Testcontainers, you don’t need to configure URL, username and password since they are autoconfigured by Spring Boot.

spring.ai.vectorstore.mariadb.* 开头的属性用于配置 MariaDBVectorStorespring-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

搜索距离类型。使用 COSINE(默认值)或 EUCLIDEAN。如果向量被归一化为长度为1,则可以使用 EUCLIDEAN 以获得最佳性能。spring-doc.cadn.net.cn

COSINEspring-doc.cadn.net.cn

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

Embeddings dimension. If not specified explicitly, will retrieve dimensions from the provided EmbeddingModel.spring-doc.cadn.net.cn

1536spring-doc.cadn.net.cn

spring.ai.vectorstore.mariadb.remove-existing-vector-store-tablespring-doc.cadn.net.cn

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

falsespring-doc.cadn.net.cn

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

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

nullspring-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 注入攻击的风险。

手动配置

除了使用Spring Boot的自动配置外,您还可以手动配置MariaDB向量存储。为此,您需要添加以下依赖项到您的项目中: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 BOM到你的构建文件中。

然后使用构建器模式创建 MariaDBVectorStore Bean: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")));
}

元数据过滤

你可以利用通用的元数据过滤器metadata filters与MariaDB向量存储集成。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());

或通过编程方式使用 Filter.Expression 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

分数计算

相似性分数使用公式计算,其中:spring-doc.cadn.net.cn

  • 分数:表示一个介于 0.01.0 之间,其中 1.0 表示完全相似,0.0 表示不相似spring-doc.cadn.net.cn

  • 距离: 使用配置的距离类型计算得到的原始距离值(COSINEEUCLIDEANspring-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

Distance Metadata

除了相似度分数之外,原始距离值仍然在文档元数据中可用: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

访问原生客户端

The MariaDB Vector Store实现通过调用底层的 native JDBC 客户端(0)提供了访问(1)的方法: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