Reputation: 12847
Assume I have multiple hash lists as below:
HMSET myhash1 type Car company BMW
HMSET myhash2 type Car company Benz
HMSET myhash3 type Car company BMW
HMSET myhash4 type Car company Honda
HMSET myhash5 type Car company BMW
HMSET myhash6 type Car company Toyota
HMSET myhash7 type Car company Benz
I want to count how many hash list I have with company = BMW
which is 3
Upvotes: 0
Views: 41
Reputation: 1843
The thing with non-relational databases is that you have to make relations by hand if needed. So here you are "obliged" to have another key holding this information.
SADD BMW myhash1
//use SCARD to know how many BMW there are
SCARD BWM
INCR BMW //autoset to 0 before applying INCR, holds 1 after this command
//use GET to have the number of BMWs
GET BWM //returns 1
//if you want to delete a hash you can use INCRBY to update the number
INCRBY BMW -1
Upvotes: 0
Reputation: 1149
You have to build some form of secondary index to accomplish this efficently.
You can use a set, and create a set for each company, and add each key to it.
SADD myhash:Company:BMW myhash1 myhash3 myhash5
SADD myhash:Company:Benz myhash2 myhash7
SADD myhash:Company:Honda myhash4
SADD myhash:Company:Toyota myhash6
Then when you want to query it, you would just use SCARD, so if you wanted to know how many BMWs there were you'd just run
SCARD myhash:Company:BMW
Redis Stack has native secondary indexing capabilities which you can leverage here this is much easier to maintain (and can actually work across shards in a scaled out environment if need be). You'd just need to create the secondary index
FT.CREATE hashes PREFIX 1 myhash SCHEMA company tag
Then you'd just need to query them (if you don't care to get the actual cars matching your query back just pass in LIMIT 0 0
FT.SEARCH hashes "@company:{BMW}" LIMIT 0 0
Upvotes: 2