如何在Redis哈希中存储数组? [英] How to store array in Redis hashes?

查看:139
本文介绍了如何在Redis哈希中存储数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Redis 很陌生,想看看它是否可行.想象一下,我正在接收这样的数据:

I'm very new to Redis, and looking to see if its possible to do. Imagine I'm receiving data like this:

{ "account": "abc", "name": "Bob", "lname": "Smith" }
{ "account": "abc", "name": "Sam", "lname": "Wilson" }
{ "account": "abc", "name": "Joe"}

并为另一个帐户接收此数据:

And receiving this data for another account:

{ "account": "xyz", "name": "Bob", "lname": "Smith" } 
{ "account": "xyz", "name": "Sam", "lname": "Smith"}

我想将这些数据以类似的格式保存在 Redis 中:

I would like to keep this data in Redis in similar format:

abc:name ["Bob", "Sam", "Joe"]
abc:lname ["Smith", "Wilson", Null]

对于 xyz:

xyz:name["Bob", "Sam"]
xyz:lname["Smith", "Smith"]

那么问题是我应该使用什么数据类型来存储这个 Redis?

So the question is what data types should I use to store this Redis?

推荐答案

如果您的目标是检查 Bob 是否用作帐户 nameabc 解决方案应该是这样的:

If your goal is to check if Bob is used as a name for the account abc the solution should be something like:

示例数据

{ "account": "abc", "name": "Bob", "lname": "Smith" }
{ "account": "abc", "name": "Sam", "lname": "Wilson" }
{ "account": "abc", "name": "Joe"}

执行此操作(使用 redis 集):

Do this (using a redis set):

SADD abc:name Bob Sam Joe
SADD abc:lname Wilson Smith

然后,您将能够检查 Bob 是否用作帐户 abcname,使用:

You'll then be able to check if Bob is used as a name for the account abc, with:

SISMEMBER abc:name Bob
> true

要检索字段的所有值,请使用 SMEMBERS:

To retrieve all values of a field use SMEMBERS:

SMEMBERS abc:name
> ["Bob", "Sam", "Joe"]

注意:

  • 此处的密钥名称采用 [account]:[field] 格式.其中[account]可以是abcxyz等,field可以是name, lname ...
  • 如果您不想要唯一值,例如:

  • The key name here is under the [account]:[field] format. Where [account] can be abc, xyz and so on and field can be name, lname ...
  • If you don't want unique value, for instance:

abc:name ["Bob", "Sam", "Joe", "Bob", "Joe"]

那么你应该使用列表代替

这篇关于如何在Redis哈希中存储数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆