如何使用golang和mgo库在mongodb中创建文本索引?
发布时间:2020-12-16 19:23:48 所属栏目:大数据 来源:网络整理
导读:我正在尝试对集合进行全文搜索,但为了做到这一点,我需要创建一个文本索引( http://docs.mongodb.org/manual/tutorial/create-text-index-on-multiple-fields/) mgo库提供了EnsureIndex()函数,但它只接受一片字符串作为键.我尝试将索引写成字符串:{name:“t
我正在尝试对集合进行全文搜索,但为了做到这一点,我需要创建一个文本索引(
http://docs.mongodb.org/manual/tutorial/create-text-index-on-multiple-fields/)
mgo库提供了EnsureIndex()函数,但它只接受一片字符串作为键.我尝试将索引写成字符串:{name:“text”,about:“text”}并将其传递给该函数但它不起作用. 我还设法在mongo shell中手动创建索引,但我真的想在我的go项目中记录索引.这可能吗?提前致谢!
驱动程序支持此功能.您需要做的就是将您的字段定义为“text”,如$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 } ] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |