5

A CMS I use implements memcached by default and I'm working to expand it. One key contains an array of user information, like userstats_id and contains information like forum post counts, number of posts they've liked blah blah. The key looks like this:

[userstats_1] => Array
        (
            [forum_posts] => 178
            [forum_likes] => 16
            [forum_dislikes] => 0
            [now_online] => 1
        )

I'm expanding the usage of this key because I also want to store which specific forums the user is browsing, e.g.:

[userstats_forumbrowsing_1] => Array
    (
        [forum_browsing] => 'Foobar'
    )

It would be better if I could have this within [userstats_1] as of course that makes more sense. So given also that this changes a lot more frequently than the rest of the elements of that cached array, what's the best way to get and set the elements of the cached array?

The only way I have come up with is to copy the array, manipulate it then re-set it in the cache, but that seems crazy. Thanks!

1 Answer 1

6

No, unfortunately because memcached is a simple key-value store you cannot modify or access just part of a value addressed by a single key.

So you have two choices:

  1. Do the "crazy" thing you mention: use a single key to store the array, get the entire array, modify one element, and then set the entire array.
  2. Use a separate key for each part, and get and set them separately.

Which is better depend on the relative sizes of the parts, their pattern of usage, and how important it is to maintain consistency.

Or another choice is to not use memcached, and instead use Redis, which extends the simple key-value model to include data types, including hashes that support the kind of updates you want.

Sign up to request clarification or add additional context in comments.

2 Comments

Redis hashes, you meant, I guess (redis.io/commands#hash) Looks like they do exactly what's required - they are basically associative arrays in Redis.
Thank you Catherine for pointing out my error. I updated the answer as you suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.