张国伟 发表于 2024-7-21 22:39:14

【Spring AI】05. 向量数据库-Redis

Redis

本节将指导您设置RedisVectorStore,作为文档存储向量数据库,并执行相似性搜索。
什么是 Redis?

Redis 是一个开源(BSD 许可证),用作数据库、缓存、消息代理和流引擎的内存数据结构存储。Redis支持多种数据结构,包罗字符串、哈希、列表、集合、带范围查询的有序集合、位图、hyperloglogs、地理空间索引和流。
Redis 向量搜索是什么?

Redis Search and Query 扩展了 Redis OSS 的焦点功能,使您可以将 Redis 用作矢量数据库:


[*]在哈希或 JSON 文档中存储向量和相关元数据
[*]检索向量
[*]执行向量搜索
先决条件


[*]EmbeddingClient实例,来计算文档嵌入向量。有几种选项可用:


[*]Transformers Embedding- 在您的本地情况中计算嵌入向量。请按照 ONNX Transformers Embedding 分析操作。
[*]OpenAI Embedding- 使用 OpenAI 嵌入端点。您需要在 OpenAI 注册并在 API Keys 生成 api-key 令牌。
[*]您也可以使用Azure OpenAI Embedding。

[*]一个 Redis Stack 实例
a. Redis Cloud (推荐)
b. Docker 镜像 redis/redis-stack:latest
依赖项

将这些依赖项添加到您的项目中:


[*] Embedding Client boot starter ,用于计算嵌入。
[*] Transformers Embedding(本地),并按照 ONNX Transformers 嵌入向量分析操作。
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-transformers-spring-boot-starter</artifactId>
</dependency>
或使用 OpenAI(云)
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
       请参阅 03. 开始章节 的 Dependency Management 部分,将 Spring AI BOM 添加到构建文件中
    您需要提供您的 OpenAI API 密钥。将其设置为情况变量,如下所示:
export SPRING_AI_OPENAI_API_KEY='Your_OpenAI_API_Key'

[*] 添加 Redis Vector Store 和 Jedis 依赖项
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-redis</artifactId>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>5.1.0</version>
</dependency>

   请参阅 03. 开始章节 的 Dependency Management 部分,将 Spring AI BOM 添加到构建文件中
用法

创建一个连接到您的 Redis 数据库的 RedisVectorStore 实例:
@Bean
public VectorStore vectorStore(EmbeddingClient embeddingClient) {
RedisVectorStoreConfig config = RedisVectorStoreConfig.builder()
   .withURI("redis://localhost:6379")
   // Define the metadata fields to be used
   // in the similarity search filters.
   .withMetadataFields(
      MetadataField.tag("country"),
      MetadataField.numeric("year"))
   .build();

return new RedisVectorStore(config, embeddingClient);
}
   更方便和推荐的做法是将 RedisVectorStore 创建为一个 Bean。但如果您决定手动创建它,则必须在设置属性之后并在使用客户端之前调用 RedisVectorStore#afterPropertiesSet() 。
    您必须明确列出所有元数据字段名称和范例( TAG , TEXT 或 NUMERIC ),用于过滤表达式中使用的任何元数据字段。上面的 withMetadataFields 注册可过滤的元数据字段:范例为 TAG 的 country ,范例为 NUMERIC 的 year 。
然后在您的主代码中,创建一些文档:
List<Document> documents = List.of(
   new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("country", "UK", "year", 2020)),
   new Document("The World is Big and Salvation Lurks Around the Corner", Map.of()),
   new Document("You walk forward facing the past and you turn back toward the future.", Map.of("country", "NL", "year", 2023)));
如今将文档添加到您的向量存储中:
vectorStore.add(documents);
末了,检索与查询相似的文档:
List<Document> results = vectorStore.similaritySearch(
   SearchRequest
      .query("Spring")
      .withTopK(5));
如果一切顺遂,您应该可以或许检索包罗文本“Spring AI rocks!!”的文档。
元数据过滤

您也可以使用通用、可移植的元数据过滤器与 RedisVectorStore。
例如,您可以使用文本表达语言:
vectorStore.similaritySearch(
   SearchRequest
      .query("The World")
      .withTopK(TOP_K)
      .withSimilarityThreshold(SIMILARITY_THRESHOLD)
      .withFilterExpression("country in ['UK', 'NL'] && year >= 2020"));
或者使用表达式 DSL 进行编程:
FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(
   SearchRequest
      .query("The World")
      .withTopK(TOP_K)
      .withSimilarityThreshold(SIMILARITY_THRESHOLD)
      .withFilterExpression(b.and(
         b.in("country", "UK", "NL"),
         b.gte("year", 2020)).build()));
可移植的过滤表达式会主动转换为 Redis 搜索查询。例如,以下可移植的过滤表达式:
country in ['UK', 'NL'] && year >= 2020
被转换为 Redis 查询:
@country:{UK | NL} @year:

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 【Spring AI】05. 向量数据库-Redis