skip to Main Content

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

2

Answers


  1. You have to build some form of secondary index to accomplish this efficently.

    Use a Set

    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
    

    With Redis Stack

    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
    
    Login or Signup to reply.
  2. 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.

    1. If you want all informations, you can have a set key holding it like :
    SADD BMW myhash1 
    //use SCARD to know how many BMW there are
    SCARD BWM
    
    1. If you only want to know the number of BMWs you can have a simple key holding a number like :
    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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search