Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use redis to store hierarchical data?

I have a set of hierarchical data to store, the hierarchy is like site/building/floor, the data, for example

{ 
   site:'New York',
   buildings: [
              {
                name:'building a',
                floors: [
                       'Ground':[{room:room1},{room:room2}],
                       'First':[{room:room1},{room:room2}]
                        ]
              }
          ] 
},
{ 
   site:'London',
   buildings: [
              {
                name:'building a',
                floors: [
                       'Ground':[{room:room1},{room:room2}],
                       'First':[{room:room1},{room:room2}]
                        ]
              }
          ] 
}

I want to store these room data into a set, but I can also query the a subset of rooms by selecting the site name or (site name + building name ) or ( site name + building name + floor )

like image 476
user824624 Avatar asked Mar 03 '14 15:03

user824624


People also ask

How does Redis store hierarchical data?

In Redis you won't store your data in a unique data structure. You have to create multiple data structure, each one being identified by a key. Use a convention to name yours keys: for example site:<CITY>:buildings will be a set that contains the list of building ids for a given site.

Can Redis handle large data?

Redis can handle up to 2^32 keys, and was tested in practice to handle at least 250 million keys per instance. Every hash, list, set, and sorted set, can hold 2^32 elements. In other words your limit is likely the available memory in your system.

How does Redis store data?

Since Redis is an in-memory database, data is stored in memory (or RAM). If a server crashes, all the data stored is lost. Redis has back-up mechanisms in place for the data on the disk. This way, the data is loaded from the disk to the memory when the server reboots.


1 Answers

In Redis you won't store your data in a unique data structure. You have to create multiple data structure, each one being identified by a key.

Use a convention to name yours keys: by example site:<CITY>:buildings will be a set that contains the list of building ids for a given site.

Then define hashes to store each building description. The key for these hashes could be something like: building:<ID>

In the hash you have 2 members: name and floors. Floors value is the unique id of the set containing the list of floor identifiers.

Then create a last set for each floor, to store the room names. The name of the sets could be something like: floor:<ID>.

Tips:

  • use redis INCR command to generate unique IDs.
  • avoid too long keys if you intend to store a very high number of them (longer keys require more memory)
like image 105
Pascal Le Merrer Avatar answered Oct 29 '22 23:10

Pascal Le Merrer