如何有效地将uuid类型存储到bigint中?

问题描述 投票:0回答:1

在我的 Python 应用程序中,我有一个接受 128 位值 (_id: uuid.UUID) 的函数。我需要使用

pg_advisory_xact_lock
将此值存储到 postgres 数据库中作为咨询锁,它需要
bigInt
类型,它是一个 64 位整数。解决这个问题的最佳方法是什么?我应该使用某种哈希表吗?

python postgresql locking uuid bigint
1个回答
0
投票

我不知道您尝试过什么,但您可以使用哈希函数来减小 UUID 的大小,同时保持唯一性。您可以遵循以下一般方法:

  1. 对 UUID 进行哈希处理:可以使用 SHA-256 等哈希函数将 128 位 UUID 转换为固定大小的 256 位哈希值。因为这个哈希值大于 64 位,所以必须进一步减少。
  2. 截断哈希:您可以截断哈希以使其适合 64 位整数。但请记住,这种截断将导致个性的丧失。缩短的哈希值对于所有 UUID 可能不是唯一的,但对于大多数实际用例来说它应该足够唯一,然后将截断的哈希值转换为 PostgreSQL 中的 BigInt。 下面是一些使用 uuid 和 hashlib 库说明这种方法的 Python 代码:
import hashlib
import uuid

def uuid_to_int(uuid_val):
    # Convert the UUID to bytes
    uuid_bytes = uuid_val.bytes

    # Calculate a hash of the UUID bytes (using MD5 in this example)
    md5_hash = hashlib.md5(uuid_bytes)

    # Take the first 8 bytes of the MD5 hash and convert them to an integer
    result = int.from_bytes(md5_hash.digest()[:8], byteorder='big')

    return result
© www.soinside.com 2019 - 2024. All rights reserved.