Batch cache reads
Read several cached string fields in one request.
Redis · Module
MGET atomically retrieves the string values of one or more keys in a single command. Missing keys and keys holding non-string values return nil in their corresponding result positions.
MGET atomically reads the string values for one or more keys and returns them as an array aligned with the requested key order. A missing key or a key containing a non-string value contributes nil, so the command does not fail for those cases.
MGET key [key ...]| Name | Type | Description |
|---|---|---|
key [key ...] | key | One or more keys whose string values should be retrieved. |
An array of values corresponding to the specified keys; missing keys and keys that do not hold strings return nil.
redis-cli SET user:1 Alice
redis-cli SET user:2 Bob
redis-cli MGET user:1 user:2 user:3The command returns the values in key order; the missing key produces nil.
Read several cached string fields in one request.
Fetch a group of independent values while reducing client-server round trips.
Preserve the association between requested keys and returned values by using the response positions.
MGET accepts one or more keys and returns an array containing the corresponding values. Results preserve the input-key order, and missing or non-string keys contribute nil.
Follow-up: What is its time complexity? It is O(N), where N is the number of keys retrieved.
MGET is atomic as a command: Redis returns the string values for all requested keys in one operation. It is useful when several independent string values must be read with fewer client-server round trips.
Follow-up: How would you reduce latency further for many unrelated requests? Compare MGET with pipelining, while considering the key distribution and the deployment's clustering behavior.
MGET is intended for string values. If a requested key is absent or does not contain a string, its position in the returned array is nil rather than causing the whole command to fail.
Follow-up: How should an application distinguish an absent key from a non-string key? Use an additional type-aware check such as TYPE when that distinction matters, because MGET itself reports nil for both cases.
GETMSETSETRedis Stringsmulti-key operations