如何使用golang和mgo库在mongodb中创建文本索引?

Rya*_*Epp 8 go mongodb mgo

我正在尝试对集合进行全文搜索,但为了做到这一点,我需要创建一个文本索引(http://docs.mongodb.org/manual/tutorial/create-text-index-on-多场/)

mgo库提供了一个EnsureIndex()函数,但它只接受一段字符串作为键.我尝试将索引写为字符串:{ name: "text", about: "text" }并将其传递给该函数,但它不起作用.

我还设法在mongo shell中手动创建索引,但我真的想在我的go项目中记录索引.这可能吗?提前致谢!

Nei*_*unn 16

驱动程序支持此功能.您需要做的就是将要编入索引的字段定义为"文本",如下所示$text:field.

在完整列表中:

import (
  "labix.org/v2/mgo"
)

func main() {

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

  defer session.Close()

  session.SetMode(mgo.Monotonic, true)

  c := session.DB("test").C("texty")

  index := mgo.Index{
    Key: []string{"$text:name", "$text:about"},
  }

  err = c.EnsureIndex(index)
  if err != nil {
    panic(err)
  }

}
Run Code Online (Sandbox Code Playgroud)

从mongo shell查看时会给出:

> db.texty.getIndices()
[
    {
            "v" : 1,
            "key" : {
                    "_id" : 1
            },
            "name" : "_id_",
            "ns" : "test.texty"
    },
    {
            "v" : 1,
            "key" : {
                    "_fts" : "text",
                    "_ftsx" : 1
            },
            "name" : "name_text_about_text",
            "ns" : "test.texty",
            "weights" : {
                    "about" : 1,
                    "name" : 1
            },
            "default_language" : "english",
            "language_override" : "language",
            "textIndexVersion" : 2
    }
]
Run Code Online (Sandbox Code Playgroud)