如何用mgo包创建(或确保)散列索引?如何用mgo创建散列索引(golang)
我需要去的代码是等效采用这样的:
>> db.collection.createIndex({ _id: "hashed" })
我一直在使用runCommand尝试,但只有createIndexes
希望的index specs
list命令。而且我不知道那是什么以及我如何创建index specs
。
如何用mgo包创建(或确保)散列索引?如何用mgo创建散列索引(golang)
我需要去的代码是等效采用这样的:
>> db.collection.createIndex({ _id: "hashed" })
我一直在使用runCommand尝试,但只有createIndexes
希望的index specs
list命令。而且我不知道那是什么以及我如何创建index specs
。
你可以做到这一点作为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"
}
]
的回答其指数与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)
}
}
我需要免费的啤酒,余生。 ;)我省钱。你试过什么了? –
@ markus-w-mahlberg我尝试过使用runCommand,但只有“createIndexes”命令需要“索引规格”列表。我不知道那是什么.. – Mohsenasm