redis-search
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRedis Search
Redis Search
Single source of guidance for Redis Search — the retrieval surface that spans lexical, numeric, geo, JSON-path, and vector queries. Vector fields are part of the same machinery as TEXT/TAG/NUMERIC fields, and blends lexical and vector ranking in one command, so this skill covers them together.
FT.CREATEFT.HYBRID这是Redis Search的一站式指南——它是一个支持词汇、数值、地理、JSON路径和向量查询的检索引擎。向量字段与TEXT/TAG/NUMERIC字段共用同一套机制,且命令可在单次操作中融合词汇与向量排序,因此本指南将它们放在一起讲解。
FT.CREATEFT.HYBRIDWhen to apply
适用场景
- Creating, modifying, or reviewing a Redis Search index (,
FT.CREATE).FT.ALTER - Writing or optimizing ,
FT.SEARCH, orFT.AGGREGATEqueries.FT.HYBRID - Picking between ,
TEXT,TAG,NUMERIC,GEO,GEOSHAPE, or JSON-path fields.VECTOR - Defining a field, choosing HNSW vs FLAT, tuning HNSW parameters.
VECTOR - Building a retrieval-augmented generation (RAG) pipeline.
- Rolling out a new index schema without downtime.
- Troubleshooting empty results, slow queries, or tokenization issues with ,
FT.EXPLAIN,FT.PROFILE.FT.INFO
- 创建、修改或审核Redis Search索引(、
FT.CREATE)。FT.ALTER - 编写或优化、
FT.SEARCH或FT.AGGREGATE查询。FT.HYBRID - 在、
TEXT、TAG、NUMERIC、GEO、GEOSHAPE或JSON路径字段中进行选择。VECTOR - 定义字段,选择HNSW或FLAT算法,调优HNSW参数。
VECTOR - 构建检索增强生成(RAG)管道。
- 零停机推出新的索引schema。
- 使用、
FT.EXPLAIN、FT.PROFILE排查结果为空、查询缓慢或分词问题。FT.INFO
1. Pick the right command
1. 选择合适的命令
Three query commands. Reach for the narrowest one that fits.
| Command | When to use | Mental model | Minimum Redis |
|---|---|---|---|
| FT.SEARCH | Document retrieval, ranked or sorted. Best default. | Returns matching docs directly. | 2.0 (module) / 8.0 (built-in) |
| FT.AGGREGATE | Faceting, computed fields, custom output shape, analytics. | Declarative pipeline: | 2.0 / 8.0 |
| FT.HYBRID | Blend lexical (BM25) with vector similarity, with configurable fusion. | Pipeline with explicit | 8.4.0 |
undefined共有三种查询命令,请选择最贴合需求的窄范围命令。
| 命令 | 使用场景 | 思维模型 | 最低Redis版本 |
|---|---|---|---|
| FT.SEARCH | 文档检索,支持排序或排名。默认首选命令。 | 直接返回匹配的文档。 | 2.0(模块版)/ 8.0(内置版) |
| FT.AGGREGATE | 分面统计、计算字段、自定义输出格式、数据分析。 | 声明式管道: | 2.0 / 8.0 |
| FT.HYBRID | 融合词汇(BM25)与向量相似度,支持可配置的融合策略。 | 包含明确 | 8.4.0 |
undefinedFT.SEARCH — most common
FT.SEARCH — 最常用
FT.SEARCH idx:products "@category:{electronics} @price:[100 500]" LIMIT 0 20 RETURN 3 name price category
FT.SEARCH idx:products "@category:{electronics} @price:[100 500]" LIMIT 0 20 RETURN 3 name price category
FT.AGGREGATE — top categories by avg price
FT.AGGREGATE — 按平均价格排序的热门分类
FT.AGGREGATE idx:products "*" GROUPBY 1 @category REDUCE AVG 1 @price AS avg_price SORTBY 2 @avg_price DESC
FT.AGGREGATE idx:products "*" GROUPBY 1 @category REDUCE AVG 1 @price AS avg_price SORTBY 2 @avg_price DESC
FT.HYBRID (Redis ≥ 8.4) — lexical + vector fusion
FT.HYBRID (Redis ≥ 8.4) — 词汇+向量融合
FT.HYBRID idx:docs
SEARCH "@title:transformers" SCORER BM25 YIELD_SCORE_AS lexscore
VSIM embedding $vec KNN count 1 K 50 YIELD_SCORE_AS vecscore
COMBINE RRF 2 CONSTANT 60
PARAMS 2 vec "..."
DIALECT 2
For Redis < 8.4 the lexical+vector blend is approximated with `FT.SEARCH` pre-filter + `=>[KNN ...]`. See [references/command-selection.md](references/command-selection.md) and [references/hybrid-search.md](references/hybrid-search.md).FT.HYBRID idx:docs
SEARCH "@title:transformers" SCORER BM25 YIELD_SCORE_AS lexscore
VSIM embedding $vec KNN count 1 K 50 YIELD_SCORE_AS vecscore
COMBINE RRF 2 CONSTANT 60
PARAMS 2 vec "..."
DIALECT 2
对于Redis < 8.4版本,词汇+向量融合可通过`FT.SEARCH`预过滤 + `=>[KNN ...]`近似实现。详见[references/command-selection.md](references/command-selection.md)和[references/hybrid-search.md](references/hybrid-search.md)。2. Schema basics — FT.CREATE
FT.CREATE2. Schema基础 — FT.CREATE
FT.CREATEFT.CREATEPREFIXPREFIXDIALECT 2FT.CREATE idx:products ON HASH PREFIX 1 product:
SCHEMA
name TEXT WEIGHT 2.0
category TAG SORTABLE
price NUMERIC SORTABLE
location GEO
embedding VECTOR HNSW 6
TYPE FLOAT32
DIM 1536
DISTANCE_METRIC COSINEPick the narrowest field type that supports your access pattern:
| Field type | Use when | Notes |
|---|---|---|
| Full-text search | Tokenized + stemmed; not for exact match |
| Exact match / filtering | Add |
| Range queries, sorting | Prices, counts, timestamps |
| Lat/long points | Stores, users |
| Polygon / area queries | Delivery zones, regions |
| Similarity search | HNSW or FLAT; see §4 |
JSON | Nested JSON fields | |
The classic mistake is for a category or status field "because it's a string" — is roughly 10× faster for exact-match filtering.
TEXTTAGSee references/index-creation.md, references/field-types.md, references/dialect.md, references/ft-create-options.md, references/json-indexing.md.
FT.CREATEPREFIXPREFIXDIALECT 2FT.CREATE idx:products ON HASH PREFIX 1 product:
SCHEMA
name TEXT WEIGHT 2.0
category TAG SORTABLE
price NUMERIC SORTABLE
location GEO
embedding VECTOR HNSW 6
TYPE FLOAT32
DIM 1536
DISTANCE_METRIC COSINE选择最贴合访问模式的窄范围字段类型:
| 字段类型 | 使用场景 | 注意事项 |
|---|---|---|
| 全文搜索 | 会进行分词+词干提取;不适合精确匹配 |
| 精确匹配/过滤 | 添加 |
| 范围查询、排序 | 价格、计数、时间戳等 |
| 经纬度点 | 店铺、用户位置等 |
| 多边形/区域查询 | 配送区域、行政区域等 |
| 相似度搜索 | HNSW或FLAT算法;详见第4节 |
JSON | 嵌套JSON字段 | 需使用 |
常见错误是将分类或状态字段设为(“因为它是字符串”)——在精确匹配过滤时速度大约快10倍。
TEXTTAG详见references/index-creation.md、references/field-types.md、references/dialect.md、references/ft-create-options.md、references/json-indexing.md。
3. Common queries
3. 常见查询
Narrow with filters; return only what you need.
undefined使用过滤缩小范围;仅返回所需内容。
undefinedTag filter + numeric range, sorted by price
标签过滤+数值范围,按价格排序
FT.SEARCH idx:products "@category:{electronics} @price:[100 500]"
SORTBY price ASC
LIMIT 0 20
RETURN 3 name price category
FT.SEARCH idx:products "@category:{electronics} @price:[100 500]"
SORTBY price ASC
LIMIT 0 20
RETURN 3 name price category
Text + tag filter
文本+标签过滤
FT.SEARCH idx:products "wireless headphones @category:{audio}"
FT.SEARCH idx:products "wireless headphones @category:{audio}"
Negation and OR
否定与或操作
FT.SEARCH idx:products "@category:{audio} -@brand:{generic} (@price:[0 100] | @on_sale:{true})"
Operators worth remembering: space = AND, `|` = OR, `-` = NOT, `~` = optional (scoring boost), `=>{$weight: N}` = boost. Escape hyphens and special characters inside TAG values (`@sku:{ABC\\-123}`). See [references/query-syntax.md](references/query-syntax.md) and [references/search-syntax-primitives.md](references/search-syntax-primitives.md) for the DSL vocabulary.
For tokenization gotchas (stemming, stopwords, language) see [references/text-tokenization.md](references/text-tokenization.md). For result shaping (`SORTBY`, `RETURN`, `HIGHLIGHT`, `SUMMARIZE`, `NOCONTENT`) see [references/result-shaping.md](references/result-shaping.md). For performance levers (pre-filters, `SORTABLE` fields, tight `RETURN`, `FT.PROFILE`) see [references/query-optimization.md](references/query-optimization.md).FT.SEARCH idx:products "@category:{audio} -@brand:{generic} (@price:[0 100] | @on_sale:{true})"
值得记住的操作符:空格=AND,`|`=OR,`-`=NOT,`~`=可选(评分提升),`=>{$weight: N}`=权重提升。TAG值中的连字符和特殊字符需转义(`@sku:{ABC\\-123}`)。DSL词汇详见[references/query-syntax.md](references/query-syntax.md)和[references/search-syntax-primitives.md](references/search-syntax-primitives.md)。
关于分词陷阱(词干提取、停用词、语言)详见[references/text-tokenization.md](references/text-tokenization.md)。关于结果格式化(`SORTBY`、`RETURN`、`HIGHLIGHT`、`SUMMARIZE`、`NOCONTENT`)详见[references/result-shaping.md](references/result-shaping.md)。关于性能优化手段(预过滤、`SORTABLE`字段、精简`RETURN`、`FT.PROFILE`)详见[references/query-optimization.md](references/query-optimization.md)。4. Vector basics
4. 向量基础
Three vector settings have to match the embedding model exactly:
- — output dimensionality (e.g. 1536 for OpenAI
DIM). Mismatch produces silent garbage.text-embedding-3-small - —
DISTANCE_METRICfor normalized text embeddings (common case),COSINEfor unnormalized inner-product,IPfor raw Euclidean.L2 - — usually
TYPE. UseFLOAT32or quantized variants only when memory is the binding constraint.FLOAT16
undefined三个向量设置必须与嵌入模型完全匹配:
- — 输出维度(例如OpenAI
DIM为1536)。不匹配会导致无提示的错误结果。text-embedding-3-small - — 归一化文本嵌入使用
DISTANCE_METRIC(常见场景),未归一化内积使用COSINE,原始欧氏距离使用IP。L2 - — 通常为
TYPE。仅当内存是瓶颈时才使用FLOAT32或量化变体。FLOAT16
undefinedIndex
索引
FT.CREATE idx:docs ON HASH PREFIX 1 doc:
SCHEMA
content TEXT
embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1536 DISTANCE_METRIC COSINE
FT.CREATE idx:docs ON HASH PREFIX 1 doc:
SCHEMA
content TEXT
embedding VECTOR HNSW 6 TYPE FLOAT32 DIM 1536 DISTANCE_METRIC COSINE
Pure KNN query (top 5 by cosine similarity)
纯KNN查询(余弦相似度前5)
FT.SEARCH idx:docs "*=>[KNN 5 @embedding $vec AS score]"
PARAMS 2 vec "..."
SORTBY score
DIALECT 2
| Algorithm | Speed | Accuracy | Memory | Use for |
|---|---|---|---|---|
| **HNSW** | Fast (approximate) | ~95%+ recall (tunable) | Higher | Production: >10k vectors, latency-sensitive |
| **FLAT** | Slow (exact) | 100% | Lower | Small corpora (<10k), exact-match required |
HNSW tuning levers: `M` (16–64, connections per node), `EF_CONSTRUCTION` (100–500, build quality), `EF_RUNTIME` (query-time candidate list).
See [references/vector-query.md](references/vector-query.md), [references/algorithm-choice.md](references/algorithm-choice.md).FT.SEARCH idx:docs "*=>[KNN 5 @embedding $vec AS score]"
PARAMS 2 vec "..."
SORTBY score
DIALECT 2
| 算法 | 速度 | 准确率 | 内存占用 | 适用场景 |
|---|---|---|---|---|
| **HNSW** | 快(近似) | ~95%+召回率(可调节) | 较高 | 生产环境:向量数>10k,对延迟敏感 |
| **FLAT** | 慢(精确) | 100% | 较低 | 小型语料库(<10k向量),需精确匹配 |
HNSW调优参数:`M`(16–64,每个节点的连接数)、`EF_CONSTRUCTION`(100–500,构建质量)、`EF_RUNTIME`(查询时候选列表大小)。
详见[references/vector-query.md](references/vector-query.md)、[references/algorithm-choice.md](references/algorithm-choice.md)。5. Hybrid retrieval
5. 混合检索
Two distinct patterns get called "hybrid." Pick by intent.
Filter-then-vector (any Redis version) — apply attribute filters so the engine narrows the search space before the vector comparison.
FT.SEARCH idx:docs "(@category:{tech} @date:[2024 +inf])=>[KNN 10 @embedding $vec AS score]"
PARAMS 2 vec "..."
SORTBY score
DIALECT 2Lexical + vector fusion (Redis ≥ 8.4) — blend BM25 text scoring with vector similarity, fuse with or . Use (see §1).
RRFLINEARFT.HYBRIDDon't fetch a wide unfiltered result and filter client-side — slower and less accurate. See references/hybrid-search.md.
有两种不同的模式被称为“混合检索”,根据意图选择。
先过滤后向量(任何Redis版本)——先应用属性过滤缩小搜索范围,再进行向量比较。
FT.SEARCH idx:docs "(@category:{tech} @date:[2024 +inf])=>[KNN 10 @embedding $vec AS score]"
PARAMS 2 vec "..."
SORTBY score
DIALECT 2词汇+向量融合(Redis ≥ 8.4)——将BM25文本评分与向量相似度融合,使用或策略。使用(见第1节)。
RRFLINEARFT.HYBRID请勿先获取大范围未过滤结果再在客户端过滤——速度更慢且准确率更低。详见references/hybrid-search.md。
6. Aggregations and shaping
6. 聚合与格式化
FT.AGGREGATEundefinedFT.AGGREGATEundefinedTop 5 categories by total revenue
按总营收排序的前5分类
FT.AGGREGATE idx:orders "@status:{shipped}"
LOAD 2 @category @amount
GROUPBY 1 @category
REDUCE SUM 1 @amount AS revenue
SORTBY 2 @revenue DESC
LIMIT 0 5
Common stages: `LOAD`, `APPLY` (computed fields), `FILTER` (post-query), `GROUPBY` + `REDUCE` (`SUM`, `COUNT`, `AVG`, `FIRST_VALUE`, `TOLIST`), `SORTBY`, `LIMIT`.
For long-running result sets use `WITHCURSOR` + `FT.CURSOR READ` to page server-side. See [references/aggregate-pipeline.md](references/aggregate-pipeline.md) and [references/aggregate-cursors.md](references/aggregate-cursors.md).FT.AGGREGATE idx:orders "@status:{shipped}"
LOAD 2 @category @amount
GROUPBY 1 @category
REDUCE SUM 1 @amount AS revenue
SORTBY 2 @revenue DESC
LIMIT 0 5
常见阶段:`LOAD`、`APPLY`(计算字段)、`FILTER`(查询后过滤)、`GROUPBY`+`REDUCE`(`SUM`、`COUNT`、`AVG`、`FIRST_VALUE`、`TOLIST`)、`SORTBY`、`LIMIT`。
对于长结果集,使用`WITHCURSOR`+`FT.CURSOR READ`实现服务端分页。详见[references/aggregate-pipeline.md](references/aggregate-pipeline.md)和[references/aggregate-cursors.md](references/aggregate-cursors.md)。7. RAG pattern
7. RAG模式
Standard pipeline: embed the query, vector-search Redis, pass top-K context to the LLM.
Practical tips:
- Match the metric to the embedding model (almost always for normalized text models).
COSINE - Chunk long documents (200–500-token chunks usually beat indexing whole pages).
- Batch inserts rather than one call per record.
- Pre-filter with attributes (tenant, recency, document type) before the vector search — see §5.
- Re-rank at the top of the funnel if precision matters more than recall.
See references/rag-pattern.md.
标准流程:嵌入查询词,在Redis中进行向量搜索,将Top-K上下文传递给LLM。
实用技巧:
- 匹配度量方式与嵌入模型一致(归一化文本模型几乎总是使用)。
COSINE - 拆分长文档(200–500 token的片段通常比索引整页效果更好)。
- 批量插入而非单条记录逐个调用。
- 向量搜索前先进行属性预过滤(租户、时效性、文档类型)——见第5节。
- 如果精度比召回率更重要,在顶层进行重排序。
详见references/rag-pattern.md。
8. Operations
8. 运维
Zero-downtime schema changes: keep app queries pointed at an alias and swap the underlying index.
FT.CREATE idx:products_v2 ON HASH PREFIX 1 product: SCHEMA ...
FT.ALIASUPDATE products idx:products_v2零停机schema变更:保持应用查询指向别名,然后切换底层索引。
FT.CREATE idx:products_v2 ON HASH PREFIX 1 product: SCHEMA ...
FT.ALIASUPDATE products idx:products_v2App queries are stable:
应用查询保持稳定:
FT.SEARCH products "@category:{electronics}"
Useful management commands: `FT.INFO`, `FT.DROPINDEX`, `FT._LIST`, `FT.ALIASADD/UPDATE/DEL`. See [references/index-management.md](references/index-management.md).
Debug empty or slow queries with `FT.EXPLAIN` (shows how the query was parsed) and `FT.PROFILE` (shows execution stats). See [references/debugging.md](references/debugging.md).FT.SEARCH products "@category:{electronics}"
实用管理命令:`FT.INFO`、`FT.DROPINDEX`、`FT._LIST`、`FT.ALIASADD/UPDATE/DEL`。详见[references/index-management.md](references/index-management.md)。
使用`FT.EXPLAIN`(显示查询解析方式)和`FT.PROFILE`(显示执行统计)排查结果为空或查询缓慢的问题。详见[references/debugging.md](references/debugging.md)。9. Client examples
9. 客户端示例
Inline examples in this SKILL.md are CLI / RESP form — the wire protocol every client serializes to. For idiomatic snippets in a specific client:
- redis-py (Python, raw client): references/clients/python-redis-py.md
- Jedis (Java): references/clients/java-jedis.md
- RedisVL (Python, higher-level SDK on top of redis-py): references/clients/python-redisvl.md
Other clients (Lettuce, node-redis, go-redis, NRedisStack, .NET) translate the same CLI form; coverage is tracked as a follow-up.
本SKILL.md中的内联示例为CLI/RESP格式——这是所有客户端都会序列化的有线协议。如需特定客户端的惯用代码片段:
- redis-py(Python,原生客户端):references/clients/python-redis-py.md
- Jedis(Java):references/clients/java-jedis.md
- RedisVL(Python,基于redis-py的高层SDK):references/clients/python-redisvl.md
其他客户端(Lettuce、node-redis、go-redis、NRedisStack、.NET)均可转换为相同的CLI格式;后续会跟踪覆盖情况。