【问题标题】:How to create hashed index by mgo (golang)如何通过mgo(golang)创建哈希索引
【发布时间】:2018-01-05 11:06:39
【问题描述】:

如何使用mgo 包创建(或确保)散列索引?

我需要一个与此等效的 go 代码:

>> db.collection.createIndex( { _id: "hashed" } )

我尝试过使用 runCommand,但只有 ‍createIndexes 命令需要 index specs 的列表。而且我不知道那是什么以及如何创建index specs

【问题讨论】:

  • 我的余生都需要免费啤酒。 ;) 我省钱。到目前为止,您尝试过什么?
  • @markus-w-mahlberg 我曾尝试使用 runCommand,但只有“createIndexes”命令需要“索引规范”列表。我不知道那是什么..

标签: mongodb go mgo


【解决方案1】:

您可以按照Collection.EnsureIndex 中的说明进行操作:

该 API 还支持其他类型的索引。这是一个例子:

index := Index{
    Key: []string{"$2d:loc"},
    Bits: 26,
}
err := collection.EnsureIndex(index)

上面的例子请求为“loc”字段创建一个“2d”索引。

所以基本上,你的格式是$<indexType>:<indexedField>,如下所示:

package main

import mgo "gopkg.in/mgo.v2"

const (
    db   = "so_hashed_idx"
    coll = "testcoll"
)

func main() {
    var s *mgo.Session
    var err error

    if s, err = mgo.Dial("127.0.0.1:27017"); err != nil {
        panic(err)
    }

    // An index spec is nothing more than a fancy word for the keys
    // or the key/value pairs handed over to the Key slice of the
    // Index type.
    idx := mgo.Index{
        Key: []string{"$hashed:_id"},
    }

    if err := s.DB(db).C(coll).EnsureIndex(idx); err != nil {
        panic(err)
    }
}

so_hashed_idx.testcoll 中构建并运行上述结果,显示其索引如下

> db.testcoll.getIndices()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "so_hashed_idx.testcoll"
    },
    {
        "v" : 1,
        "key" : {
            "_id" : "hashed"
        },
        "name" : "_id_hashed",
        "ns" : "so_hashed_idx.testcoll"
    }
]

【讨论】:

    【解决方案2】:

    runCommand 的回答:

    func createHashedIndex(session *mgo.Session, collectionName string, indexKey string){
        var result interface{}
        if err := session.Run(bson.D{
            {"createIndexes", collectionName},
            {"indexes", []bson.M{bson.M{"name": indexKey+"_hashed_index", "key": bson.M{indexKey: "hashed"}}}}}, &result); err != nil {
            fmt.Println("Create Index Error:", err.Error())
        } else {
            fmt.Println("Create Index:", result)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-26
      • 2017-01-13
      • 1970-01-01
      • 2022-10-25
      • 2011-09-20
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多