Redis セカンダリインデックス
ebiken.iconRedisでセカンダリインデックスを実現する方法が公式で紹介されていたのでまとめておく Summary
Sorted sets to create secondary indexes by ID or other numerical fields.
Sorted sets with lexicographical ranges for creating more advanced secondary indexes, composite indexes and graph traversal indexes.
Sets for creating random indexes.
Lists for creating simple iterable indexes and last N items indexes.
Simple numerical indexes with sorted sets
add ZADD
retrieve all elements by scores range
ZRANGEBYSCORE / ZREVRANGEBYSCORE
by using WITHSCORES option to obtain the scores
retrieve number of elements ZCOUNT
hash map for using objects ids as associated values
HMSET
multi dimensional data
Redis geo indexing API (Geo hash)
score limits
-/+ 2^53
example
Ranking
Lexicographical indexes
Lexicographical order
alphabetical order (not numeric. e.g. 1, 10, 2,..)
elements are added with the same score, they are sorted lexicographically
ZRANGEBYLEX, ZLEXCOUNT
example
Completion
e.g. get words starts with "bit" ZRANGEBYLEX myindex "[bit" "[bit\xff"
add frequency like ZADD myindex 0 banana:1
increment
code:_
ZREM myindex 0 banana:1
ZADD myindex 0 banana:2
normalization
ZADD myindex 0 banana:273:Banana
Composite indexes
e.g. room:price:product_id
code:_
ZADD myindex 0 0056:0028.44:90
ZADD myindex 0 0034:0011.00:832
get by room and price ZRANGEBYLEX myindex [0056:0010.00 [0056:0030.00
Representing and querying graphs using an hexastore
hexastore
relations betwen subject, predicate and object
e.g.
code:_
ZADD myindex 0 sop:antirez:matteocollina:is-friend-of
ZADD myindex 0 ops:matteocollina:is-friend-of:antirez
ZADD myindex 0 osp:matteocollina:antirez:is-friend-of
ZADD myindex 0 pso:is-friend-of:antirez:matteocollina
ZADD myindex 0 pos:is-friend-of:matteocollina:antirez
get friends of antirez
code:_
ZRANGEBYLEX myindex "[spo:antirez:is-friend-of:" "[spo:antirez:is-friend-of:\xff"
1) "spo:antirez:is-friend-of:matteocollina"
2) "spo:antirez:is-friend-of:wonderwoman"
3) "spo:antirez:is-friend-of:spiderman"
get relationships between antirez and matteocollina
code:_
ZRANGEBYLEX myindex "[sop:antirez:matteocollina:" "[sop:antirez:matteocollina:\xff"
1) "sop:antirez:matteocollina:is-friend-of"
2) "sop:antirez:matteocollina:was-at-conference-with"
3) "sop:antirez:matteocollina:talked-with"
Multi dimensional indexes
Non range indexes
get random elements from sets SRANDMEMBER
queue, circular list RPOPLPUSH
capped list LPUSH, LTRIM
Index inconsistency
if the index data is outside Redis, read repair can be a solution
SCAN