redis-search

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Redis 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
FT.CREATE
machinery as TEXT/TAG/NUMERIC fields, and
FT.HYBRID
blends lexical and vector ranking in one command, so this skill covers them together.
这是Redis Search的一站式指南——它是一个支持词汇、数值、地理、JSON路径和向量查询的检索引擎。向量字段与TEXT/TAG/NUMERIC字段共用同一套
FT.CREATE
机制,且
FT.HYBRID
命令可在单次操作中融合词汇与向量排序,因此本指南将它们放在一起讲解。

When to apply

适用场景

  • Creating, modifying, or reviewing a Redis Search index (
    FT.CREATE
    ,
    FT.ALTER
    ).
  • Writing or optimizing
    FT.SEARCH
    ,
    FT.AGGREGATE
    , or
    FT.HYBRID
    queries.
  • Picking between
    TEXT
    ,
    TAG
    ,
    NUMERIC
    ,
    GEO
    ,
    GEOSHAPE
    ,
    VECTOR
    , or JSON-path fields.
  • Defining a
    VECTOR
    field, choosing HNSW vs FLAT, tuning HNSW parameters.
  • 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
    VECTOR
    或JSON路径字段中进行选择。
  • 定义
    VECTOR
    字段,选择HNSW或FLAT算法,调优HNSW参数。
  • 构建检索增强生成(RAG)管道。
  • 零停机推出新的索引schema。
  • 使用
    FT.EXPLAIN
    FT.PROFILE
    FT.INFO
    排查结果为空、查询缓慢或分词问题。

1. Pick the right command

1. 选择合适的命令

Three query commands. Reach for the narrowest one that fits.
CommandWhen to useMental modelMinimum Redis
FT.SEARCHDocument retrieval, ranked or sorted. Best default.Returns matching docs directly.2.0 (module) / 8.0 (built-in)
FT.AGGREGATEFaceting, computed fields, custom output shape, analytics.Declarative pipeline:
LOAD
,
APPLY
,
GROUPBY
,
REDUCE
,
SORTBY
.
2.0 / 8.0
FT.HYBRIDBlend lexical (BM25) with vector similarity, with configurable fusion.Pipeline with explicit
SEARCH
+
VSIM
legs and a
COMBINE
fusion stage.
8.4.0
undefined
共有三种查询命令,请选择最贴合需求的窄范围命令。
命令使用场景思维模型最低Redis版本
FT.SEARCH文档检索,支持排序或排名。默认首选命令。直接返回匹配的文档。2.0(模块版)/ 8.0(内置版)
FT.AGGREGATE分面统计、计算字段、自定义输出格式、数据分析。声明式管道:
LOAD
APPLY
GROUPBY
REDUCE
SORTBY
2.0 / 8.0
FT.HYBRID融合词汇(BM25)与向量相似度,支持可配置的融合策略。包含明确
SEARCH
+
VSIM
阶段和
COMBINE
融合阶段的管道。
8.4.0
undefined

FT.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

2. Schema基础 —
FT.CREATE

FT.CREATE
indexes Hash or JSON documents matching a
PREFIX
. Always set
PREFIX
. Use
DIALECT 2
(the default since Redis 8; required for vector queries).
FT.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
Pick the narrowest field type that supports your access pattern:
Field typeUse whenNotes
TEXT
Full-text searchTokenized + stemmed; not for exact match
TAG
Exact match / filteringAdd
SORTABLE UNF
for fastest tag queries
NUMERIC
Range queries, sortingPrices, counts, timestamps
GEO
Lat/long pointsStores, users
GEOSHAPE
Polygon / area queriesDelivery zones, regions
VECTOR
Similarity searchHNSW or FLAT; see §4
JSON
$.path AS alias
Nested JSON fields
ON JSON
; see references/json-indexing.md
The classic mistake is
TEXT
for a category or status field "because it's a string" —
TAG
is roughly 10× faster for exact-match filtering.
See references/index-creation.md, references/field-types.md, references/dialect.md, references/ft-create-options.md, references/json-indexing.md.
FT.CREATE
为匹配指定
PREFIX
的Hash或JSON文档创建索引。务必设置
PREFIX
。使用
DIALECT 2
(Redis 8起默认启用;向量查询必需)。
FT.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
选择最贴合访问模式的窄范围字段类型:
字段类型使用场景注意事项
TEXT
全文搜索会进行分词+词干提取;不适合精确匹配
TAG
精确匹配/过滤添加
SORTABLE UNF
可实现最快的标签查询
NUMERIC
范围查询、排序价格、计数、时间戳等
GEO
经纬度点店铺、用户位置等
GEOSHAPE
多边形/区域查询配送区域、行政区域等
VECTOR
相似度搜索HNSW或FLAT算法;详见第4节
JSON
$.path AS alias
嵌套JSON字段需使用
ON JSON
;详见references/json-indexing.md
常见错误是将分类或状态字段设为
TEXT
(“因为它是字符串”)——
TAG
在精确匹配过滤时速度大约快10倍。
详见references/index-creation.mdreferences/field-types.mdreferences/dialect.mdreferences/ft-create-options.mdreferences/json-indexing.md

3. Common queries

3. 常见查询

Narrow with filters; return only what you need.
undefined
使用过滤缩小范围;仅返回所需内容。
undefined

Tag 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:
  • DIM
    — output dimensionality (e.g. 1536 for OpenAI
    text-embedding-3-small
    ). Mismatch produces silent garbage.
  • DISTANCE_METRIC
    COSINE
    for normalized text embeddings (common case),
    IP
    for unnormalized inner-product,
    L2
    for raw Euclidean.
  • TYPE
    — usually
    FLOAT32
    . Use
    FLOAT16
    or quantized variants only when memory is the binding constraint.
undefined
三个向量设置必须与嵌入模型完全匹配:
  • DIM
    — 输出维度(例如OpenAI
    text-embedding-3-small
    为1536)。不匹配会导致无提示的错误结果。
  • DISTANCE_METRIC
    — 归一化文本嵌入使用
    COSINE
    (常见场景),未归一化内积使用
    IP
    ,原始欧氏距离使用
    L2
  • TYPE
    — 通常为
    FLOAT32
    。仅当内存是瓶颈时才使用
    FLOAT16
    或量化变体。
undefined

Index

索引

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 2
Lexical + vector fusion (Redis ≥ 8.4) — blend BM25 text scoring with vector similarity, fuse with
RRF
or
LINEAR
. Use
FT.HYBRID
(see §1).
Don'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文本评分与向量相似度融合,使用
RRF
LINEAR
策略。使用
FT.HYBRID
(见第1节)。
请勿先获取大范围未过滤结果再在客户端过滤——速度更慢且准确率更低。详见references/hybrid-search.md

6. Aggregations and shaping

6. 聚合与格式化

FT.AGGREGATE
is the declarative result-shaping command. Build a pipeline of stages.
undefined
FT.AGGREGATE
是声明式结果格式化命令。构建多阶段管道。
undefined

Top 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
    COSINE
    for normalized text models).
  • 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_v2

App 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格式;后续会跟踪覆盖情况。

References

参考资料