I have been trying to figure out how I can set key and value to a specific column. By column I mean something like:
"fruit": {
"american" {
"key": "value",
"key2": "value2"
},
"europe" {
"key": "value"
"key2": "value2"
}
},
"books": {
"american_author" {
"key": "value"
"key2": "value2"
},
"asia_author" {
"key": "value"
"key2": "value2"
}
},
"paint": {
"africa" {
"key": "value"
"key2": "value2"
},
"south_america" {
"key": "value"
"key2": "value2"
}
}
What im trying to achieve here is that I would like to be able to add a new "column" which is fruit, book and paint and inside those values I would like to add another "column" and inside each column I want to add keys and values. As you can see in the snippet above.
For now I have done something like this:
import serialized_redis
r = serialized_redis.JSONSerializedRedis(host='localhost', port=6379, db=0)
r.set('fruit', 'american', {'key': 'value' })
but what returns:
raise DataError("Invalid input of type: '%s'. Convert to a "
redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.
My question is, am I able to do it using Redis and if so, how can I be able to add the keys and values to a specific "column" as given at the top of the thread?
2
Answers
You can encode the nested JSON part as a string as use Redis Hash
For example, ‘fruit’, ‘books’, ‘paint’ , etc can be a redis hash, ‘american’, ‘europe’, etc can be the key of the hash and ‘key’, ‘key2’ can be stored as value of the key as JSON string. Like the following:
If at this point you check redis:
Further code logic to add new fields:
Final output in redis:
You can accomplish this by using the Hash data type with HSET
https://redis-py.readthedocs.io/en/stable/#redis.Redis.hset