How to use redis to store hierarchical data?

如何使用redis存储层次数据?

问题 (Question)

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 )

我有一套分层数据存储,层次结构是这样的网站/建筑/地板,数据,例如

{ 
   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}]
                        ]
              }
          ] 
}

我想把这些房间数据为一组,但我也可以通过选择网站名称或查询的一个子集的房间(网站名称+建筑名称)或(网站名称+名称+建筑楼)

最佳答案 (Best Answer)

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 buildings id for a given site.

Then defines 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.
  • avoids too long keys if you intend too store a very high number of them (longer keys require more memory)

在使用你不会把你的数据储存在一个独特的数据结构。你必须创建多个数据结构,每一个的一个关键的发现。

使用常规的名字你的钥匙:例如site:<CITY>:buildings将一组包含了对于一个给定的现场建筑物ID列表。

然后定义了散列存储每个建筑描述。关键这些哈希的样子:building:<ID>

你有2个成员的散列:名称和地板。地板值的设定包含地板标识符列表的唯一ID。

然后创建每一层楼的一套房间的名称,存储。本集的名称可以像:floor:<ID>

小贴士

  • 使用redis增加命令生成唯一的ID。
  • 如果你想避免太长密钥的商店一个非常高的数字,他们(更长的密钥需要更多的内存)

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/22150219