Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a cache key (unique key) for a hash

Tags:

caching

ruby

I have a hash, for example:

filers = {query: 'nice post', sort: 'time_desc', post_type: 'blog'...limit: 100}

which is used to filter response data. I need to create a unique key for this hash to cache the response. I can think of taking its keys and values and converting them into a single string. Looking for some interesting answers that are simple and efficient.

like image 251
nkm Avatar asked Oct 21 '25 20:10

nkm


1 Answers

Consider these following two steps:

  1. Convert the Hash to a string (or other serialized format) after sorting the output write-order based on key.

    It is important that the values are sorted by key during this transformation so that Hashes with the same key/value pairs (but with a different key order) will yield the same output. More complicated/nested structures need additional handling and should ensure consistent output for equivalent objects.

    To get started with the process, consider:

    sorted_kv_pairs = hash.to_a.sort_by {|k,v| k.to_s}
    
  2. Use a hashing function such as SHA-1 or SHA-256/160 to generate a 40-byte Unique ID from the previously serialized object.

    The huge output space (and cryptography qualities) of these functions make it unfeasible for there to be a purposeful collision and thus lead to "unique IDs".

like image 182
user2864740 Avatar answered Oct 24 '25 09:10

user2864740