我正在尝试对集合进行全文搜索,但为了做到这一点,我需要创建一个文本索引(
http://docs.mongodb.org/manual/tutorial/create-text-index-on-multiple-fields/)
mgo库提供了EnsureIndex()函数,但它只接受一片字符串作为键.我尝试将索引写成字符串:{name:“text”,about:“text”}并将其传递给该函数但它不起作用.
我还设法在mongo shell中手动创建索引,但我真的想在我的go项目中记录索引.这可能吗?提前致谢!
驱动程序支持此功能.您需要做的就是将您的字段定义为“text”,如$text:field中所示.
原文链接:https://www.f2er.com/go/186923.html在完整的列表中:
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 } ]