Remove complete hashset at once in redis

I have a hash in Redis named "match/123/result".

I am adding entries to this hash using HSET and retrieving all entries at once using HGETALL.

I want to flush this hash, but there is no command like "HDELALL" (in redis-cli).

I am therefore using DEL to remove the hash name, like this:

DEL match/123/result

I could find only this approach to removing everything (hash and its contents) at once. Is there any other solution?

71843 次浏览

Here's a ruby-based way to remove all the keys in a Hash via a single, pipelined request:

def hdelall(key)
r = Redis.new
keys = r.hgetall(key).keys
r.pipelined do
keys.each do |k|
r.hdel key, k
end
end
end

If you have a list of keys then you maybe can use hdel with multiple keys But i would certainly recommend not to use it since it has a complexity of O(N).

By default redis doesn't allow clear function inside a hashet so you'll have to use del

If you want to delete or flush the 'myhash' hash.

Please use the command below:

redis-cli


redis> del myhash

Hope it will solve the problem.

This should work in Python (from "Redis in Action" book)

all_keys = list(conn.hgetall('some_hash_name').keys())
conn.hdel('some_hash_name', *all_keys)

We can do it with one iteration: In my case, I have stored a hash in which key was my "field" and at value, I have stored an object. So you can change accordingly.

Object.keys(cartData).forEach((field)=>{
redisClient.hdel("YOUR KEY",field);
});