Redis

このセクションでは、ドキュメントの埋め込みを保存し、類似性検索を実行するための RedisVectorStore のセットアップについて説明します。

Redis (英語) は、データベース、キャッシュ、メッセージブローカー、ストリーミングエンジンとして使用されるオープンソース (BSD ライセンス) のインメモリデータ構造ストアです。Redis は、文字列、ハッシュ、リスト、セット、範囲クエリを備えたソートセット、ビットマップ、ハイパーログログ、地理空間インデックス、ストリームなどのデータ構造を提供します。

Redis 検索とクエリ (英語) は、Redis OSS のコア機能を継承し、Redis をベクトルデータベースとして使用できるようにします。

  • ベクトルと関連するメタデータをハッシュまたは JSON ドキュメント内に保存します

  • ベクトルの取得

  • ベクトル検索を実行する

前提条件

  1. Redis スタックインスタンス

  2. EmbeddingModel インスタンスを使用してドキュメントの埋め込みを計算します。いくつかのオプションが利用可能です:

    • 必要に応じて、EmbeddingModel が RedisVectorStore によって保存される埋め込みを生成するための API キー。

自動構成

Spring AI は、Redis ベクトルストア用の Spring Boot 自動構成を提供します。これを有効にするには、プロジェクトの Maven pom.xml ファイルに次の依存関係を追加します。

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-redis-store-spring-boot-starter</artifactId>
</dependency>

または、Gradle build.gradle ビルドファイルに保存します。

dependencies {
    implementation 'org.springframework.ai:spring-ai-redis-store-spring-boot-starter'
}
Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。
マイルストーンおよび / またはスナップショットリポジトリをビルドファイルに追加するには、リポジトリセクションを参照してください。

ベクトルストアの実装では必要なスキーマを初期化できますが、適切なコンストラクターで initializeSchema ブール値を指定するか、application.properties ファイルで …​initialize-schema=true を設定することによってオプトインする必要があります。

これは重大な変更です。Spring AI の以前のバージョンでは、このスキーマの初期化はデフォルトで行われていました。

さらに、設定済みの EmbeddingModel Bean が必要です。詳細については、"EmbeddingModel" セクションを参照してください。

必要な Bean の例を次に示します。

@Bean
public EmbeddingModel embeddingModel() {
    // Can be any other EmbeddingModel implementation.
    return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("SPRING_AI_OPENAI_API_KEY")));
}

Redis に接続するには、インスタンスのアクセス詳細を提供する必要があります。簡単な設定は、Spring Boot の application.properties を介して提供できます。

spring.ai.vectorstore.redis.uri=<your redis instance uri>
spring.ai.vectorstore.redis.index=<your index name>
spring.ai.vectorstore.redis.prefix=<your prefix>

# API key if needed, e.g. OpenAI
spring.ai.openai.api.key=<api-key>

デフォルト値と構成オプションについては、ベクトルストアの構成パラメーターのリストを参照してください。

これで、Redis ベクトルストア をアプリケーションに自動接続して使用できるようになりました。

@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 Redis
vectorStore.add(List.of(document));

// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.query("Spring").withTopK(5));

構成プロパティ

Spring Boot 構成で次のプロパティを使用して、Redis ベクトルストアをカスタマイズできます。

プロパティ 説明 デフォルト値

spring.ai.vectorstore.redis.uri

サーバー接続 URI

redis://localhost:6379

spring.ai.vectorstore.redis.index

インデックス名

default-index

spring.ai.vectorstore.redis.initialize-schema

必要なスキーマを初期化するかどうか

false

spring.ai.vectorstore.redis.prefix

接頭辞

default:

メタデータのフィルタリング

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:[2020 inf]

手動構成

自動構成を使用しない場合は、Redis ベクトルストアを手動で構成できます。Redis ベクトルストアと Jedis の依存関係を追加します。

<dependency>
  <groupId>org.springframework.ai</groupId>
  <artifactId>spring-ai-redis-store</artifactId>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>5.1.0</version>
</dependency>
Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。

次に、Spring 構成で RedisVectorStore Bean を作成します。

@Bean
public VectorStore vectorStore(EmbeddingModel embeddingModel) {
  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, embeddingModel);
}

RedisVectorStore を Bean として作成する方が便利であり、推奨されます。ただし、手動で作成する場合は、プロパティを設定した後、クライアントを使用する前に RedisVectorStore#afterPropertiesSet() を呼び出す必要があります。

フィルター式で使用されるメタデータフィールドのすべてのメタデータフィールド名と型 (TAGTEXT、または 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!!" というテキストを含むドキュメントを取得する必要があります。