Azure Cosmos DB
本部分将引导您完成设置CosmosDBVectorStore
以存储文档嵌入并执行相似性搜索。
什么是 Azure Cosmos DB?
Azure Cosmos DB 是 Microsoft 的全球分布式云原生数据库服务,专为任务关键型应用程序而设计。 它提供高可用性、低延迟以及水平扩展以满足现代应用程序需求的能力。 它是从头开始构建的,其核心是全球分布、细粒度的多租户和水平可扩展性。 它是 Azure 中的一项基础服务,被 Microsoft 全球范围内的大多数任务关键型应用程序使用,包括 Teams、Skype、Xbox Live、Office 365、必应、Azure Active Directory、Azure 门户、Microsoft Store 等。 它还被包括 OpenAI 在内的数千家外部客户用于 ChatGPT 和其他需要弹性扩展、交钥匙全球分发以及全球低延迟和高可用性的关键任务 AI 应用程序。
什么是 DiskANN?
DiskANN(基于磁盘的近似最近邻搜索)是 Azure Cosmos DB 中使用的一项创新技术,用于增强矢量搜索的性能。 它通过对存储在 Cosmos DB 中的嵌入进行索引,实现跨高维数据的高效且可缩放的相似性搜索。
DiskANN 提供以下优势:
-
效率:与传统方法相比,通过利用基于磁盘的结构,DiskANN 显着减少了查找最近邻所需的时间。
-
可扩展性:它可以处理超过内存容量的大型数据集,使其适合各种应用程序,包括机器学习和人工智能驱动的解决方案。
-
低延迟:DiskANN 最大限度地减少搜索作期间的延迟,确保应用程序即使数据量很大,也能快速检索结果。
在适用于 Azure Cosmos DB 的 Spring AI 上下文中,矢量搜索将创建和利用 DiskANN 索引来确保相似性查询的最佳性能。
使用自动配置设置 Azure Cosmos DB 矢量存储
以下代码演示了如何设置CosmosDBVectorStore
使用自动配置:
package com.example.demo;
import io.micrometer.observation.ObservationRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootApplication
@EnableAutoConfiguration
public class DemoApplication implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
@Lazy
@Autowired
private VectorStore vectorStore;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
Document document1 = new Document(UUID.randomUUID().toString(), "Sample content1", Map.of("key1", "value1"));
Document document2 = new Document(UUID.randomUUID().toString(), "Sample content2", Map.of("key2", "value2"));
this.vectorStore.add(List.of(document1, document2));
List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Sample content").topK(1).build());
log.info("Search results: {}", results);
// Remove the documents from the vector store
this.vectorStore.delete(List.of(document1.getId(), document2.getId()));
}
@Bean
public ObservationRegistry observationRegistry() {
return ObservationRegistry.create();
}
}
自动配置
Spring AI 自动配置、入门模块的工件名称发生了重大变化。 有关更多信息,请参阅升级说明。 |
将以下依赖项添加到您的 Maven 项目:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-azure-cosmos-db</artifactId>
</dependency>
配置属性
以下配置属性可用于 Cosmos DB 矢量存储:
属性 | 描述 |
---|---|
spring.ai.vectorstore.cosmosdb.databaseName |
要使用的 Cosmos DB 数据库的名称。 |
spring.ai.vectorstore.cosmosdb.containerName |
要使用的 Cosmos DB 容器的名称。 |
spring.ai.vectorstore.cosmosdb.partitionKeyPath |
分区键的路径。 |
spring.ai.vectorstore.cosmosdb.metadata字段 |
元数据字段的逗号分隔列表。 |
spring.ai.vectorstore.cosmosdb.vectorStore吞吐量 |
向量存储的吞吐量。 |
spring.ai.vectorstore.cosmosdb.vector尺寸 |
向量的维数。 |
spring.ai.vectorstore.cosmosdb.endpoint |
Cosmos DB 的终结点。 |
spring.ai.vectorstore.cosmosdb.key |
Cosmos DB 的密钥(如果密钥不存在,则将使用 [DefaultAzureCredential](learn.microsoft.com/azure/developer/java/sdk/authentication/credential-chains#defaultazurecredential-overview) )。 |
使用过滤器进行复杂搜索
可以使用 Cosmos DB 矢量存储中的筛选器执行更复杂的搜索。下面是一个示例,演示了如何在搜索查询中使用筛选器。
Map<String, Object> metadata1 = new HashMap<>();
metadata1.put("country", "UK");
metadata1.put("year", 2021);
metadata1.put("city", "London");
Map<String, Object> metadata2 = new HashMap<>();
metadata2.put("country", "NL");
metadata2.put("year", 2022);
metadata2.put("city", "Amsterdam");
Document document1 = new Document("1", "A document about the UK", this.metadata1);
Document document2 = new Document("2", "A document about the Netherlands", this.metadata2);
vectorStore.add(List.of(document1, document2));
FilterExpressionBuilder builder = new FilterExpressionBuilder();
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("The World")
.topK(10)
.filterExpression((this.builder.in("country", "UK", "NL")).build()).build());
在不进行自动配置的情况下设置 Azure Cosmos DB 矢量存储
以下代码演示了如何设置CosmosDBVectorStore
而不依赖自动配置。[默认 Azure凭据]建议将 (learn.microsoft.com/azure/developer/java/sdk/authentication/credential-chains#defaultazurecredential-overview) 用于对 Azure Cosmos DB 进行身份验证。
@Bean
public VectorStore vectorStore(ObservationRegistry observationRegistry) {
// Create the Cosmos DB client
CosmosAsyncClient cosmosClient = new CosmosClientBuilder()
.endpoint(System.getenv("COSMOSDB_AI_ENDPOINT"))
.credential(new DefaultAzureCredentialBuilder().build())
.userAgentSuffix("SpringAI-CDBNoSQL-VectorStore")
.gatewayMode()
.buildAsyncClient();
// Create and configure the vector store
return CosmosDBVectorStore.builder(cosmosClient, embeddingModel)
.databaseName("test-database")
.containerName("test-container")
// Configure metadata fields for filtering
.metadataFields(List.of("country", "year", "city"))
// Set the partition key path (optional)
.partitionKeyPath("/id")
// Configure performance settings
.vectorStoreThroughput(1000)
.vectorDimensions(1536) // Match your embedding model's dimensions
// Add custom batching strategy (optional)
.batchingStrategy(new TokenCountBatchingStrategy())
// Add observation registry for metrics
.observationRegistry(observationRegistry)
.build();
}
@Bean
public EmbeddingModel embeddingModel() {
return new TransformersEmbeddingModel();
}
此配置显示所有可用的构建器选项:
-
databaseName
:Cosmos DB 数据库的名称 -
containerName
:数据库中容器的名称 -
partitionKeyPath
:分区键的路径(例如,“/id”) -
metadataFields
:将用于筛选的元数据字段列表 -
vectorStoreThroughput
:向量存储容器的吞吐量 (RU/s) -
vectorDimensions
:向量的维数(应与嵌入模型匹配) -
batchingStrategy
:批处理文档作的策略(可选)
手动依赖项设置
在 Maven 项目中添加以下依赖项:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-azure-cosmos-db-store</artifactId>
</dependency>
访问本机客户端
Azure Cosmos DB 矢量存储实现提供对基础本机 Azure Cosmos DB 客户端 (CosmosClient
) 通过getNativeClient()
方法:
CosmosDBVectorStore vectorStore = context.getBean(CosmosDBVectorStore.class);
Optional<CosmosClient> nativeClient = vectorStore.getNativeClient();
if (nativeClient.isPresent()) {
CosmosClient client = nativeClient.get();
// Use the native client for Azure Cosmos DB-specific operations
}
本机客户端使你能够访问特定于 Azure Cosmos DB 的功能和作,这些功能和作可能不会通过VectorStore
接口。