Shopping carts in Redis

5.3k views Asked by At

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?

2

There are 2 answers

3
Itamar Haber On BEST ANSWER

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:

HSET cart:X id1 "name1:price1"
HSET cart:X id2 "name2:price2"

HMSET cart:Y id1 "name1:price1" id2 "name2:price2"

To get a user's cart, do an HGETALL on the key or use HSCAN if you have really big carts.

0
ajeetraina On

This tutorial will show you how to harness the power of Redis by creating a basic eCommerce shopping cart application with Node.js. Usually, the shopping cart data is stored on the client-side as a cookie. Cookies are small text files stored in a web user's browser directory or data folder. The advantage of doing this is that you wouldn't need to store such temporary data in your database. However, this will require you to send the cookies with every web request, which can slow down the request in case of large cookies.

You might find this interesting: https://developer.redislabs.com/howtos/shoppingcart/