NoSql:枚举与字符串
只是好奇其他人如何处理枚举和枚举没有SQL?将属性存储为枚举值还是字符串更好?在某些情况下这会影响数据库的大小或性能吗?例如,假设一个职业运动员...他的运动类型可以是足球、曲棍球、棒球、篮球等...字符串与枚举,你们都怎么看?
Just curious how others deal with enums & nosql? Is it better to store an attribute as an enum value or a string? Does this affect the size or performance of the database in some cases? For example, just think of, let's say, a pro sports player... his sport type could be Football, Hockey, Baseball, Basketball, etc... string vs enum, what do you all think?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该在代码中使用枚举 - 强类型有助于避免很多错误 - 并将它们转换为字符串或数字进行存储。
字符串确实需要更多的存储空间 - “篮球”是 10-20 个字节,具体取决于编码,如果将其存储为 4,则只需要 1 个字节。然而,在极少数情况下,这实际上很重要 - 如果您有 100 万条记录,数据库总大小的差异仍然小于 20MB。字符串更容易使用,并且在枚举发生更改时不太可能默默失败,因此请使用字符串。
对于大多数操作来说,字符串也比数字慢,包括在加载时转换为枚举。但是,差异比从数据库检索任何内容所需的时间要小几个数量级,因此并不重要。
You should be using enums in your code - strong typing helps avoid a lot of mistakes - and converting them to strings or numbers for storage.
Strings do require significantly more storage space - "Basketball" is 10-20 bytes depending on encoding, and if you store it as 4 it only needs 1 byte. However, there are very few cases where this will actually matter - if you have a million records, it is still less than 20MB difference in total database size. Strings are easier to work with and less likely to fail silently if the enumeration changes, so use strings.
Strings are also slower than numbers for most operations, including conversion to enum on load. However, the difference is orders of magnitude less than the time taken to retrieve anything at all from the database, so doesn't matter.
从可移植性的角度来看,
String
更好。Enum
不受MSSQL Server
等流行 DBMS 的支持。您可以使用应用程序级逻辑来防止对数组进行有效输入,并将其存储为字符串。
编辑:
我的首选项更改为
String
,因为CakePHP
(我在其中开发网络应用程序)不再支持Enum
出于可移植性考虑。String
are better of portability perspective. AndEnum
is not supported by popular DBMS's likeMSSQL Server
and many others.You can have application level logic to prevent valid input against an array and just store it as String.
EDIT:
My preferences changed to
String
asCakePHP
(where I do web apps) no-longer supportEnum
for portability concerns.