【问题标题】:How do I create a text index in mongodb with golang and the mgo library?如何使用 golang 和 mgo 库在 mongodb 中创建文本索引?
【发布时间】:2014-08-26 21:20:14
【问题描述】:

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

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

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

【问题讨论】:

    标签: mongodb go mgo


    【解决方案1】:

    驱动程序支持此功能。您需要做的就是将要索引的字段定义为“文本”,如$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)
      }
    
    }
    

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

    【讨论】:

      猜你喜欢
      • 2018-01-05
      • 1970-01-01
      • 2012-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多