You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RedisSearch中索引channels:*:users:*格式的键

解决RedisSearch索引特定嵌套前缀键的问题

问题根源

RedisSearch的prefix参数是前缀精确匹配,不是通配符模式匹配——你写prefix=["channels:*:users:*"]时,*会被当成普通字符,只会匹配以channels:*:users:*字面开头的键,完全不符合需求。而用prefix=["channels:"]会把所有以channels:开头的键都纳入索引,包括你不需要的一级键。

可行解决办法

利用RedisSearch的filter过滤功能(需RedisSearch 2.4+版本支持),结合键名字段索引,精准筛选目标键:

  1. 修改索引Schema:新增一个字段用来索引Redis键本身(用__key__内置变量)
  2. 保留基础前缀:用prefix=["channels:"]选中所有相关范围的键
  3. 添加过滤条件:通过键名过滤出包含:users:的目标键

修改后的代码如下:

async def create_index(self):
    schema = (
        NumericField("$.channel_id", as_name="channel_id"),
        NumericField("$.events[*].event_id", as_name="event_id"),
        NumericField("$.events[*].timestamp", as_name="timestamp"),
        TagField("__key__", as_name="key_name")  # 新增:索引键名本身
    )
    await self.connection.ft("idx:events").create_index(
        schema,
        definition=IndexDefinition(
            prefix=["channels:"],
            index_type=IndexType.JSON,
            filter="key_name LIKE '%:users:%'"  # 过滤出键名包含`:users:`的键
        )
    )

补充说明

  • __key__是RedisSearch的内置变量,用来引用Redis键的名称,将其作为字段索引后,就能基于键名做过滤。
  • LIKE '%:users:%'中的%是通配符,匹配任意字符序列,确保只有键名中包含:users:的条目会被索引。
  • 若你的RedisSearch版本低于2.4,需要先升级到对应版本才能使用filter参数。

内容的提问来源于stack exchange,提问作者Раенко Тимофей

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 08:52:29