【问题标题】:Does MongoDB use a combination of indexes to narrow docs to scan?MongoDB 是否使用索引组合来缩小要扫描的文档?
【发布时间】:2015-02-23 09:05:10
【问题描述】:

我知道索引交集,但从文档中我不清楚以下方案是否有效:

我的文档彼此非常不同,都在一个集合中。每个文档“模式”都有一个或多个具有不同值的实例,可能有数十万个值。我使用哈希值来识别记录架构,然后使用其他字段来搜索特定文档。

例如,我在集合中获得了以下条目:

 {
    type: "ABC",
    details: { model: "14Q3", manufacturer: "M1 Corporation" },
    stock: [ { size: "M", qty: 50 } ],
    category: "clothing"
  },
  {
    item: "ABC",
    details: { model: "14Q3", manufacturer: "ABC Company" },
    stock: [ { size: "S", qty: 5 }, { size: "M", qty: 5 }, { size: "L", qty: 1 } ],
    category: "clothing"
  },
  {
    type: "XYZ",
    message: "a generic text message",
    date: [ "tag1", "tag2" , "tag3" ],
    category: "houseware",
    age: 12,
  }
  ...

查询时,我打算使用类型来缩小要搜索的文档,然后搜索其他索引字段。

MongoDB 是否能够利用涵盖我正在搜索的字段的不同索引来执行这些查询?

另外,如果我在搜索中包含索引的type 字段以及非索引字段,它会扫描所有文档还是利用type 字段索引来缩小范围,然后才扫描这些文档以查找其他标准?

我使用的是 MongoDB 2.6.6。

谢谢!

【问题讨论】:

    标签: mongodb search indexing


    【解决方案1】:

    是的,也不是。它不会使用索引组合,但您可以创建复合索引。

    为了简化,例如如果你有收藏:

    > db.test.find()
    { "_id" : ObjectId("549d0b5bde6b4daa2e1f1859"), "name" : "Adam", "age" : 15 }
    { "_id" : ObjectId("549d0b70de6b4daa2e1f185a"), "name" : "John", "hobby" : "skiing" }
    { "_id" : ObjectId("549d0b96de6b4daa2e1f185b"), "name" : "Barbara", "occupation" : "student" }
    

    然后使用名称和每个特定值创建复合索引:

    db.test.ensureIndex({name: 1, age: 1})
    db.test.ensureIndex({name: 1, hobby: 1})
    db.test.ensureIndex({name: 1, occupation: 1})
    

    然后你会尝试找到特定的文件:

    > db.test.find({name: "Adam", age: 15}).explain()
    {
        "cursor" : "BtreeCursor name_1_age_1",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 2,
        "nscannedAllPlans" : 2,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
            "name" : [
                [
                    "Adam",
                    "Adam"
                ]
            ],
            "age" : [
                [
                    15,
                    15
                ]
            ]
        },
        "server" : "CBS:27017",
        "filterSet" : false
    }
    

    您会看到,它使用了正确的索引,并且只扫描了一个文档即可找到它。
    使用explain() 命令检查每个查询使用的索引、搜索文档和搜索时间。对理解mongodb很有帮助!

    有关索引的更多信息:indexes
    并解释():explain

    您还可以设置sparse 索引,它将仅引用包含特定字段的文件,但也有一些不同之处。有关稀疏索引的更多信息:sparse indexes

    【讨论】:

      猜你喜欢
      • 2018-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      相关资源
      最近更新 更多