PythonNewbie
PythonNewbie

Reputation: 1163

How to add multiple values into one key using Redis

I have been trying to figure out how to get multiple values into a key for example:

{
    "fruit": {
        "tomato": {
            "Color": "red",
            "Price": "100"
        },
        "banana": {
            "Color": "yellow",
            "Price": "150"
        }
    }
}

For now my currently code is:

r = serialized_redis.MsgpackSerializedRedis(host='localhost', port=6379, db=0)
r.set("fruit", {"tomato": {"Color": "red", "Price": "100"}})
r.set("fruit", {"banana": {"Color": "yellow", "Price": "150"}})

The problem is that everytime that I do a r.set it seems that it replaces so meaning that when I run this code it will just be set of:

{
    "fruit": {
        "banana": {
            "Color": "yellow",
            "Price": "150"
        }
    }
}

so even if I do a r.set of "tomato" it will be replaced by "banana" since its the latest one that is being SET.

My question is, how can I add it to the same Key but with different values so that everything is in the same key but it has different "furits"?

{
    "fruit": {
        "tomato": {
            "Color": "red",
            "Price": "100"
        },
        "banana": {
            "Color": "yellow",
            "Price": "150"
        }
    }
}

Upvotes: 3

Views: 14878

Answers (1)

Tuan Anh Tran
Tuan Anh Tran

Reputation: 7237

you can use hash for that

hmset fruit tomato your_json_serialized_here
hmset fruit orange ...

you can do hmset with multiple fruit too like this hmset fruit apple 1 banana 2 orange 3

accessing data from hash with hmget is like this hmget fruit orange banana apple

Upvotes: 2

Related Questions