How to Use HEXISTS Command in Redis: Syntax and Examples
Use the
HEXISTS command in Redis to check if a specific field exists within a hash stored at a given key. It returns 1 if the field exists and 0 if it does not. The syntax is HEXISTS key field.Syntax
The HEXISTS command checks if a field exists in a hash stored at a specified key.
- key: The name of the hash.
- field: The field name to check for existence.
The command returns 1 if the field exists, otherwise 0.
redis
HEXISTS key field
Example
This example shows how to use HEXISTS to check if a field exists in a hash.
redis
HSET user:1000 name "Alice" HSET user:1000 age 30 HEXISTS user:1000 name HEXISTS user:1000 email
Output
1
0
Common Pitfalls
Common mistakes when using HEXISTS include:
- Checking a field on a key that is not a hash, which returns
0because the field cannot exist. - Confusing
HEXISTSwithHGET—HEXISTSonly checks existence and returns1or0, it does not return the field value. - Using wrong key or field names due to typos, leading to unexpected
0results.
redis
/* Wrong: Using HGET to check existence */ HGET user:1000 name /* Right: Use HEXISTS to check existence */ HEXISTS user:1000 name
Quick Reference
| Command | Description | Returns |
|---|---|---|
| HEXISTS key field | Check if field exists in hash at key | 1 if exists, 0 if not |
| HSET key field value | Set field in hash | 1 if new field, 0 if updated |
| HGET key field | Get value of field in hash | Value or nil if not found |
Key Takeaways
Use HEXISTS to quickly check if a field exists in a Redis hash.
HEXISTS returns 1 if the field exists, otherwise 0.
Do not confuse HEXISTS with HGET; HEXISTS only checks existence.
Ensure the key is a hash type to get accurate results.
Always double-check key and field names to avoid false negatives.