Valkey: 向量搜索与RAG

使用Valkey进行语义搜索、推荐和检索增强生成(RAG)

👋 欢迎查阅 Stackhero 文档!

Stackhero 提供即开即用的 Valkey 云端 解决方案,带来多项优势,包括:

  • 集成 Valkey Admin Web 管理界面
  • 无限制的消息大小与传输。
  • 一键完成升级,操作便捷。
  • 基于专属私有基础设施,实现卓越性能与强大安全性

节省时间简化您的工作流程:只需 5 分钟即可体验 Stackhero 的 Valkey 云托管 方案!

如果您正在构建语义搜索、推荐引擎或检索增强生成(RAG)流程,您需要存储embedding,并能够快速找到与查询最接近的匹配项。Stackhero for Valkey原生支持这一需求:Search模块会对向量进行索引,并在毫秒级内响应相似度查询。您无需为已在使用的Valkey服务单独部署一个向量数据库。

这种方案之所以高效实用,主要得益于以下两点:

  • 混合查询。 您可以在一次请求中同时进行向量相似度搜索,并应用常规过滤(如数值区间、标签或文本)。例如,您可以通过一次查询检索“与该问题最接近的5个片段,但仅限于该用户有权限阅读的文档”,无需分两步操作。
  • 减少系统复杂度。 您的embedding与缓存和会话数据存储在一起,使用相同的凭据、备份和监控工具。这让您的技术栈更简单,管理更容易。

请在Stackhero 控制台的服务配置 Modules 部分启用 Search 模块(如需以JSON格式存储文档,也请启用 JSON 模块)。详细说明请参阅Search与JSON指南

声明向量字段时需指定其维度和距离度量方式。维度需与您的模型一致:例如,OpenAI的 text-embedding-3-small 需1536维,许多开源模型则为768维。

FT.CREATE chunksIndex
  ON HASH
  PREFIX 1 chunk:
  SCHEMA
    content TEXT
    documentId TAG
    embedding VECTOR HNSW 6
      TYPE FLOAT32
      DIM 1536
      DISTANCE_METRIC COSINE

HNSW 会创建图索引,即使数据量很大也能实现高效的近似搜索。对于几千条以上的向量集合,推荐使用HNSW。对于小型集合,可以使用 FLAT 进行精确、暴力搜索。

COSINE 通常是文本embedding的最佳距离度量方式。也支持 L2IP 度量。

K近邻(KNN)查询以参数形式传递向量,格式为原始little-endian float32字节:

FT.SEARCH chunksIndex "*=>[KNN 5 @embedding $queryVector]"
  PARAMS 2 queryVector "<rawBytes>"

如需结合向量搜索与过滤,只需将 * 替换为您的过滤表达式:

FT.SEARCH chunksIndex "@documentId:{doc42}=>[KNN 5 @embedding $queryVector]"
  PARAMS 2 queryVector "<rawBytes>"

Valkey采用与Redis相同的协议,因此您可以使用任何兼容Redis的客户端。

import { createClient, SCHEMA_FIELD_TYPE, SCHEMA_VECTOR_FIELD_ALGORITHM } from 'redis';

const client = createClient({ url: process.env.STACKHERO_VALKEY_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. 索引您的片段(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]`,
    { PARAMS: { queryVector: toBytes(questionEmbedding) } }
  );

  return results.documents.map(({ value }) => value.content);
}

// 4. 将检索到的内容作为上下文传递给模型
const context = await retrieve({ questionEmbedding, documentId: 'doc42' });
const prompt = `Answer using only this context:\n\n${context.join('\n\n')}\n\nQuestion: ${question}`;
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_VALKEY_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]')
    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]

向量存储在内存中,因此需要提前规划其内存占用。float32向量的粗略估算公式为:

numberOfVectors x dimensions x 4 bytes,再加上HNSW图结构大约30%到50%的额外空间。

例如,一百万条1536维向量,原始向量大约需要6GB内存。建议选择20GB套餐作为起步。您也可以通过选择维度更低的模型来降低内存消耗:768维模型的内存占用仅为1536维模型的一半。

您可以通过 FT.INFO chunksIndexPrometheus监控中的 used_memory 指标查看实际内存使用情况。如需更多内存,您可随时在控制台升级套餐。

  • 对已有键的索引在后台进行。 您可以通过 FT.INFO 跟踪进度。在回填完成前,搜索结果可能是部分的。
  • Search模块实现了一组精简的 FT.* 命令。 针对向量搜索,涵盖了所有核心功能:HNSW与精确KNN、混合过滤以及 FT.AGGREGATE

完整参考请参阅 Valkey search官方文档