Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Redis Cheatsheet

Redis

Set record

SET foo bar

Get record

GET foo

Secondary indexes with hashes

HSET doc:1 "foo" 1
HSET doc:1 "bar" 2

Scan first 10 records

SCAN 0 COUNT 10

Reset database

FLUSHALL
FLUSHDB

RediSearch

Create an index

FT.CREATE names SCHEMA name TEXT WEIGHT 5.0 PHONETIC dm:en rank NUMERIC SORTABLE tags TEXT class TEXT

Set and index document

HSET doc:1 name "foo" rank 1 tags "foo,bar" class "bar"
HSET doc:2 name "bar" rank 1 tags "bar" class "foo"

Get all by index

HGETALL doc:1

Get attribute by index

HGET doc:1 name rank

Searching (query language)

FT.SEARCH names "foo"

Get aggregations

FT.AGGREGATE names "@class:\"foo\"" GROUPBY 1 @class REDUCE count 0 AS total

Drop index

FT.DROPINDEX names DD

redis-cli

Connect to Redis instance

redis-cli -h 0.0.0.0 -p 6301

Mass insert data from file

# data.txt
SET doc:1 foo
SET doc:2 bar
$ cat data.txt | redis-cli --pipe

Mass insert data from file (with progress monitor)

$ (f=data.txt; s=$(stat -c %s $f); echo "Rows: $(wc -l $f) $s"; cat $f | pv -s $s | redis-cli --pipe)

Mass delete records by pattern

redis-cli --scan --pattern doc:* | xargs redis-cli del

Monitor output of Redis for errors

redis-cli monitor

Tips

Double escape all characters

HSET doc:1 name "Foo\\-foo\\-bar" rank 10
FT.SEARCH names "Foo\\-foo\\-bar"

Generate Redis mass insert file from key/value JSON

$ jq -r 'to_entries|map("HSET \(.key|@sh) name \(.value|@sh) class foo")|.[]' data.json > data.txt

Validating data

Find unbalanced quotes in a mass insert file

$ awk -F\' 'NF%2==0 {print NR$0;;}' data.txt
$ awk -F\" 'NF%2==0 {print NR$0;;}' data.txt

Print a line from file

$ sed -n '15p' < data.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment