Todd Michaud
Todd Michaud

Reputation: 11

Redis Key Structure

When creating a key in Redis, I get using the ":" format and treating it similar to a URL structure.

But what if that structure itself contains key-value type combinations? Does one put the key in the structure?

Made-up Example:

Option A) "country:usa:manufacturer:ford:vehicle:f150:color" = black

or

Option B) "usa:ford:f150:color" = black

In some ways, I think that there is strength in the structure of Option A, but it also adds a lot of complexity to the key.

Thoughts?

Upvotes: 1

Views: 2645

Answers (1)

The Real Bill
The Real Bill

Reputation: 15773

While keeping in mind your made-up example (do try to use an actual example, you'll get better answers) I would have to say neither.

I would go with an ID for the key, likely an int. then I'd put each key/value pair in your option A as a hash member and value.

For example:

HSET 1 country USA

HSET 1 manufacturer ford

And so on. Or you could use an hmset operation to set them all at once.

Why? You get the benefit of keeping the fields as describing the data (which you lose in your option b), the memory advantages of hashes over strings, and reduced complexity on key structure, not to mention the memory benefits of a short integer as keyname versus a long string.

Further, you have a memory cheap way to create indexes as integer sets. for example a key called "country:1" could be a set of entry IDs which then give you a way to "pull all entries for country ID 1" - USA in the example. By using integers you get the benefit of being able to store these all in a very memory efficient way, at the minor cost of a lookup table. This could even be done in lua to avoid a network hop.

The greater the range of possible combinations and entries, the more valuable the memory savings are. If you've got millions or billions of them, you'll want to follow the integer-ID & lookup route. This would also set you up nicely if you ever need to shard data - either server side or client side.

Upvotes: 2

Related Questions