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

Viewed 7881

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)
5 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)
    }

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"}})

To create indexes using the official mongo go driver you can use the following code:

// create Index
indexName, err := c.Indexes().CreateOne(
        context.Background(),
        mongo.IndexModel{
                Keys: bson.M{
                        "time": 1,
                },
                Options: options.Index().SetUnique(true),
        },
)
if err != nil {
        log.Fatal(err)
}
fmt.Println(indexName)

You can replace it with your desired index configuration.

With Geospatial (2dsphere), text and single field.

models := []mongo.IndexModel{
    {
        Keys: bsonx.Doc{{Key: "username", Value: bsonx.String("text")}},
    },
    {
        Keys: bsonx.Doc{{Key: "NearCoordinates", Value: bsonx.String("2dsphere")}},
    },
    {
        Keys: bsonx.Doc{{Key: "password", Value: bsonx.Int32(1)}},
    },
}
opts := options.CreateIndexes().SetMaxTime(20 * time.Second)
_, err := collectionName.Indexes().CreateMany(context.Background(), models, opts)

You can simply create text index with custom options and weights as follows:

mod := mongo.IndexModel{
    Keys: bson.D{
        {"title", "text"},
        {"description", "text"},
    },
    // create UniqueIndex option
    Options: options.Index().SetWeights(bson.D{
        {"title", 9},
        {"description", 3},
    }),
}

collection.Indexes().CreateOne(context.Background(), mod)
Related