I want to store shopping cart data in Redis.
I have this kind of data:
{ user_X (unique)
product_id1, product_name1, product_price1
product_id2, product_name2, product_price2
... } example of a shopping cart
{ user_Y (unique)
product_id1, product_name1, product_price1
product_id2, product_name2, product_price2
... } example of another shopping cart
Which data type should I use?
Your data appears to fit in nicely into the Hash data type. Use key names made up of the user's ID (the Redis convention is to separate elements in the key name using the colon, ':', character). The field names in each cart Hash should be the product ids.
Since Redis' Hashes (and all other data types for that matter) do not support nesting, the only possible data type for a Hash's field value is a String. The easiest to store your product's name and price in a String is simply to concatenate the two and use a delimiter for separation. The example above would therefore be stored in Redis similar to the below:
To get a user's cart, do an
HGETALL
on the key or useHSCAN
if you have really big carts.