How to get the number of values ​​in a redis hash?

I got a redis hash like

key field value 1000 state "ca" 1000 zip "95054" 2000 state "ca" 2000 zip "95050" 3000 state "ny" 3000 zip "12345" 

how can I answer questions such as the number of states "CA". I need to do a value count for a field. Is it possible? help would be appreciated.

-AVI

+6
source share
3 answers

I think you need to keep a separate counter for unique values. You can get the length of one hash, but not when you get three different keys in this case.

Command Line Field Value

HSET 1000 state "ca"

HSET 1000 zip "95054"

INCR ca

HSET 2000 state "ca"

HSET 2000 zip "95050"

INCR ca

HSET 3000 "ny" Status

HSET 3000 zip "12345"

INCR ny

If you want to get how many hash keys with the state "ca" use:

Get ca

+5
source

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:

+1
source

Assuming you are responsible for inserting values ​​into a hash, use MULTI / EXEC to wrap the hash inserts and the corresponding INCRS. So take the ptzOn approach, but remember to wrap it in MULTI / EXEC to have atomic semantics. Do the same when deleting the hash and use DECR.

0
source

Source: https://habr.com/ru/post/886925/


All Articles