Redis®*: 向量搜尋與RAG
使用Redis進行語意搜尋、推薦系統及檢索增強生成(RAG)
👋 歡迎瀏覽 Stackhero 文件!
Stackhero 提供即開即用的 Redis cloud 方案,帶來多項優勢,包括:
- 已包含
Redis Commander網頁介面。- 無限訊息大小及傳輸量。
- 一鍵輕鬆完成更新。
- 以專屬私人基礎設施提供最佳效能及強大安全性。
節省時間,簡化您的工作流程:只需5分鐘即可體驗 Stackhero 的 Redis cloud hosting 方案!
如果您正在開發語意搜尋、推薦引擎或檢索增強生成(RAG)流程,您需要一個可靠的方法來儲存embeddings,並能夠快速找到與查詢最接近的匹配項。您在Stackhero上的Redis實例原生支援這個功能:查詢引擎會為向量建立索引,並能在毫秒級回應相似度搜尋。您無需額外部署獨立的向量資料庫,所有功能都集中在同一個地方。
這種做法之所以高效且具生產力,主要得益於兩個關鍵特點:
- 混合查詢(Hybrid queries)。 您可以在單一請求中,將向量相似度搜尋與標準篩選條件(如數值範圍、標籤或全文檢索)結合。例如:「找出最接近這個問題的5個片段,但僅限於這位用戶有權閱讀、且於一月後發佈的文件」——這樣的需求可以用一個查詢完成,無需多次請求。
- 簡化架構。 Embeddings、快取(cache)及sessions可共存於同一服務,並共用認證、備份及監控,從而降低系統複雜度及管理負擔。
開始前
請於Stackhero 控制台的服務設定內的Modules區段啟用Search模組(如需以JSON格式儲存文件,亦請啟用JSON模組)。詳細步驟請參閱Search與JSON指南。
建立向量索引
要宣告一個向量欄位,請指定其維度(dimension)及距離度量(distance metric)。維度需與您的embedding模型一致:例如,OpenAI text-embedding-3-small為1536,許多開源模型則為768等。
FT.CREATE chunksIndex
ON HASH
PREFIX 1 chunk:
SCHEMA
content TEXT
documentId TAG
publishedAt NUMERIC
embedding VECTOR HNSW 6
TYPE FLOAT32
DIM 1536
DISTANCE_METRIC COSINE
HNSW會建立一個圖形索引(graph index),即使您的資料集規模增長,查詢速度仍然維持快速。這在向量數量超過數千時尤其適用。若您的資料集較小且需精確結果,可選用FLAT進行暴力搜尋。
COSINE是大多數文本embedding模型推薦的距離度量。若您的應用有特殊需求,也可選擇L2或IP。
查詢
K近鄰(KNN)查詢語法如下。向量需以原始little-endian float32 bytes格式傳入:
FT.SEARCH chunksIndex "*=>[KNN 5 @embedding $queryVector AS score]"
PARAMS 2 queryVector "<rawBytes>"
SORTBY score
RETURN 2 content score
DIALECT 2
如需結合相似度搜尋與篩選條件,只需將*替換為篩選表達式:
FT.SEARCH chunksIndex "(@documentId:{doc42} @publishedAt:[1735689600 +inf])=>[KNN 5 @embedding $queryVector AS score]"
PARAMS 2 queryVector "<rawBytes>"
SORTBY score
DIALECT 2
向量查詢必須使用
DIALECT 2。如省略此參數,查詢將採用舊語法並返回錯誤。
Node.js中的RAG流程範例
import { createClient, SCHEMA_FIELD_TYPE, SCHEMA_VECTOR_FIELD_ALGORITHM } from 'redis';
const client = createClient({ url: process.env.STACKHERO_REDIS_URL_TLS });
await client.connect();
const DIMENSIONS = 1536;
const toBytes = embedding => Buffer.from(new Float32Array(embedding).buffer);
// 1. 啟動時建立索引(只需一次)
try {
await client.ft.create(
'chunksIndex',
{
content: SCHEMA_FIELD_TYPE.TEXT,
documentId: SCHEMA_FIELD_TYPE.TAG,
embedding: {
type: SCHEMA_FIELD_TYPE.VECTOR,
ALGORITHM: SCHEMA_VECTOR_FIELD_ALGORITHM.HNSW,
TYPE: 'FLOAT32',
DIM: DIMENSIONS,
DISTANCE_METRIC: 'COSINE'
}
},
{ ON: 'HASH', PREFIX: 'chunk:' }
);
}
catch (error) {
if (!error.message.includes('Index already exists')) {
throw error;
}
}
// 2. 將片段(chunk)建立索引(embedding由您的模型提供)
async function indexChunk({ id, documentId, content, embedding }) {
await client.hSet(`chunk:${id}`, {
content,
documentId,
embedding: toBytes(embedding)
});
}
// 3. 查詢最接近問題的片段,並限制於單一文件
async function retrieve({ questionEmbedding, documentId, count = 5 }) {
const results = await client.ft.search(
'chunksIndex',
`(@documentId:{${documentId}})=>[KNN ${count} @embedding $queryVector AS score]`,
{
PARAMS: { queryVector: toBytes(questionEmbedding) },
SORTBY: 'score',
RETURN: [ 'content', 'score' ],
DIALECT: 2
}
);
return results.documents.map(({ value }) => value.content);
}
// 4. 將查詢結果作為context傳給您的模型
const context = await retrieve({ questionEmbedding, documentId: 'doc42' });
const prompt = `請僅根據以下context作答:\n\n${context.join('\n\n')}\n\n問題:${question}`;
Python範例
import os
import numpy as np
import redis
from redis.commands.search.field import TextField, TagField, VectorField
from redis.commands.search.index_definition import IndexDefinition, IndexType
from redis.commands.search.query import Query
DIMENSIONS = 1536
r = redis.from_url(os.environ['STACKHERO_REDIS_URL_TLS'])
# 啟動時建立索引(只需一次)
try:
r.ft('chunksIndex').create_index(
(
TextField('content'),
TagField('documentId'),
VectorField(
'embedding',
'HNSW',
{'TYPE': 'FLOAT32', 'DIM': DIMENSIONS, 'DISTANCE_METRIC': 'COSINE'},
),
),
definition=IndexDefinition(prefix=['chunk:'], index_type=IndexType.HASH),
)
except redis.ResponseError as error:
if 'Index already exists' not in str(error):
raise
def index_chunk(chunk_id, document_id, content, embedding):
r.hset(
f'chunk:{chunk_id}',
mapping={
'content': content,
'documentId': document_id,
'embedding': np.array(embedding, dtype=np.float32).tobytes(),
},
)
def retrieve(question_embedding, document_id, count=5):
query = (
Query(f'(@documentId:{{{document_id}}})=>[KNN {count} @embedding $queryVector AS score]')
.sort_by('score')
.return_fields('content', 'score')
.dialect(2)
)
results = r.ft('chunksIndex').search(
query,
query_params={'queryVector': np.array(question_embedding, dtype=np.float32).tobytes()},
)
return [document.content for document in results.docs]
服務規模規劃
向量會儲存在記憶體中。您可以用以下公式估算所需記憶體:
numberOfVectors x dimensions x 4 bytes,再加上約30–50%額外空間以儲存HNSW圖形。
例如,一百萬個1536維的向量,僅原始向量就需約6GB記憶體。對這種規模,建議選擇20GB方案作為起點。您可以透過以下方式減少記憶體用量:
- 使用較小的模型。 例如,768維模型的記憶體需求僅為1536維模型的一半。
- 如模型支援,將
FLOAT32改為FLOAT16,可再減半空間需求。
您可透過FT.INFO chunksIndex及Prometheus監控中的used_memory指標,監察實際用量。如有需要,您可隨時於控制台升級方案,操作簡單直接。
實用資訊
- 向量索引僅支援資料庫0,這與Redis所有搜尋索引一致。
- 向量集合(Vector sets)提供更簡單的替代方案,無需任何設定。 Redis內建
VADD及VSIM指令,讓您可即時進行相似度搜尋,無需啟用模組。這對於單一集合的簡單推薦場景非常方便。如需篩選、分頁或多欄位查詢,建議使用查詢引擎。 - 針對現有key建立索引會於背景執行。 您可用
FT.INFO查詢進度。索引未完成前,搜尋會返回部分結果。
如欲深入了解Redis的向量搜尋,請參閱官方Redis vector search文件。