Redis finding hashes by field values

12,999

There are no indexes in redis, and it doesn't implement SQL. It's a key-value store. You provide a key, it gets you a value.

That said, you can implement this by maintaining secondary indexes yourself. For example:

create a record and an index entry

HMSET myhash field1 Hello field2 World
SADD field2_world myhash

update a record, delete old index entry, create new one

SREM field2_world myhash
HMSET myhash field2 Mundo
SADD field2_mundo myhash

find all records which have "World" in field2

SMEMBERS field2_world

I hope you get the idea.

Share:
12,999
Chris Maness
Author by

Chris Maness

There isn't anything that I can't figure out how to do with a little help.

Updated on June 09, 2022

Comments

  • Chris Maness
    Chris Maness about 2 years

    When using Redis in order to create a "record" you can create a hash with several fields. For example:

    HMSET myhash field1 "Hello" field2 "World"
    HMSET myhash2 field1 "Goodbye" field2 "World"
    

    You can retrieve this by knowing the key values, however what I want to know is there any way to retrieve all hashes that have "World" in field2?

  • SHM
    SHM almost 8 years
    i executed the exact commands in the answer with 2 hashes and it did not work. may you explain a bit more?
  • Sergio Tulentsev
    Sergio Tulentsev almost 8 years
    @SHM: How it didn't work? Show your entire command history for that session. With outputs.
  • Ade
    Ade about 2 years
    Doesn't work on Redis 7.0.0, failing with error (error) WRONGTYPE Operation against a key holding the wrong kind of value