down_load1117
2014-07-06 05:02
浏览 153

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

I'm trying to do a full text search on a collection, but in order to do that I need to create a text index (http://docs.mongodb.org/manual/tutorial/create-text-index-on-multiple-fields/)

The mgo library provides an EnsureIndex() function however, it only accepts a slice of strings as a key. I tried just writing the index out as a string: { name: "text", about: "text" } and passing it to that function but it didn't work.

I've also managed to manually create the index in the mongo shell but I'd really like to have the index documented in my go project. Is this possible? Thanks in advance!

图片转代码服务由CSDN问答提供 功能建议

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

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

我还设法在mongo shell中手动创建了索引,但是我真的很想在我的go项目中记录该索引。 这可能吗? 预先感谢!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanlun2827 2014-07-07 01:55
    已采纳

    This is supported in the driver. All you need to do is define your fields to be indexed as "text" as in $text:field.

    In a complete listing:

    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)
      }
    
    }
    

    Which when viewed from the mongo shell will give:

    > 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
        }
    ]
    
    点赞 评论

相关推荐 更多相似问题