Tundebabzy
Tundebabzy

Reputation: 879

Explanation of small Redis snippet

I'm referring to this great answer given by @Sripathi Krishnan to the question asked here on SO: Is Redis just a cache

I'm trying to learn how to use redis and my research brought me to the question on SO.

Can someone please explain the reason for these two lines in the code because I'm still finding it difficult to understand their usefulness in the code Sripathi gave in the answer.

$ HINCRBY unique_ids question 1
$ HINCRBY unique_ids answer 1  

I know that it creates a hash with 'unique_ids' as its key with fields 'question' and 'answer' first initialised to 0 then increased to 1. Apart from this, I don't see any link of the unique_ids key with the flow but I'm not sure if my noob mind is missing something.

Upvotes: 3

Views: 219

Answers (1)

Didier Spezia
Didier Spezia

Reputation: 73246

These commands are just a way to generate synthetic primary keys.

In Sri's example, people can add questions and answers in the system. These entities need to be referenced, so they need to be identified by unique keys. You may imagine using some kind of UUID mechanism for this, but using numeric keys is generally simpler.

The unique_ids is just a convenient container to store the next available keys of the objects stored in your system. To add new question, just increment the question field of unique_ids (atomic operation with Redis) and use the returned value as the key of the new question. It guarantees all the new questions will have a different key value.

In relational data stores, such feature is provided by sequences (Oracle, PostgreSQL) or autoincrement primary keys (MySQL).

Upvotes: 2

Related Questions