How to store array in Redis hashes?

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

Sample Data

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

Do this (using a redis set):

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

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

SISMEMBER abc:name Bob
> true

To retrieve all values of a field use SMEMBERS:

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

Note:

  • 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"]

    then you should use a list instead

Leave a Comment