life is too short for a diary




Resolve the Error CROSSSLOT Keys in request don't hash to the same slot

Tags: python redis memorydb aws

Author
Written by: Tushar Sharma
Featured image for Resolve the Error CROSSSLOT Keys in request don't hash to the same slot

AWS offers managed service Amazon MemoryDB which is redis compatible.. The entire keyspace in Redis cluster is divided into hash slots and these slots are assigned to multiple nodes. In redis-cli, getting a single value is straightforward

> mget "user1.key1"

> mget "user1.key2"

However if you want to run multi-operations in redis,

> MULTI 
Queued
> EVAL "return redis.call('TIME')[1]" 0 0

> mget "user1.key1"

> mget "user1.key2"

> EVAL "return redis.call('TIME')[1]" 0 0

> EXEC

This would most likely will result in following error

(error) CROSSSLOT Keys in request don't hash to the same slot

Solution 1

One solution is to force redis to insert the keys into same slot. We can achieve that using pattern "{…}"

So we have to modify are keys as {user1}.key1 and {user1}.key2. Here hash slots are only computed for keys within the braces

Solution 2

We could simply use a python library redis, if you dont want to modify your keys

To execute commands that are currently supported

print("\n%s" % conn.mget(key1))

print("\n%s" % conn.mget(key2))

To execute an arbitrary redis command,

print(conn.execute_command('zscan key1 0 MATCH *EMAIL:random@email.com*#* COUNT 100000'))

comments powered by Disqus