简体   繁体   English

来自字符串的Python最短唯一ID

[英]Python shortest unique id from strings

I have more than 100 million unique strings (VARCHAR(100) UNIQUE in MySQL database). 我有超过1亿个唯一字符串(MySQL数据库中的VARCHAR(100)UNIQUE)。 Now I use the code below to create unique hash from them (VARCHAR(32) UNIQUE) in order to reduct index size of the InnoDB table (a unique index on varchar(100) is roughly 3 times larger than on varchar(32) field). 现在我使用下面的代码从它们创建唯一的哈希值(VARCHAR(32)UNIQUE)以减少InnoDB表的索引大小(varchar(100)上的唯一索引大约是varchar(32)字段的3倍)。

id = hashlib.md5(str).hexdigest()

Is there any other method to create shorter ids from those strings and make reasonable uniqueness guarantees? 有没有其他方法可以从这些字符串创建更短的ID并做出合理的唯一性保证?

You can save it as integer: 您可以将其保存为整数:

id_ = int(hashlib.md5(your_str).hexdigest(), 16)

Or as binary string: 或者作为二进制字符串

id_ = hashlib.md5(your_str).digest()

一种粗暴的方式可以是,你可以做md5,然后从中挑选前16个字符,而不是全部32.冲突仍然不会那么高,你将有合理的唯一性保证。

The simplest solutions is to convert hexadecimal data (yor digests have base of 16) to something else, eg. 最简单的解决方案是将十六进制数据(yor摘要具有16的基数)转换为其他数据,例如。 with base 64. 基地64。

If you agree on some level of higher risk, you can use only eg first ten digits (hexadecimal) of the digest. 如果您同意某种程度的高风险,则只能使用例如摘要的前十位(十六进制)。 It will give you 16**10 (more than 10**12 ) possibilities instead of 16**32 (more than 10**38 ), but it is still huge and is commonly used technique (Git and Github usually use 7 digits for identifying commits, afair). 它会给你16**10 (超过10**12 )的可能性而不是16**32 (超过10**38 ),但它仍然是巨大的并且是常用的技术(Git和Github通常使用7位数字)用于识别提交,不确定)。

Since hashing and compression are very similar an obvious solution is to use a compression algorithm to compress your keys. 由于散列和压缩非常相似,显而易见的解决方案是使用压缩算法来压缩密钥。 This will preserve the uniqueness of the keys as well. 这也将保留键的唯一性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM