2017-07-29 151 views
1

如何用mgo包創建(或確保)散列索引?如何用mgo創建散列索引(golang)

我需要去的代碼是等效採用這樣的:

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

我一直在使用runCommand嘗試,但只有createIndexes希望的index specs list命令。而且我不知道那是什麼以及我如何創建index specs

+1

我需要免費的啤酒,餘生。 ;)我省錢。你試過什麼了? –

+0

@ markus-w-mahlberg我嘗試過使用runCommand,但只有「createIndexes」命令需要「索引規格」列表。我不知道那是什麼.. – Mohsenasm

回答

2

你可以做到這一點作爲Collection.EnsureIndex記載:

其他類型的指數也通過該API支持。下面是一個例子:

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

上面的示例請求「2D」索引的創建,爲「LOC」字段。

所以基本上,你有格式$<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" 
    } 
] 
1

的回答其指數與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) 
    } 
}