{
  "schema_version": 2,
  "id": "commands/keys",
  "title": "KEYS",
  "url": "https://redis.io/docs/latest/commands/keys/",
  "summary": "Returns all key names that match a pattern.",
  "since": "1.0.0",
  "tags": [
    "docs",
    "develop",
    "stack",
    "oss",
    "rs",
    "rc",
    "oss",
    "kubernetes",
    "clients"
  ],
  "last_updated": "2026-09-18T09:48:32+01:00",
  "page_type": "content",
  "content_hash": "ba79622196deab0a26c24fa079c48f76fce3b564b4077348497fe94de15b1bf9",
  "sections": [
    {
      "id": "required-arguments",
      "title": "Required arguments",
      "role": "content",
      "text": "<details open><summary><code>pattern</code></summary>\n\nThe glob-style pattern to match key names against.\n\n</details>"
    },
    {
      "id": "details",
      "title": "Details",
      "role": "content",
      "text": "While the time complexity for this operation is O(N), the constant times are\nfairly low.\nFor example, Redis running on an entry level laptop can scan a 1 million key\ndatabase in 40 milliseconds.\n\n> [!WARNING]\n> Use extreme care when using this command in production environments.\n> It may ruin performance when it is executed against large databases.\n> This command is intended for debugging and special operations, such as changing\n> your keyspace layout.\n> Don't use `KEYS` in your regular application code.\n> If you're looking for a way to find keys in a subset of your keyspace, consider\n> using [`SCAN`](https://redis.io/docs/latest/commands/scan) or [sets](https://redis.io/docs/latest/develop/data-types/sets).\n\nSupported glob-style patterns:\n\n* `h?llo` matches `hello`, `hallo` and `hxllo`\n* `h*llo` matches `hllo` and `heeeello`\n* `h[ae]llo` matches `hello` and `hallo,` but not `hillo`\n* `h[^e]llo` matches `hallo`, `hbllo`, ... but not `hello`\n* `h[a-b]llo` matches `hallo` and `hbllo`\n\nUse `\\` to escape special characters if you want to match them verbatim.\n\nWhen using [Redis Cluster](https://redis.io/docs/latest/operate/oss_and_stack/management/scaling), the search is optimized for patterns that imply a single slot.\nIf a pattern can only match keys of one slot,\nRedis only iterates over keys in that slot, rather than the whole database,\nwhen searching for keys matching the pattern.\nFor example, with the pattern `{a}h*llo`, Redis would only try to match it with the keys in slot 15495, which hash tag `{a}` implies.\nTo use pattern with a hash tag, see [Hash tags](https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec#hash-tags) in the Cluster specification for more information."
    },
    {
      "id": "examples",
      "title": "Examples",
      "role": "example",
      "text": "Returns all key names that match a pattern\n\n**Difficulty:** Beginner\n\n**Commands:** MSET, KEYS\n\n**Complexity:**\n- MSET: O(N)\n- KEYS: O(N)\n\n**Available in:** Redis CLI, C, C#, Go, Java (Asynchronous - Lettuce), Java (Reactive - Lettuce), Java (Synchronous - Jedis), JavaScript (Node.js), JavaScript (Node.js), PHP, Python, Rust (Asynchronous), Rust (Synchronous)\n\n##### Redis CLI\n\n[code example]\n\n##### C\n\n[code example]\n\n##### C#\n\n[code example]\n\n##### Go\n\n[code example]\n\n##### Java (Asynchronous - Lettuce)\n\n[code example]\n\n##### Java (Reactive - Lettuce)\n\n[code example]\n\n##### Java (Synchronous - Jedis)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### JavaScript (Node.js)\n\n[code example]\n\n##### PHP\n\n[code example]\n\n##### Python\n\n[code example]\n\n##### Rust (Asynchronous)\n\n[code example]\n\n##### Rust (Synchronous)\n\n[code example]"
    },
    {
      "id": "redis-software-and-redis-cloud-compatibility",
      "title": "Redis Software and Redis Cloud compatibility",
      "role": "content",
      "text": "| Redis<br />Software | Redis<br />Cloud | <span style=\"min-width: 9em; display: table-cell\">Notes</span> |\n|:----------------------|:-----------------|:------|\n| <span title=\"Supported\">&#x2705; Standard</span><br /><span title=\"Supported\"><nobr>&#x2705; Active-Active</nobr></span> | <span title=\"Supported\">&#x2705; Standard</span><br /><span title=\"Supported\"><nobr>&#x2705; Active-Active</nobr></span> |  |"
    },
    {
      "id": "return-information",
      "title": "Return information",
      "role": "returns",
      "text": "**RESP2:**\n\n[Array reply](../../develop/reference/protocol-spec#arrays): a list of keys matching _pattern_.\n\n**RESP3:**\n\n[Array reply](../../develop/reference/protocol-spec#arrays): a list of keys matching _pattern_."
    }
  ],
  "examples": [
    {
      "id": "examples-ex0",
      "language": "plaintext",
      "code": "> MSET firstname Jack lastname Stuntman age 35\nOK\n> KEYS *name*\n1) \"lastname\"\n2) \"firstname\"\n> KEYS a??\n1) \"age\"\n> KEYS *\n1) \"age\"\n2) \"lastname\"\n3) \"firstname\"",
      "section_id": "examples"
    },
    {
      "id": "examples-ex1",
      "language": "c",
      "code": "redisReply *reply;\n\n    // Set up keys\n    reply = redisCommand(c, \"MSET %s %s %s %s %s %s\",\n        \"firstname\", \"Jack\", \"lastname\", \"Stuntman\", \"age\", \"35\");\n    printf(\"MSET firstname Jack lastname Stuntman age 35: %s\\n\", reply->str);\n    // >>> OK\n    freeReplyObject(reply);\n\n    // Keys matching *name*\n    reply = redisCommand(c, \"KEYS %s\", \"*name*\");\n    printf(\"KEYS *name*:\\n\");\n    for (size_t i = 0; i < reply->elements; i++) {\n        printf(\"  %s\\n\", reply->element[i]->str);\n    }\n    // >>> firstname\n    // >>> lastname\n    freeReplyObject(reply);\n\n    // Keys matching a??\n    reply = redisCommand(c, \"KEYS %s\", \"a??\");\n    printf(\"KEYS a??:\\n\");\n    for (size_t i = 0; i < reply->elements; i++) {\n        printf(\"  %s\\n\", reply->element[i]->str);\n    }\n    // >>> age\n    freeReplyObject(reply);\n\n    // All keys\n    reply = redisCommand(c, \"KEYS %s\", \"*\");\n    printf(\"KEYS *:\\n\");\n    for (size_t i = 0; i < reply->elements; i++) {\n        printf(\"  %s\\n\", reply->element[i]->str);\n    }\n    // >>> age\n    // >>> firstname\n    // >>> lastname\n    freeReplyObject(reply);",
      "section_id": "examples"
    },
    {
      "id": "examples-ex2",
      "language": "csharp",
      "code": "bool keysResult1 = db.StringSet(\n            new KeyValuePair<RedisKey, RedisValue>[] {\n                new(\"firstname\", \"Jack\"),\n                new(\"lastname\", \"Stuntman\"),\n                new(\"age\", \"35\")\n            }\n        );\n        Console.WriteLine(keysResult1);  // >>> True\n\n        IServer server = muxer.GetServer(\"localhost:6379\");\n\n        RedisKey[] keysResult2 = server.Keys(pattern: \"*name*\").ToArray();\n        Array.Sort(keysResult2, (a, b) => a.ToString().CompareTo(b.ToString()));\n        Console.WriteLine(string.Join(\", \", keysResult2.Select(k => k.ToString())));  // >>> firstname, lastname\n\n        RedisKey[] keysResult3 = server.Keys(pattern: \"a??\").ToArray();\n        Console.WriteLine(string.Join(\", \", keysResult3.Select(k => k.ToString())));  // >>> age\n\n        RedisKey[] keysResult4 = server.Keys(pattern: \"*\").ToArray();\n        Array.Sort(keysResult4, (a, b) => a.ToString().CompareTo(b.ToString()));\n        Console.WriteLine(string.Join(\", \", keysResult4.Select(k => k.ToString())));  // >>> age, firstname, lastname",
      "section_id": "examples"
    },
    {
      "id": "examples-ex3",
      "language": "go",
      "code": "keysResult1, err := rdb.MSet(ctx, \"firstname\", \"Jack\", \"lastname\", \"Stuntman\", \"age\", \"35\").Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(keysResult1) // >>> OK\n\n\tkeysResult2, err := rdb.Keys(ctx, \"*name*\").Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsort.Strings(keysResult2)\n\tfmt.Println(keysResult2) // >>> [firstname lastname]\n\n\tkeysResult3, err := rdb.Keys(ctx, \"a??\").Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(keysResult3) // >>> [age]\n\n\tkeysResult4, err := rdb.Keys(ctx, \"*\").Result()\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsort.Strings(keysResult4)\n\tfmt.Println(keysResult4) // >>> [age firstname lastname]",
      "section_id": "examples"
    },
    {
      "id": "examples-ex4",
      "language": "java",
      "code": "CompletableFuture<Void> keysExample = asyncCommands.mset(Map.of(\n                    \"firstname\", \"Jack\",\n                    \"lastname\", \"Stuntman\",\n                    \"age\", \"35\"\n            )).thenCompose(res1 -> {\n                System.out.println(res1); // >>> OK\n\n                return asyncCommands.keys(\"*name*\");\n            }).thenCompose(res2 -> {\n                Collections.sort(res2);\n                System.out.println(res2); // >>> [firstname, lastname]\n\n                return asyncCommands.keys(\"a??\");\n            }).thenCompose(res3 -> {\n                System.out.println(res3); // >>> [age]\n\n                return asyncCommands.keys(\"*\");\n            }).thenAccept(res4 -> {\n                Collections.sort(res4);\n                System.out.println(res4); // >>> [age, firstname, lastname]\n            }).toCompletableFuture();",
      "section_id": "examples"
    },
    {
      "id": "examples-ex5",
      "language": "java",
      "code": "Mono<Void> keysExample = reactiveCommands.mset(Map.of(\n                    \"firstname\", \"Jack\",\n                    \"lastname\", \"Stuntman\",\n                    \"age\", \"35\"\n            )).doOnNext(res1 -> {\n                System.out.println(res1); // >>> OK\n            }).then(reactiveCommands.keys(\"*name*\").collectList()).doOnNext(res2 -> {\n                Collections.sort(res2);\n                System.out.println(res2); // >>> [firstname, lastname]\n            }).then(reactiveCommands.keys(\"a??\").collectList()).doOnNext(res3 -> {\n                System.out.println(res3); // >>> [age]\n            }).then(reactiveCommands.keys(\"*\").collectList()).doOnNext(res4 -> {\n                Collections.sort(res4);\n                System.out.println(res4); // >>> [age, firstname, lastname]\n            }).then();",
      "section_id": "examples"
    },
    {
      "id": "examples-ex6",
      "language": "java",
      "code": "String keysResult1 = jedis.mset(\"firstname\", \"Jack\", \"lastname\", \"Stuntman\", \"age\", \"35\");\n        System.out.println(keysResult1); // >>> OK\n\n        Set<String> keysResult2 = jedis.keys(\"*name*\");\n        ArrayList<String> keysResult2List = new ArrayList<>(keysResult2);\n        Collections.sort(keysResult2List);\n        System.out.println(keysResult2List); // >>> [firstname, lastname]\n\n        Set<String> keysResult3 = jedis.keys(\"a??\");\n        System.out.println(keysResult3); // >>> [age]\n\n        Set<String> keysResult4 = jedis.keys(\"*\");\n        ArrayList<String> keysResult4List = new ArrayList<>(keysResult4);\n        Collections.sort(keysResult4List);\n        System.out.println(keysResult4List); // >>> [age, firstname, lastname]",
      "section_id": "examples"
    },
    {
      "id": "examples-ex7",
      "language": "javascript",
      "code": "const keysRes1 = await client.mSet({ firstname: 'Jack', lastname: 'Stuntman', age: '35' });\nconsole.log(keysRes1); // OK\n\nconst keysRes2 = await client.keys('*name*');\nconsole.log(keysRes2.sort()); // ['firstname', 'lastname']\n\nconst keysRes3 = await client.keys('a??');\nconsole.log(keysRes3); // ['age']\n\nconst keysRes4 = await client.keys('*');\nconsole.log(keysRes4.sort()); // ['age', 'firstname', 'lastname']",
      "section_id": "examples"
    },
    {
      "id": "examples-ex8",
      "language": "javascript",
      "code": "const keysRes1 = await redis.mset({ firstname: 'Jack', lastname: 'Stuntman', age: '35' });\nconsole.log(keysRes1); // >>> OK\n\nconst keysRes2 = await redis.keys('*name*');\nconsole.log(keysRes2.sort()); // >>> ['firstname', 'lastname']\n\nconst keysRes3 = await redis.keys('a??');\nconsole.log(keysRes3); // >>> ['age']\n\nconst keysRes4 = await redis.keys('*');\nconsole.log(keysRes4.sort()); // >>> ['age', 'firstname', 'lastname']",
      "section_id": "examples"
    },
    {
      "id": "examples-ex9",
      "language": "javascript",
      "code": "const keysRes1 = await client.mSet({ firstname: 'Jack', lastname: 'Stuntman', age: '35' });\nconsole.log(keysRes1); // OK\n\nconst keysRes2 = await client.keys('*name*');\nconsole.log(keysRes2.sort()); // ['firstname', 'lastname']\n\nconst keysRes3 = await client.keys('a??');\nconsole.log(keysRes3); // ['age']\n\nconst keysRes4 = await client.keys('*');\nconsole.log(keysRes4.sort()); // ['age', 'firstname', 'lastname']",
      "section_id": "examples"
    },
    {
      "id": "examples-ex10",
      "language": "javascript",
      "code": "const keysRes1 = await redis.mset({ firstname: 'Jack', lastname: 'Stuntman', age: '35' });\nconsole.log(keysRes1); // >>> OK\n\nconst keysRes2 = await redis.keys('*name*');\nconsole.log(keysRes2.sort()); // >>> ['firstname', 'lastname']\n\nconst keysRes3 = await redis.keys('a??');\nconsole.log(keysRes3); // >>> ['age']\n\nconst keysRes4 = await redis.keys('*');\nconsole.log(keysRes4.sort()); // >>> ['age', 'firstname', 'lastname']",
      "section_id": "examples"
    },
    {
      "id": "examples-ex11",
      "language": "php",
      "code": "$keysResult1 = $r->mset(['firstname' => 'Jack', 'lastname' => 'Stuntman', 'age' => '35']);\n        echo $keysResult1 . PHP_EOL; // >>> OK\n\n        $keysResult2 = $r->keys('*name*');\n        sort($keysResult2);\n        echo implode(', ', $keysResult2) . PHP_EOL; // >>> firstname, lastname\n\n        $keysResult3 = $r->keys('a??');\n        echo implode(', ', $keysResult3) . PHP_EOL; // >>> age\n\n        $keysResult4 = $r->keys('*');\n        sort($keysResult4);\n        echo implode(', ', $keysResult4) . PHP_EOL; // >>> age, firstname, lastname",
      "section_id": "examples"
    },
    {
      "id": "examples-ex12",
      "language": "python",
      "code": "res = r.mset({\"firstname\": \"Jack\", \"lastname\": \"Stuntman\", \"age\": \"35\"})\nprint(res)\n# >>> True\n\nres = r.keys(\"*name*\")\nprint(sorted(res))\n# >>> ['firstname', 'lastname']\n\nres = r.keys(\"a??\")\nprint(res)\n# >>> ['age']\n\nres = r.keys(\"*\")\nprint(sorted(res))\n# >>> ['age', 'firstname', 'lastname']",
      "section_id": "examples"
    },
    {
      "id": "examples-ex13",
      "language": "rust",
      "code": "match r.mset(&[(\"firstname\", \"Jack\"), (\"lastname\", \"Stuntman\"), (\"age\", \"35\")]).await {\n            Ok(res) => {\n                let res: String = res;\n                println!(\"{res}\");    // >>> OK\n            },\n            Err(e) => {\n                println!(\"Error setting keys: {e}\");\n                return;\n            }\n        }\n\n        match r.keys::<&str, Vec<String>>(\"*name*\").await {\n            Ok(res) => {\n                let mut sorted_res = res.clone();\n                sorted_res.sort();\n                println!(\"{sorted_res:?}\");    // >>> [\"firstname\", \"lastname\"]\n            },\n            Err(e) => {\n                println!(\"Error getting keys: {e}\");\n                return;\n            }\n        }\n\n        match r.keys::<&str, Vec<String>>(\"a??\").await {\n            Ok(res) => {\n                println!(\"{res:?}\");    // >>> [\"age\"]\n            },\n            Err(e) => {\n                println!(\"Error getting keys: {e}\");\n                return;\n            }\n        }\n\n        match r.keys::<&str, Vec<String>>(\"*\").await {\n            Ok(res) => {\n                let mut sorted_res = res.clone();\n                sorted_res.sort();\n                println!(\"{sorted_res:?}\");    // >>> [\"age\", \"firstname\", \"lastname\"]\n            },\n            Err(e) => {\n                println!(\"Error getting keys: {e}\");\n                return;\n            }\n        }",
      "section_id": "examples"
    },
    {
      "id": "examples-ex14",
      "language": "rust",
      "code": "match r.mset(&[(\"firstname\", \"Jack\"), (\"lastname\", \"Stuntman\"), (\"age\", \"35\")]) {\n            Ok(res) => {\n                let res: String = res;\n                println!(\"{res}\");    // >>> OK\n            },\n            Err(e) => {\n                println!(\"Error setting keys: {e}\");\n                return;\n            }\n        }\n\n        match r.keys::<&str, Vec<String>>(\"*name*\") {\n            Ok(res) => {\n                let mut sorted_res = res.clone();\n                sorted_res.sort();\n                println!(\"{sorted_res:?}\");    // >>> [\"firstname\", \"lastname\"]\n            },\n            Err(e) => {\n                println!(\"Error getting keys: {e}\");\n                return;\n            }\n        }\n\n        match r.keys::<&str, Vec<String>>(\"a??\") {\n            Ok(res) => {\n                println!(\"{res:?}\");    // >>> [\"age\"]\n            },\n            Err(e) => {\n                println!(\"Error getting keys: {e}\");\n                return;\n            }\n        }\n\n        match r.keys::<&str, Vec<String>>(\"*\") {\n            Ok(res) => {\n                let mut sorted_res = res.clone();\n                sorted_res.sort();\n                println!(\"{sorted_res:?}\");    // >>> [\"age\", \"firstname\", \"lastname\"]\n            },\n            Err(e) => {\n                println!(\"Error getting keys: {e}\");\n                return;\n            }\n        }",
      "section_id": "examples"
    }
  ]
}
