Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store array in Redis hashes?

Tags:

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"} 

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

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

And for xyz:

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

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

like image 338
Vor Avatar asked Nov 05 '13 14:11

Vor


People also ask

Can you store array in Redis?

We use various data structures (linked lists, arrays, hashes, etc) in our applications. They are usually implemented in memory but sometimes we need persistence AND speed. This is where in memory DB like Redis can be very useful.

Which stores Redis hash?

A Redis Hash can store up to 4 billion key value pairs. If the value is Integer, Redis hash allows you to atomically increment or decrement the value. It is a highly performant data structure and supports adding a key, removing a key, and checking membership of key in constant time or O(1).

Can Redis store numbers?

Redis stores integers in their integer representation, so for string values that actually hold an integer, there is no overhead for storing the string representation of the integer.

Can Redis store objects?

Object Storing Procedure. In the Redis, Everything can be stored as only key-value pair format. Key must be unique and storing an object in a string format is not a good practice anyway. Objects are usually stored in a binary array format in the databases.


1 Answers

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

like image 61
FGRibreau Avatar answered Sep 30 '22 16:09

FGRibreau