Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a text index in mongodb with golang and the mgo library?

Tags:

mongodb

go

mgo

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!

like image 630
Ryan Epp Avatar asked Jul 06 '14 05:07

Ryan Epp


People also ask

Is it possible to index text with MongoDB?

MongoDB provides text indexes to support text search queries on string content. text indexes can include any field whose value is a string or an array of string elements. A collection can only have one text search index, but that index can cover multiple fields.

How do I create a text index?

In MongoDB, we can create text indexes using db. collectionName. createIndex() method. So, to index a field that contains either string or an array of string elements, pass a document in the createIndex() method that contains the field and the string literal(i.e., “text”).

Which is the method used to create index in MongoDB?

Creating an Index in MongoDB is done by using the “createIndex” method.


1 Answers

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
    }
]
like image 72
Neil Lunn Avatar answered Oct 17 '22 19:10

Neil Lunn