Ranieri Mazili
Ranieri Mazili

Reputation: 833

Organizing data on Redis

I'm starting with Redis and I'm having difficult to understand how to organize data on it. I would like to store the states of Brazil on Redis. PS: Brazil has 27 states, I'm using a lower number on this example.

My data is divided into sigla (prefix), nome (state name) and região (region).

Sigla | Nome | Região
AC | Acre | Norte
AL | Alagoas | Nordeste
AP | Amapá | Norte
AM | Amazonas | Norte
MT | Mato Grosso | Centro Oeste
SC | Santa Catarina | Sul
SP | São Paulo | Suldeste

How to save it on Redis in a way that I could do the following searches: All States All States of a specific region All States where name starts with "A"

I've tried to use HMSET but haven't found a way to save the data in a way that I could retrieve it filtered.

Should I save all data on a unique key (states) in json format and filter the result directly on backend service instead of filter direcly on Redis?

Upvotes: 3

Views: 1297

Answers (1)

Itamar Haber
Itamar Haber

Reputation: 49932

In Redis, you store the data according to how you're going to read it. This sometimes means having the same data in different data structures.

  • All states: this can be addressed by keeping a Hash where each field is a state and calling HGETALL for example. Alternatively, use a Set.
  • All states in a region: A Hash or a Set per region is usually the solution, e.g. SADD region:Norte AC AP AM and then calling SMEMBERS region:Norte.
  • All states where name starts with "A": use a Sorted Set as a lexicographical index - see https://redis.io/topics/indexes#lexicographical-indexes for the details.

Upvotes: 3

Related Questions