memcache - 搜索包含多个标识符的密钥名称

时间:2013-08-26 21:33:29

标签: php python memcached amazon-elasticache

我是memcache的新手(通过Amazon ElastiCache),并且我使用它来存储数据以从数据库卸载一些工作。

目前我存储2个相同的值,其中键是不同的查找键。

例如:

// each key represents the user email address with the value a json dump of the user record
'email@email.com': {
    id: 1,
    name: 'John Doe',
    email: 'email@email.com'
}

// each key represents the user id with the value a json dump of the user record
1: {
    id: 1,
    name: 'John Doe',
    email: 'email@email.com'
}

是否可以将id / email存储在一个密钥中,从而无需在内存中存储2个单独的记录?

Python或PHP中的任何示例都会非常有用!

1 个答案:

答案 0 :(得分:0)

这是我的数据结构....不要判断,使用风险自负:P

class KeyedDictionaryReturn(object):
    def __init__(self, a, r):
        self.exact = a
        self.all = r
    def __str__(self):
        if self.exact: return str(self.exact)

class KeyedDictionary(dict):
    def __init__(self, *args, **kwargs):
        super(KeyedDictionary, self).__init__(*args, **kwargs)

    def __getitem__(self, key):
        _ret, _abs = [], None
        for keys, values in self.items():
            if isinstance(keys, tuple) and key in keys:
                _ret.append(dict.__getitem__(self, keys))
            elif isinstance(key, type(keys)) and key == keys:
                _abs = dict.__getitem__(self, key)
                _ret.append(_abs)
        if len(_ret) == 0:
            return None
        if len(_ret) == 1:
            return _ret[0]
        return KeyedDictionaryReturn(_abs, _ret)

简单用法:

>>> k = KeyedDictionary()
>>> k.update({(1, 'one'):1})
>>> print(k)
>>> print(k[1])
>>> print(k['one'])
{(1, 'one'): 1}
1
1
>>> k.update({2:2})
>>> k.update({(2, 'two'):3})
>>> print(k)
>>> print(k[2])
>>> print(k[2].exact)
>>> print(k[2].all)
{(1, 'one'): 1, 2: 2, (2, 'two'): 3}
2
2
[2, 3]

...我不知道这是不是你想要的,或者如果没有黑客攻击,它会在memcache中运行。