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

文章目录

Redis

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

什么是 Redis?


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


Redis 向量搜索是什么?


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

  • 在哈希或 JSON 文档中存储向量和相关元数据
  • 检索向量
  • 执行向量搜索

先决条件

  1. EmbeddingClient实例,来计算文档嵌入向量。有几种选项可用:
  • Transformers Embedding- 在您的本地环境中计算嵌入向量。请按照 ONNX Transformers Embedding 说明操作。
  • OpenAI Embedding- 使用 OpenAI 嵌入端点。您需要在 OpenAI 注册并在 API Keys 生成 api-key 令牌。
  • 您也可以使用Azure OpenAI Embedding。
  1. 一个 Redis Stack 实例
    a. Redis Cloud (推荐)
    b. Docker 镜像 redis/redis-stack:latest

依赖项

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

  • Embedding Client boot starter ,用于计算嵌入。

  • Transformers Embedding(本地),并按照 ONNX Transformers 嵌入向量说明操作。

    html 复制代码
    <dependency>
      <groupId>org.springframework.ai</groupId>
      <artifactId>spring-ai-transformers-spring-boot-starter</artifactId>
    </dependency>

    或使用 OpenAI(云)

    html 复制代码
    <dependency>
        <groupId>org.springframework.ai</groupId>
        <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
    </dependency>

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

    您需要提供您的 OpenAI API 密钥。将其设置为环境变量,如下所示:

    shell 复制代码
    export SPRING_AI_OPENAI_API_KEY='Your_OpenAI_API_Key'
  • 添加 Redis Vector Store 和 Jedis 依赖项

    html 复制代码
    <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 实例:

java 复制代码
@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 。

然后在您的主代码中,创建一些文档:

java 复制代码
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)));

现在将文档添加到您的向量存储中:

java 复制代码
vectorStore.add(documents);

最后,检索与查询相似的文档:

java 复制代码
List<Document> results = vectorStore.similaritySearch(
   SearchRequest
      .query("Spring")
      .withTopK(5));

如果一切顺利,您应该能够检索包含文本"Spring AI rocks!!"的文档。

元数据过滤

您也可以利用通用、可移植的元数据过滤器与 RedisVectorStore。

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

java 复制代码
vectorStore.similaritySearch(
   SearchRequest
      .query("The World")
      .withTopK(TOP_K)
      .withSimilarityThreshold(SIMILARITY_THRESHOLD)
      .withFilterExpression("country in ['UK', 'NL'] && year >= 2020"));

或者使用表达式 DSL 进行编程:

java 复制代码
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 搜索查询。例如,以下可移植的过滤表达式:

text 复制代码
country in ['UK', 'NL'] && year >= 2020

被转换为 Redis 查询:

text 复制代码
@country:{UK | NL} @year:[2020 inf]
相关推荐
旦莫几秒前
AI测试Agent的两种架构路径:谁做主控?
人工智能·python·架构·自动化·ai测试
xcLeigh1 分钟前
KES数据库运维监控与故障排查实战
运维·数据库·sql·故障排查·运维监控·kes
城事漫游Molly1 分钟前
AI赋能质性研究(二):用 AI 做归纳编码,7 个场景提示词模板
人工智能·prompt·ai for science·提示词工程·定性研究
GlobalSign数字证书3 分钟前
中小企业的 SSL/TLS 证书管理,有更轻量的方案
数据库·网络协议·ssl
搬石头的马农5 分钟前
从零配置Claude自动修Bug:6步打造全自动开发流程
java·人工智能·python·bug·ai编程
梓䈑7 分钟前
【MySQL】库的操作(数据库的创建、查看、修改 和 备份)
数据库·mysql
暗夜猎手-大魔王11 分钟前
转载--Hermes Agent 04 | Agent 主循环:一次对话背后发生了什么
人工智能·python·算法
GPUStack11 分钟前
没有 GPU,还能跑大模型吗?vLLM vs llama.cpp 实测对比
人工智能·开源
星越华夏13 分钟前
物联网基于树莓派的智能环境监控系统:温湿度传感与远程控制综合设计
人工智能·物联网
Xxtaoaooo18 分钟前
DolphinDB物联网实测手记:用环境传感器数据跑通时序分析的完整链路
人工智能