在 Redis 中聚合时如何使用 APPLY format() 加载 JSON 值?

问题描述 投票:0回答:1

我正在尝试使用 RedisJson 在 Redis 上运行

FT.AGGREGATE
命令的
APPLY format(...)
子表达式,但尝试使用 JsonPath 作为格式参数会给我带来
Unknown symbol
错误。

我有几个格式为

{"shape": "circle", "color": "blue", "material": "metal"}
的 JSON 类型键,我想要一个索引来返回每个形状的颜色和材质组合,即对于圆形,给出
["blue metal", "red wood"]

我使用

FT.SEARCH shapeSearch ON JSON SCHEMA $.shape as shape TAG SORTABLE
创建搜索索引,效果很好。然后我尝试用
FT.AGGREGATE shapeSearch "@shape:{circle}" LOAD 2 $.color $.material APPLY "format(\"%s %s\", @$.color, @$.material)" AS colorAndMaterial GROUPBY 1 @shape REDUCE TOLIST 1 @colorAndMaterial
进行聚合。聚合命令失败,显示
Unknown symbol 'color'

我认为问题是由

@$.color
中的点引起的,Redis 将其视为特殊字符,并且无法将完整的 JsonPath 识别为参数。尝试像
@$\.color
那样转义它是行不通的,将其放入
\"@$.color\"
@\"$.color\"
等字符串中只是将路径放入格式化字符串中,而不是值中。

这怎么办?

database indexing redis aggregate full-text-search
1个回答
0
投票

我必须为这个挖掘一点。总是喜欢这样的好问题。也帮助我变得更聪明!

因此,要使其工作,您需要在 LOAD 语句中提供 AS 别名。这不会将其放入索引中,但会为搜索提供一个可以引用的名称。

这在文档中非常简短地提到过,我自己也差点错过了。这里最重要的一点是:

APPLY 步骤必须具有由 AS 参数确定的显式别名。

因此,将您的呼叫替换为 FT.AGGREGATE 以下内容,您应该像 Flynn 一样:

redis.cloud> FT.AGGREGATE shapeSearch "@shape:{circle}" LOAD 6 $.color AS color $.material AS material APPLY "format(\"%s %s\", @color, @material)" AS colorAndMaterial
1) (integer) 1
2) 1) "color"
   2) "blue"
   3) "material"
   4) "metal"
   5) "colorAndMaterial"
   6) "blue metal"

顺便说一句,支持 RediSearch 的一些可靠使用。很高兴看到它得到很好的利用!

当然,我希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.