问题
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