如何使用mgo(golang)创建哈希索引

huangapple go评论94阅读模式
英文:

How to create hashed index by mgo (golang)

问题

你可以使用mgo包来创建(或确保)哈希索引。以下是相当于你提供的代码的Go代码:

index := mgo.Index{
    Key:        []string{"hashed:_id"},
    Background: true,
}

err := collection.EnsureIndex(index)
if err != nil {
    // 处理错误
}

这段代码使用EnsureIndex方法来创建哈希索引。Key字段指定要创建索引的键,hashed:_id表示要对_id字段进行哈希索引。Background字段设置为true表示在后台创建索引。

请确保在使用此代码之前已经正确导入了mgo包,并且已经建立了与MongoDB的连接。

英文:

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.

答案1

得分: 3

你可以按照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)
    }

    // 索引规范只是一个花哨的词,用于将键或键/值对传递给Index类型的Key切片。
    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"
    }
]
英文:

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"
    }
]

答案2

得分: 2

使用runCommand的答案:

func createHashedIndex(session *mgo.Session, collectionName string, indexKey string) {
    var result interface{}
    if err := session.Run(bson.D{
        {"runCommand", collectionName},
        {"command", []bson.M{bson.M{"name": indexKey+"_hashed_index", "key": bson.M{indexKey: "hashed"}}}}}, &result); err != nil {
        fmt.Println("创建索引错误:", err.Error())
    } else {
        fmt.Println("创建索引:", result)
    }
}
英文:

An answer with 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)
	}
}

huangapple
  • 本文由 发表于 2017年7月29日 20:41:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/45389410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定