gpt4 book ai didi

node.js - 在 redis 中搜索 JSON 值

转载 作者:IT王子 更新时间:2023-10-29 06:08:51 26 4
gpt4 key购买 nike

我正在开发一个使用 redis 作为数据库的 nodeJS 服务器,我需要检索所有具有特定 service_id 值的 redis 键。例如,如果服务 ID 为 4,我需要检索 service_id = 4 的所有键。我在 redis 中有以下结构,其中值为 JSON:


关键:“{service_id:数字}”

是否可以过滤具有特定服务 ID 的键?也许有一些解决方法可以实现?

最佳答案

尽管 Redis 是一种键值存储,但您可以通过多种方式对其进行调整以使其受益。例如,您可以使用 hashes并像这样存储您的值:

HSET services service:1 foo
HSET services service:2 bar
HSET services service:3 buz

所以语法是 HSET hashname fieldname value 作为一个字段,您用冒号分隔 ID。

如果每个键有超过 1 个值,您可以执行以下操作:

HSET services service:1:name foo
HSET services service:1:id 1
HSET services service:2:name bar
HSET services service:2:id 2

因此,通过用另一个冒号分隔键,您可以存储更多值。然后如果你想从服务 1 中检索所有内容,你可以执行 SCAN使用通配符,像这样:

HSCAN services 0 match service:1:*

哎呀,您甚至可以将每个服务存储为单独的散列:

HSET services:1 id 1
HSET services:1 name foo
HSET services:2 id 2
HSET services:2 name buz

或者用 HMSET 让它更短

HMSET services:1 id 1 name foo
HMSET services:2 id 2 name buz

总而言之 - Redis 很棒!

关于node.js - 在 redis 中搜索 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52001620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com