以redis格式存储和检索数据

时间:2015-05-27 15:17:59

标签: redis

如何在redis中存储以下结构并获取特定输出:

projects is the main category.
projects has categories each category has a list of data.

projects:catega contains: id: 1 values {id: 123, name: 'bla'}
                          id: 2 values {id: 124, name: 'bla1'}
projects:categb contains: id: 1 values {id: 125, name: 'bla2'}
                          id: 2 values {id: 126, name: 'bla4'}

我希望能够通过选择项目所有类别及其数据来获得所有这些:

{catega: [{id...}, {id...}], categb: [{id...}, {id...}]}

1 个答案:

答案 0 :(得分:2)

Redis可以存储哈希键而不是复杂对象,但是,您可以使用下面的

来解决这个问题

1-重构您的对象更简单,例如

而不是

project1:
{
catega: 
    [{id: 123, name: 'bla'}, {id: 124, name: 'bla1'}], 
    [{id: 123, name: 'bla'}, {id: 124, name: 'bla1'}]
categb: 
    [{id: 123, name: 'bla'}, {id: 124, name: 'bla1'}], 
    [{id: 123, name: 'bla'}, {id: 124, name: 'bla1'}]
}

project1:
{
categaID123: '{name:bla, age:15, salary:20}',
categaID124: '{name:blo, age:12, salary:21}',

categbID123: '{name:bla, age:15, salary:20}',
categbID124: '{name:bla, age:15, salary:20}',

}

2-您可以按如下方式设置哈希

hset project2 categorybID123 "{name:bla, age:15, salary:20}"

或者您可以一次性设置所有按键,但使用HMSET

3-您可以在一次通话中检索数据

hget project2 categorybID123

希望这有帮助