このバージョンはまだ開発中であり、まだ安定しているとは考えられていません。最新のスナップショットバージョンについては、Spring AI 1.1.2 を使用してください。 |
Redis
このセクションでは、ドキュメントの埋め込みを保存し、類似性検索を実行するための RedisVectorStore のセットアップについて説明します。
Redis (英語) は、データベース、キャッシュ、メッセージブローカー、ストリーミングエンジンとして使用されるオープンソース (BSD ライセンス) のインメモリデータ構造ストアです。Redis は、文字列、ハッシュ、リスト、セット、範囲クエリを備えたソートセット、ビットマップ、ハイパーログログ、地理空間インデックス、ストリームなどのデータ構造を提供します。
Redis 検索とクエリ (英語) は、Redis OSS のコア機能を継承し、Redis をベクトルデータベースとして使用できるようにします。
ベクトルと関連するメタデータをハッシュまたは JSON ドキュメント内に保存します
ベクトルの取得
ベクトル類似性検索を実行する (KNN)
半径しきい値を使用した範囲ベースのベクトル検索を実行する
TEXT フィールドで全文検索を実行する
複数の距離メトリクス(COSINE、L2、IP)とベクトルアルゴリズムのサポート (HNSW, FLAT)
前提条件
Redis スタックインスタンス
Redis クラウド (英語) (推奨)
Docker (英語) イメージ redis/redis スタック: 最新
EmbeddingModelインスタンスを使用してドキュメントの埋め込みを計算します。いくつかのオプションが利用可能です:必要に応じて、EmbeddingModel が
RedisVectorStoreによって保存される埋め込みを生成するための API キー。
自動構成
Spring AI 自動構成、スターターモジュールのアーティファクト名に大きな変更がありました。詳細については、アップグレードノートを参照してください。 |
Spring AI は、Redis ベクトルストア用の Spring Boot 自動構成を提供します。これを有効にするには、プロジェクトの Maven pom.xml ファイルに次の依存関係を追加します。
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-redis</artifactId>
</dependency> または、Gradle build.gradle ビルドファイルに保存します。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-redis'
}| Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。 |
| アーティファクトリポジトリセクションを参照して、ビルドファイルに Maven Central リポジトリやスナップショットリポジトリを追加します。 |
ベクトルストアの実装では必要なスキーマを初期化できますが、適切なコンストラクターで initializeSchema ブール値を指定するか、application.properties ファイルで …initialize-schema=true を設定することによってオプトインする必要があります。
| これは重大な変更です。Spring AI の以前のバージョンでは、このスキーマの初期化はデフォルトで行われていました。 |
デフォルト値と構成オプションについては、ベクトルストアの構成パラメーターのリストを参照してください。
さらに、設定済みの EmbeddingModel Bean が必要です。詳細については、"EmbeddingModel" セクションを参照してください。
これで、RedisVectorStore をアプリケーション内のベクトルストアとして自動接続できるようになりました。
@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(documents);
// Retrieve documents similar to a query
List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());プロパティの構成
Redis に接続して RedisVectorStore を使用するには、インスタンスのアクセス詳細を提供する必要があります。簡単な構成は、Spring Boot の application.yml を介して提供できます。
spring:
data:
redis:
url: <redis instance url>
ai:
vectorstore:
redis:
initialize-schema: true
index-name: custom-index
prefix: custom-prefixredis 接続構成の場合、代わりに、Spring Boot の application.properties を介して簡単な構成を提供することもできます。
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.username=default
spring.data.redis.password=spring.ai.vectorstore.redis.* で始まるプロパティは、RedisVectorStore を構成するために使用されます。
| プロパティ | 説明 | デフォルト値 |
|---|---|---|
| 必要なスキーマを初期化するかどうか |
|
| ベクトルを格納するインデックスの名前 |
|
| Redis キーのプレフィックス |
|
| Distance metric for vector similarity (コサイン、L2、IP) |
|
| Vector indexing algorithm (HNSW, FLAT) |
|
| HNSW: Number of maximum outgoing connections |
|
| HNSW: Number of maximum connections during index building |
|
| HNSW: Number of connections to consider during search |
|
| Default radius threshold for range searches |
|
| Text scoring algorithm (BM25, TFIDF, BM25STD, DISMAX, DOCSCORE) |
|
メタデータフィルタリング
Redis でも、汎用的でポータブルなメタデータフィルターを活用できます。
例: 次のいずれかのテキスト式言語を使用できます。
vectorStore.similaritySearch(SearchRequest.builder()
.query("The World")
.topK(TOP_K)
.similarityThreshold(SIMILARITY_THRESHOLD)
.filterExpression("country in ['UK', 'NL'] && year >= 2020").build()); または、Filter.Expression DSL を使用してプログラム的に次のようにします。
FilterExpressionBuilder b = new FilterExpressionBuilder();
vectorStore.similaritySearch(SearchRequest.builder()
.query("The World")
.topK(TOP_K)
.similarityThreshold(SIMILARITY_THRESHOLD)
.filterExpression(b.and(
b.in("country", "UK", "NL"),
b.gte("year", 2020)).build()).build());| これらの (ポータブル) フィルター式は自動的に Redis 検索クエリ (英語) に変換されます。 |
例: この移植可能なフィルター式:
country in ['UK', 'NL'] && year >= 2020独自の Redis フィルター形式に変換されます。
@country:{UK | NL} @year:[2020 inf]手動構成
Spring Boot の自動構成を使用する代わりに、Redis ベクトルストアを手動で構成できます。そのためには、プロジェクトに spring-ai-redis-store を追加する必要があります。
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-redis-store</artifactId>
</dependency> または、Gradle build.gradle ビルドファイルに保存します。
dependencies {
implementation 'org.springframework.ai:spring-ai-redis-store'
}JedisPooled Bean を作成します。
@Bean
public JedisPooled jedisPooled() {
return new JedisPooled("<host>", 6379);
} 次に、ビルダーパターンを使用して RedisVectorStore Bean を作成します。
@Bean
public VectorStore vectorStore(JedisPooled jedisPooled, EmbeddingModel embeddingModel) {
return RedisVectorStore.builder(jedisPooled, embeddingModel)
.indexName("custom-index") // Optional: defaults to "spring-ai-index"
.prefix("custom-prefix") // Optional: defaults to "embedding:"
.contentFieldName("content") // Optional: field for document content
.embeddingFieldName("embedding") // Optional: field for vector embeddings
.vectorAlgorithm(Algorithm.HNSW) // Optional: HNSW or FLAT (defaults to HNSW)
.distanceMetric(DistanceMetric.COSINE) // Optional: COSINE, L2, or IP (defaults to COSINE)
.hnswM(16) // Optional: HNSW connections (defaults to 16)
.hnswEfConstruction(200) // Optional: HNSW build parameter (defaults to 200)
.hnswEfRuntime(10) // Optional: HNSW search parameter (defaults to 10)
.defaultRangeThreshold(0.8) // Optional: default radius for range searches
.textScorer(TextScorer.BM25) // Optional: text scoring algorithm (defaults to BM25)
.metadataFields( // Optional: define metadata fields for filtering
MetadataField.tag("country"),
MetadataField.numeric("year"),
MetadataField.text("description"))
.initializeSchema(true) // Optional: defaults to false
.batchingStrategy(new TokenCountBatchingStrategy()) // Optional: defaults to TokenCountBatchingStrategy
.build();
}
// This can be any EmbeddingModel implementation
@Bean
public EmbeddingModel embeddingModel() {
return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("OPENAI_API_KEY")));
} フィルター式で使用されるメタデータフィールドのすべてのメタデータフィールド名と型 ( |
ネイティブクライアントへのアクセス
Redis ベクトルストアの実装は、getNativeClient() メソッドを通じて、基盤となるネイティブ Redis クライアント (JedisPooled) へのアクセスを提供します。
RedisVectorStore vectorStore = context.getBean(RedisVectorStore.class);
Optional<JedisPooled> nativeClient = vectorStore.getNativeClient();
if (nativeClient.isPresent()) {
JedisPooled jedis = nativeClient.get();
// Use the native client for Redis-specific operations
} ネイティブクライアントを使用すると、VectorStore インターフェースでは公開されない可能性のある Redis 固有の機能と操作にアクセスできます。
Distance Metrics
The Redis Vector Store supports three distance metrics for vector similarity:
COSINE : Cosine similarity (default) - measures the cosine of the angle between vectors
L2 : Euclidean distance - measures the straight-line distance between vectors
IP : Inner Product - measures the dot product between vectors
Each metric is automatically normalized to a 0-1 similarity score, where 1 is most similar.
RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
.distanceMetric(DistanceMetric.COSINE) // or L2, IP
.build();HNSW Algorithm Configuration
The Redis Vector Store uses the HNSW (Hierarchical Navigable Small World) algorithm by default for efficient approximate nearest neighbor search. You can tune the HNSW parameters for your specific use case:
RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
.vectorAlgorithm(Algorithm.HNSW)
.hnswM(32) // Maximum outgoing connections per node (default: 16)
.hnswEfConstruction(100) // Connections during index building (default: 200)
.hnswEfRuntime(50) // Connections during search (default: 10)
.build();Parameter guidelines:
M : Higher values improve recall but increase memory usage and index time. Typical values: 12-48.
EF_CONSTRUCTION : Higher values improve index quality but increase build time. Typical values: 100-500.
EF_RUNTIME : Higher values improve search accuracy but increase latency. Typical values: 10-100.
For smaller datasets or when exact results are required, use the FLAT algorithm instead:
RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
.vectorAlgorithm(Algorithm.FLAT)
.build();テキスト検索
The Redis Vector Store provides text search capabilities using Redis Query Engine’s full-text search features. This allows you to find documents based on keywords and phrases in TEXT fields:
// Search for documents containing specific text
List<Document> textResults = vectorStore.searchByText(
"machine learning", // search query
"content", // field to search (must be TEXT type)
10, // limit
"category == 'AI'" // optional filter expression
);Text search supports:
Single word searches
Phrase searches with exact matching when
inOrderis trueTerm-based searches with OR semantics when
inOrderis falseStopword filtering to ignore common words
Multiple text scoring algorithms
Configure text search behavior at construction time:
RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
.textScorer(TextScorer.TFIDF) // Text scoring algorithm
.inOrder(true) // Match terms in order
.stopwords(Set.of("is", "a", "the", "and")) // Ignore common words
.metadataFields(MetadataField.text("description")) // Define TEXT fields
.build();Text Scoring Algorithms
Several text scoring algorithms are available:
BM25 : Modern version of TF-IDF with term saturation (default)
TFIDF : Classic term frequency-inverse document frequency
BM25STD : Standardized BM25
DISMAX : Disjunction max
DOCSCORE : Document score
Scores are normalized to a 0-1 range for consistency with vector similarity scores.
Range Search
The range search returns all documents within a specified radius threshold, rather than a fixed number of nearest neighbors:
// Search with explicit radius
List<Document> rangeResults = vectorStore.searchByRange(
"AI and machine learning", // query
0.8, // radius (similarity threshold)
"category == 'AI'" // optional filter expression
);You can also set a default range threshold at construction time:
RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
.defaultRangeThreshold(0.8) // Set default threshold
.build();
// Use default threshold
List<Document> results = vectorStore.searchByRange("query");Range search is useful when you want to retrieve all relevant documents above a similarity threshold, rather than limiting to a specific count.