MongoDB:两字段索引与文档字段索引
我需要通过两个字段(唯一索引)对集合进行索引,例如 field1 和 field2。就性能而言,什么是更好的方法:
创建常规两列索引
-或 -
将这两个字段组合在单个文档字段 {field1 : value, field2 : value2} 中并为该字段建立索引?
注意:我将始终通过这两个字段一起进行查询。
I need to index a collection by two fields (unique index), say field1 and field2. What's better approach in terms of performance:
Create a regular two-column index
-or -
Combine those two fields in a single document field {field1 : value, field2 : value2} and index that field?
Note: I will always be querying by those two fields together.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将列分开并创建单个索引,这将提高同时查询两个字段时的性能。
http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes
将各列放在同一列中不会提高性能,因为您必须以相同的方式对它们进行索引:
http://www.mongodb.org/display/DOCS/Indexes#Indexes-EmbeddedKeys
或者您可以索引整个文档
http://www.mongodb.org/display/DOCS/Indexes#Indexes-DocumentsasKeys
性能可能会有所提高,但幅度可能很大。使用测试数据库,创建测试数据并对一些测试进行基准测试以找出答案。我们很想听听您的结果。
You can keep the columns separate and create a single index that will increase performance when querying both fields together.
http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes
Having the columns in the same column provides no performance increases, because you must index them the same way:
http://www.mongodb.org/display/DOCS/Indexes#Indexes-EmbeddedKeys
Or you can index the entire document
http://www.mongodb.org/display/DOCS/Indexes#Indexes-DocumentsasKeys
There could be a possible performance increase, but doubtfully very much. Use the test database, create test data and benchmark some tests to figure it out. We would love to hear your results.
我会在这两个字段上创建一个复合索引。这将占用更少的磁盘空间,因为您不需要存储额外的组合字段,并为您提供第一个字段上的额外索引的好处,即
{ a:1, b:1 上的索引}
也是{ a:1 }
上的索引。I'd create a compound index over both fields. This'll take up less disk space because you won't need to store the extra combined field, and give you the bonus of an additional index over the first field, i.e. an index over
{ a:1, b:1 }
is also an index over{ a:1 }
.