Chris Maness
Chris Maness

Reputation: 1688

Redis finding hashes by field values

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?

Upvotes: 12

Views: 16815

Answers (2)

taubhi
taubhi

Reputation: 135

For next readers, the SORT command would probably help using the "BY pattern" argument

HMSET myhash field1 Hello field2 World
SORT myhash BY World

Patterns examples (w3resource)

Upvotes: -2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

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.

Upvotes: 27

Related Questions