Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a text index in mongodb with golang and the mongo-go-driver?

Tags:

mongodb

go

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. How can I create a text index on two fields?

I know that I must use a thing as this:

opts := options.CreateIndexes().SetMaxTime(10 * time.Second)

idxFiles := []mongo.IndexModel{
    {
      Keys: bsonx.Doc{{"name": "text"}},
    },
  }

db.Collection("mycollection").Indexes().CreateMany(context, idx, opts)
like image 742
SaroVin Avatar asked Oct 19 '25 03:10

SaroVin


2 Answers

I have founded the solution:

    coll := db.Collection("test")
    index := []mongo.IndexModel{
        {
            Keys: bsonx.Doc{{Key: "name", Value: bsonx.String("text")}},
        },
        {
            Keys: bsonx.Doc{{Key: "createdAt", Value: bsonx.Int32(-1)}},
        },
    }

    opts := options.CreateIndexes().SetMaxTime(10 * time.Second)
    _, errIndex = coll.Indexes().CreateMany(context, index, opts)
    if err != nil {
        panic(errIndex)
    }
like image 77
SaroVin Avatar answered Oct 21 '25 19:10

SaroVin


From MongoDB indexes documentation I wrote a function to create an index for all types MongoDB supported.

func AddIndex(dbName string, collection string, indexKeys interface{}) error {
    db := getNewDbClient() // get clients of mongodb connection
    serviceCollection := db.Database(dbName).Collection(collection)
    indexName, err := serviceCollection.Indexes().CreateOne(mtest.Background, mongo.IndexModel{
        Keys: indexKeys,
    })
    if err != nil {
        return err
    }
    fmt.Println(indexName)
    return nil
}

mongodb single field index:

AddIndex("mydb", "mycollection", bson.M{"myfieldname": 1}) // to descending set it to -1

mongodb Compound index:

AddIndex("mydb", "mycollection", bson.D{{"myFirstField", 1},{"mySecondField", -1}}) // to descending set it to -1

mongodb Text index

AddIndex("mydb", "mycollection", bson.D{{"myFirstTextField", "text"},{"mySecondTextField", "text"}})
like image 29
ttrasn Avatar answered Oct 21 '25 19:10

ttrasn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!