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

报告相同问题?

悬赏问题

  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?