我应该使用 UUID 作为 Rails 的主键吗?
我想使用 Spine.js 客户端框架,它生成 UUID 作为模型的 ID,然后可以将其持久化到服务器。如果我只使用客户端生成的模型 UUID,并将它们保存在服务器上,那将是最简单的。
在 Rails 中使用客户端生成的 UUID 作为主键有哪些缺点?
I want to use the Spine.js client-side framework, and it generates UUIDs as IDs for models, which can then be persisted to the server. It would be easiest if I just used the client-generated UUIDs for the models, and saved them on the server.
What are the drawbacks of using client-generated UUIDs as primary keys in Rails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,我不喜欢使用 UUID 作为“主键”,但是,分布式模型是它们非常适合的模型,假设 UUID 已正确生成;-) 根据其他问题,它仍然可能不是 主键,而是另一个候选键(想想由唯一索引支持的“备用 PK”)。
我知道的两个“问题”是:
UUID 就像 IPv6。它们很长,因此不是最人性化的价值观。另一方面,它们的格式非常一致并且很容易被发现。掌握复制粘贴技巧。
完全随机的UUID往往会导致索引碎片化;如果用作通常聚集的 PK(相对于可能只是指向记录的指针的索引),这可能会导致严重的碎片。 但是;
一个好的数据库维护计划应该解决这个问题:按计划重新索引碎片索引。
特殊 UUID 生成方案,例如
NEWSEQUENTIALID
虽然“更可预测”,但也可以生成单调递增的值,从而减少索引/簇碎片。
快乐编码。
I dislike UUIDs for "primary keys" in general, however, a distributed model is one in which they fit rather well, assuming the UUID is generated appropriately ;-) Depending upon other issues, it still might not be the primary key, but rather another candidate key (think of "an alternate PK" that is backed by a unique index).
The two "issues" I am aware of are:
UUIDs are like IPv6. They are long and are thus not the most human-friendly values about. On the other hand, they are very consistent in formatting and are easy to spot. Have your copy'n'paste skills about.
Completely random UUIDs tend to fragment indices; if used as PK, which is normally clustered (vs. an index which may just a pointer to the record), this can lead to terrible fragmentation. However;
A good database maintenance plan should solve this: re-index fragmented indices on a schedule.
Special UUID generation schemes, such as
NEWSEQUENTIALID
in SQL Server, while "more predictable", can also generate monotonically increasing values and thus mitigate index/cluster fragmentation.Happy coding.
假设您使用关系数据库来存储这些值,需要注意的一件事是,当表很大时,UUID 作为主表键通常表现不佳。
查看我们无所畏惧的领导者撰写的这篇博文中内容丰富的讨论:主键:ID 与 GUID
Assuming you're using a relational database to store these values, one thing to watch out for is that UUIDs generally perform poorly as primary table keys when the table is large.
Check out the informative discussion in this blog post written by our fearless leader: Primary Keys: IDs versus GUIDs