如何使用 golang 和 mongo-go-driver 在 mongodb 中创建文本索引?

我正在尝试对集合进行全文搜索,但为了做到这一点,我需要创建一个文本索引。如何在两个字段上创建文本索引?


我知道我必须使用这样的东西:


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


idxFiles := []mongo.IndexModel{

    {

      Keys: bsonx.Doc{{"name": "text"}},

    },

  }


db.Collection("mycollection").Indexes().CreateMany(context, idx, opts)


达令说
浏览 230回答 5
5回答

慕雪6442864

我已经找到了解决方案:    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)    }

人到中年有点甜

我编写了一个函数来MongoDB indexes documentation为 MongoDB 支持的所有类型创建索引。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单字段索引:AddIndex("mydb", "mycollection", bson.M{"myfieldname": 1}) // to descending set it to -1mongodb 复合索引:AddIndex("mydb", "mycollection", bson.D{{"myFirstField", 1},{"mySecondField", -1}}) // to descending set it to -1mongodb 文本索引AddIndex("mydb", "mycollection", bson.D{{"myFirstTextField", "text"},{"mySecondTextField", "text"}})

Smart猫小萌

要使用官方 mongo go 驱动程序创建索引,您可以使用以下代码:// create IndexindexName, 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)您可以将其替换为您想要的索引配置。

慕虎7371278

您可以使用自定义选项和权重简单地创建文本索引,如下所示: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)

德玛西亚99

具有地理空间 (2dsphere)、文本和单个字段。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)
打开App,查看更多内容
随时随地看视频慕课网APP