dongshuohuan5291 2017-07-29 12:41
浏览 210
已采纳

如何通过mgo(golang)创建哈希索引

How can I create (or ensure) hashed index with mgo package?

I need a go code to be equivalent with this:

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

I have tried using runCommand but there is only ‍createIndexes command that want a list of index specs. And I have no idea what is that and how I can create index specs.

  • 写回答

2条回答 默认 最新

  • dtmbc1606 2017-07-30 11:53
    关注

    You can do it as documented at Collection.EnsureIndex:

    Other kinds of indexes are also supported through that API. Here is an example:

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

    The example above requests the creation of a "2d" index for the "loc" field.

    So basically, you have the format $<indexType>:<indexedField>, as shown below:

    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)
        }
    }
    

    Building and running the above results in so_hashed_idx.testcoll showing its indices as follows

    > 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"
        }
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题