Is there a way to generate hash integer within a predefined range for a string in PostgreSQL?

2.4k views Asked by At

For sharding I need good hash algorithm. I need to generate hash integer value for string within 0-2^31 range. Is this possible ?

Following answer give a way to generate integer from md5 algorithm.

Hashing a String to a Numeric Value in PostgresSQL

But is there a way to generate this value within a range ?

1

There are 1 answers

0
Daniel Vérité On

In the function suggested in Hashing a String to a Numeric Value in PostgresSQL, the 32 bits range is expressed as the width of the bit(N) cast.

It cannot be passed as a parameter because a type modifier must be constant, but to get a fixed 31 bits, you may just adjust the function like this:

CREATE FUNCTION hash_string_into_31_bits(text) RETURNS int AS $$
   select ('x'||substr(md5($1),1,8))::bit(31)::int;
$$ language sql;

Then the result will be always 31 bits wide and positive, which is the same thing.