16

我发现很难理解如何在 mongodb 中对多键进行准确的索引。

这是我在其网站上的 mongodb 文档中读到的关于多键的内容:
1)“在数组元素索引上创建索引会导致数据库索引数组的每个元素”
2)“......将索引文档上的所有标签,并为该文档的“X”、“Y”和“Z”创建索引条目。”

那么该文档的索引条目到底是什么意思呢?每个文档是否记住条目,在这种情况下搜索将是全表扫描?或者它是 mysql 的相同 b-tree 索引,其中每个索引条目将指向每个相应事件的多个文档,在这种情况下,我想太多了。

举个例子:

obj1 = { 
    name: "Apollo",
    text: "Some text about Apollo moon landings",
    tags: [ "moon", "apollo", "spaceflight", "nasa" ]
}
obj2 = { 
    name: "Atlantis",
    text: "Some text about Atlantis flight missions",
    tags: [ "space", "atlantis", "spaceflight", "nasa" ]
}
db.articles.ensureIndex( { tags : 1 } )

请帮我理解!提前致谢。

4

2 回答 2

23

在这种情况下,您的索引(即 B 树)将如下所示:

 apollo => [ obj1 ]
 atlantis => [ obj2 ]
 moon => [ obj1 ]
 nasa  => [ obj1, obj2 ]
 space => [ obj2 ]
 spaceflight => [ obj1, obj2 ]

这只是一个“常规”B-tree 索引,除了每个文档可以出现不止一次(对于每个唯一的标签值它出现一次)。

于 2011-09-13T02:44:04.103 回答
2

I think you misunderstood the difference between Multiindex and Compound indexes:

Compound indexes are user-defined indexes for multiple fields at once. Multykey indexes: MongoDB determine if the field on which the Index is released is an array and create an index for each of the array elements, for example

db.user.ensureIndex({"address.street":1});

In this case and because the target field is an Array the index will store all the items but only once.

I highly recomend you to take a look at this simple articlw that will clarify you doubts about simple imdex types in MongoDB: http://mongodbspain.com/en/2014/01/24/mongodb-indexes-part1/

Regards,

于 2014-02-10T00:15:47.677 回答