【问题标题】:Creating a compound index on a single array field在单个数组字段上创建复合索引
【发布时间】:2013-07-15 15:33:33
【问题描述】:

我想在将保存数组的字段上创建索引。默认情况下,当在这样的字段上创建索引时,mongo 会分别索引每个数组中的每个项目。

但是,我希望索引改为复合索引,类似于子文档字段上的索引(我希望索引是唯一的,并且 ['a', 'b']['b', 'a'] 不同)。有没有办法在 monogo 中做到这一点?

【问题讨论】:

  • 必须是数组吗?
  • 嗯,它需要是某种任意长度的多值字段。数组是我所知道的唯一符合要求的东西......
  • 您可以将其存储在一个字符串中,"a,b" 并处理应用程序中的各个元素。
  • 值可以有不同的类型,我想保持他们的身份
  • 意识到密钥长度不能超过1024字节。

标签: mongodb indexing


【解决方案1】:

您可以通过如下方式存储数据来做到这一点:

{ 
    field: { v: [ a, "b" ] }
}

然后做一个索引:

db.collection.ensureIndex( { field: 1 } );

我知道这有点违反直觉,但是“字段”上的索引现在将用作索引值:

v: [ a, "b" ]

并不是每个 a 和 "b" 都是单独的。当然你可以为“v”使用别的东西,但重要的是字段的值是一个文档,而不是一个数组。

查询:

db.collection.find( { field: { v: [ 'a', 'b' ] } } )

然后会愉快地使用索引:

{
    "cursor" : "BtreeCursor field_1",
    "isMultiKey" : false,
    "n" : 1,
    "nscannedObjects" : 1,
    "nscanned" : 1,
    "nscannedObjectsAllPlans" : 1,
    "nscannedAllPlans" : 1,
    "scanAndOrder" : false,
    "indexOnly" : false,
    "nYields" : 0,
    "nChunkSkips" : 0,
    "millis" : 0,
    "indexBounds" : {
        "field" : [
            [
                {
                    "v" : [ "a", "b" ]
                },
                {
                    "v" : [ "a", "b" ]
                }
            ]
        ]
    },
    "server" : "whisky:27017"
}

【讨论】:

  • 在查询中使用复合值时,它实际上是否使用了索引?我认为不会。
  • 当然,我已经澄清了我的答案。
【解决方案2】:

对于在包装字段上索引时是否使用索引的问题,是的,它确实使用了索引。以下来自 shell 的语句证明了这一点。

> db.arrayindtest.insert({_id:1, f:{a:["a","b"]}})
> db.arrayindtest.insert({_id:2, f:{a:["b","a"]}})
> db.arrayindtest.insert({_id:3, f:{a:["a","b", "c"]}})
> db.arrayindtest.ensureIndex({f:1})
> db.arrayindtest.find({f:{a:["a","b"]}})
{ "_id" : 1, "f" : { "a" : [  "a",  "b" ] } }
> db.arrayindtest.find({f:{a:["a","b"]}}).explain()
{
        "cursor" : "BtreeCursor f_1",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 1,
        "nscannedAllPlans" : 1,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
                "f" : [
                        [
                                {
                                        "a" : [
                                                "a",
                                                "b"
                                        ]
                                },
                                {
                                        "a" : [
                                                "a",
                                                "b"
                                        ]
                                }
                        ]
                ]
        },
        "server" : "sridhar-PC:27017"
}
>

【讨论】:

    猜你喜欢
    • 2015-03-01
    • 2018-08-15
    • 2017-09-04
    • 2012-11-16
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2020-05-08
    相关资源
    最近更新 更多