down_load1117 2014-07-06 05:02
浏览 233
已采纳

如何使用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!

  • 写回答

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
        }
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 ZYNQ7020双核FLAHS烧写的问题
  • ¥20 ue 5 中想要实现第一人称人物左右行走摆动的效果,摄像头只向右摆动一次(关键词-结点)
  • ¥15 钢岔管添加弹性约束模拟围岩作用
  • ¥15 AD9164瞬时带宽1.8G,怎么计算出来?
  • ¥15 鼠标右键,撤销删除 复制 移动,要怎样删除
  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数