redis Python中的字典列表

g6baxovj  于 8个月前  发布在  Redis
关注(0)|答案(1)|浏览(123)

我目前将我的Python Web应用程序的引用-未引用“数据库”保存在JSON文件中,但我需要迁移到Redis上。如何在Python-Redis中创建以下数据结构?

[
    {
        "username": "guest1",
        "password": "foo",
        "enabled": true,
        "__comment__": "Alice"
    },
    {
        "username": "guest2",
        "password": "bar",
        "enabled": false,
        "__comment__": "Bob"
    },
    {
        "username": "guest3",
        "password": "baz",
        "enabled": false,
        "__comment__": "Charlie"
    }
]

我想使用哈希Map或存储JSON,但我不知道如何做到这一点。

0mkxixxg

0mkxixxg1#

看看RediSearchRedisJSON
您可以存储JSON对象并对JSON对象执行JSON操作。如果你的对象很简单,就像例子中一样,你也可以使用HASHes来存储简单的字典对象。
如果您需要在数据库上执行搜索,RediSearch具有此功能。它可以处理哈希和JSON键。
redis-py客户机也提供了我提到的所有功能,因此迁移数据应该不会太复杂

使用redis-py:

from redis import Redis
from redis.commands.json.path import Path

conn = Redis(host="localhost", port=6379, db=0)

Keys = [
    {
        "username": "guest1",
        "password": "foo",
        "enabled": true,
        "__comment__": "Alice"
    },
    {
        "username": "guest2",
        "password": "bar",
        "enabled": false,
        "__comment__": "Bob"
    },
    {
        "username": "guest3",
        "password": "baz",
        "enabled": false,
        "__comment__": "Charlie"
    }
]

# using JSON
for id, mapping in enumerate(keys):
    conn.json().set(f"json:{id}", Path.root_path(), mapping)

# using HASH
for id, mapping in enumerate(keys):
    conn.hset(f"hash:{id}", mapping=mapping)

# Getting the objects back

j = conn.json().get("json:1")
h = conn.hgetall("hash:1")

相关问题