How to use redis to store hierarchical data?

江枫思渺然 提交于 2019-12-05 16:34:28

问题


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 )


回答1:


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)


来源:https://stackoverflow.com/questions/22150219/how-to-use-redis-to-store-hierarchical-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!