Rabin
Rabin

Reputation: 418

Memcache key generation from the query

I am caching the select query and the values inside the memcache. I am only using simple single table queries. I tired using the query itself as a key , But really couldn't because of the special character and various other reasons. Is there anyway to generate a key out of the query to a unique key without any collison and use it as a key for the memcache.

Upvotes: 1

Views: 521

Answers (1)

Alagappan Ramu
Alagappan Ramu

Reputation: 2358

We create a cache key by hashing the query. Seems to work out pretty well.

If you directly try to use the query as the key, it will not work as it could contain special characters. So we could hash the query using an hashing algorithm and use the result as a key. This will be unique for each distinct query.

import hashlib
query = "" #your query here
cache_key = str(int(hashlib.md5(query.lower()).hexdigest(), 16))

Note: The .lower() method is being called in order to consider query with different cases as the same.

Upvotes: 4

Related Questions