在 Golang 中使用 MongoDB 对 text 字段建立索引可以通过以下步骤实现:
1. 在建立 MongoDB 连接时设置 textSearchEnabled 参数为 true,开启文本搜索功能:
opts := options.Client().ApplyURI("mongodb://localhost:27017").SetDirect(true)
opts.Set("textSearchEnabled", true)
client, err := mongo.Connect(context.Background(), opts)
2. 在集合创建时,使用 CreateIndexOptions 结构体中的 TextDefaultLanguage 字段指定分词器的默认语言,使用 TextIndexVersion 字段指定索引版本号:
collection := client.Database("mydb").Collection("mycollection")
indexes := []mongo.IndexModel{
{
Keys: bson.D{{"text", "text"}},
Options: options.Index().
SetTextIndexVersion(3).
SetDefaultLanguage("english"),
},
}
if _, err := collection.Indexes().CreateMany(context.Background(), indexes); err != nil {
log.Fatalf("Failed to create indexes: %s", err)
}
3. 在查询时,使用 $text 操作符指定 text 字段和搜索关键词:
q := bson.M{"$text": bson.M{"$search": "golang"}}
cur, err := collection.Find(context.Background(), q)
注意,在建立 text 索引后,需要使用文本搜索指令来查询,而不能使用 find 或 findOne 等操作。
以上就是在 Golang 中使用 MongoDB 对 text 字段建立索引,并进行模糊搜索的步骤。