785

Is there a Redis command for fetching all keys in the database? I have seen some python-redis libraries fetching them. But was wondering if it is possible from redis-client.

3

18 Answers 18

1044

Try to look at KEYS command. KEYS * will list all keys stored in redis.

EDIT: please note the warning at the top of KEYS documentation page:

Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.

UPDATE (V2.8 or greater): SCAN is a superior alternative to KEYS, in the sense that it does not block the server nor does it consume significant resources. Prefer using it.

Sign up to request clarification or add additional context in comments.

4 Comments

CLI usage example: redis-cli keys "*"
Correction: All redis commands are single-thread and will block the server. The only difference is that KEYS has the potential of blocking the server for longer when querying a large data set
also don't forget to do "select DatabaseNubmer" first
KEYS "*" (with quotes) was what I missed, thank you @XåpplI'-I0llwlg'I- ! Good to note: Quotes are needed to run inline (redis-cli KEYS "*"), but inside the cli shell no quotes are needed (KEYS *)
216

Updated for Redis 2.8 and above

As noted in the comments of previous answers to this question, KEYS is a potentially dangerous command since your Redis server will be unavailable to do other operations while it serves it. Another risk with KEYS is that it can consume (dependent on the size of your keyspace) a lot of RAM to prepare the response buffer, thus possibly exhausting your server's memory.

Version 2.8 of Redis had introduced the SCAN family of commands that are much more polite and can be used for the same purpose.

The CLI also provides a nice way to work with it:

$ redis-cli --scan --pattern '*'

2 Comments

For me this command also worked redis-cli --scan * does it has some downside?
Even redis-cli --scan should just work
127

It can happen that using redis-cli, you connect to your remote redis-server, and then the command:

KEYS *

is not showing anything, or better, it shows:
(empty list or set)

If you are absolutely sure that the Redis server you use is the one you have the data, then maybe your redis-cli is not connecting to the Redis correct database instance.

As it is mentioned in the Redis docs, new connections connect as default to the db 0.

In my case KEYS command was not retrieving results because my database was 1. In order to select the db you want, use SELECT.
The db is identified by an integer.

SELECT 1
KEYS *

I post this info because none of the previous answers was solving my issue.

4 Comments

how do I execute the command directly from a shell redis-cli keys "*", rather than first connecting to the server.
@RRM To select a database from the CLI, use the -n option, e.g. redis-cli -n 13 KEYS '*' if you are using database 13
@TheTechRobotheNerd In a Redis cluster deployment, there is no concept of databases.
Wow wow wow! This SELECT 1 was a super crucial info! Thanks!
86

Get All Keys In Redis

Get all keys using the --scan option:

$ redis-cli --scan --pattern '*'

List all keys using the KEYS command:

$ redis-cli KEYS '*'

1 Comment

careful that keys * command is blocking on large DBs
48

-->Get all keys from redis-cli

-redis 127.0.0.1:6379> keys *

-->Get list of patterns

-redis 127.0.0.1:6379> keys d??

This will produce keys which start by 'd' with three characters.

-redis 127.0.0.1:6379> keys *t*

This wil get keys with matches 't' character in key

-->Count keys from command line by

-redis-cli keys * |wc -l

-->Or you can use dbsize

-redis-cli dbsize

3 Comments

Just copied the answers and tried. It gave "unknown command 'key'". "key" is not the command, "keys" is. Please correct key *t* to keys *t*.
Thanks dude for that information.it was my mistake.current i am on mobile.i will change that command eairlier.
Very useful cheatsheet this
24

Take a look at following Redis Cheat Sheet. To get a subset of redis keys with the redis-cli i use the command

KEYS "prefix:*"

Comments

9

SCAN doesn't require the client to load all the keys into memory like KEYS does. SCAN gives you an iterator you can use. I had a 1B records in my redis and I could never get enough memory to return all the keys at once.

Here is a python snippet to get all keys from the store matching a pattern and delete them:

import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
for key in r.scan_iter("key_pattern*"):
    print key

Comments

8

Yes, you can get all keys by using this

var redis = require('redis');
redisClient = redis.createClient(redis.port, redis.host);    
  redisClient.keys('*example*', function (err, keys) {
})

1 Comment

Not exactly what the OP was asking (redis-cli), but thanks for pointing this out nevertheless.
6
redis-cli -h <host> -p <port> keys * 

where * is the pattern to list all keys

1 Comment

I had to quote the star, as follows: redis-cli -h <host> -p <port> keys '*'
6

KEYS pattern

Available since 1.0.0.

Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.

Returns all keys matching pattern.

Warning : This command is not recommended to use because it may ruin performance when it is executed against large databases instead of KEYS you can use SCAN or SETS.

Example of KEYS command to use :

redis> MSET firstname Jack lastname Stuntman age 35
"OK"
redis> KEYS *name*
1) "lastname"
2) "firstname"
redis> KEYS a??
1) "age"
redis> KEYS *
1) "lastname"
2) "age"
3) "firstname"

Comments

1

In order to get all the keys available in redis server, you should open redis-cli and type: KEYS * In order to get more help please visit this page: This Link

Comments

1

If your redis is a cluster,you can use this script

#!/usr/bin/env bash
redis_list=("172.23.3.19:7001,172.23.3.19:7002,172.23.3.19:7003,172.23.3.19:7004,172.23.3.19:7005,172.23.3.19:7006")

arr=($(echo "$redis_list" | tr ',' '\n'))

for info in ${arr[@]}; do
  echo "start :${info}"
  redis_info=($(echo "$info" | tr ':' '\n'))
  ip=${redis_info[0]}
  port=${redis_info[1]}
  echo "ip="${ip}",port="${port}
  redis-cli -c -h $ip -p $port set laker$port '湖人总冠军'
  redis-cli -c -h $ip -p $port keys \*

done

echo "end"

Comments

1

You can simply connect to your redis server using redis-cli, select your database and type KEYS *, please remember it will give you all the keys present in selected redis database.

2 Comments

beginner at redis here, can you detail your solution pls?
just fire redis-cli KEYS '*' command and you'll get the required keys.
1

Using nodejs client:

command line:
mkdir noderedis; cd noderedis; npm init -y; npm i redis; touch app.js;

app.js

const redis = require('redis');
  
async function redisClient(){
  console.log('initiating redis client');
  const client = redis.createClient(
  {
    socket: {
      host: '127.0.0.1',
      port: 6379
  }
  });
  client.on('error', (err) => console.error);
  console.log('trying to connect');
  await client.connect();
  console.log('connected');
  const keys = await client.sendCommand(["keys","*"]);
  if(!keys || keys.length == 0){
    console.log('No Keys in Redis');
  } else {
    console.log('printing all keys:')
    console.log(keys);
  }
  await client.disconnect();
}
redisClient();

execute:
node app.js

Comments

1

For the ones that want a typescript helper (using ioredis)

import Redis from 'ioredis';
import { from, Observable, of } from 'rxjs';
import { first, mergeMap } from 'rxjs/operators';

export function scanKeysFromRedis(redisStore: Redis.Redis, key: string, 
target: number = 0, keys: string[] = []): Observable<string[]> {
  return from(redisStore.scan(target, 'MATCH', key)).pipe(
    first(),
    mergeMap((_keys) => {
      const _target = Number(_keys[0]);
      if (_target !== 0) {
        return scanKeysFromRedis(redisStore, key, _target, [...keys, ..._keys[1]]);
       }
      return of([...keys, ..._keys[1]]);
    }),
  );
}

and call it with: scanKeysFromRedis(store, 'hello');

Comments

0

If you are using Laravel Framework then you can simply use this:

$allKeyList = Redis::KEYS("*");

print_r($allKeyList);

In Core PHP:

$redis = new Redis();

$redis->connect('hostname', 6379);

$allKeyList = $redis->keys('*');

print_r($allKeyList);

Comments

0

Using Python3:

mkdir pyredis; cd pyredis; python3 -m venv ./; source ./bin/activate; pip install redis; touch pyredis.py

import redis

print('# connecting to Redis server')

r = redis.Redis(host='localhost', port=6379, db=0)

print('# printing the keys')
for key in r.scan_iter():
    print(key)
print('# all keys printed')

python3 pyredis.py

Comments

-2

We should be using --scan --pattern with redis 2.8 and later.

You can try using this wrapper on top of redis-cli. https://github.com/VijayantSoni/redis-helper

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.