I am going to assume that the above data is a list of cities. In fact, you might think of storing them as ...
key value city:1000:state "ca" city:1000:zip "95054" city:2000:state "ca" city:2000:zip "95050"
Now back to your question ... In SQL, you can do something like: SELECT Count (*) FROM city WHERE state = 'CA'. Or maybe if you want a count for each state ... SELECT state, COUNT (*) FROM city GROUP BY state.
In my opinion, this is what Redis is struggling with a bit, but it gives you the opportunity to rethink your database design. If you plan to execute such a request multiple times, consider creating a new Sorted State Set. The account will be your account in this case. Use ZINCRBY in this set (call it city_count_by_state) when you add / remove records to / from your table "Table". Your query now looks something like this: ZRANK city_count_by_state 'CA'. Adding / removing / getting a rank in a sorted set is done in O (log (n)) time.
If you do not want a temporary memory with a sorted set, you can use KEYS to return a large list of all your keys in the "city" table. Then, your program can automatically iterate over these keys and count how many cities have a "CA" state. This is a bit of manual work, but it will still work in O (n) time.
If you already have city data pre-populated in your database, you can generate your sorted set using KEYS (see the method described above). Hope this helps!
Cm:
source share