
php小编草莓将为大家介绍如何在同名的嵌套字段中创建文本索引。在数据库中,我们常常会遇到需要在嵌套字段中进行搜索和查询的情况。然而,当存在多个同名的嵌套字段时,创建文本索引就会变得复杂。本文将详细讲解如何应对这个问题,为大家提供解决方案。接下来,我们将一步步引导您完成这个过程,让您轻松地为同名的嵌套字段创建文本索引。
我正在尝试在具有相同名称的 2 个嵌套字段上创建复合文本索引。我尝试这样做的原因是我可以在两个字段上使用 mongo 执行全文搜索。
{
"createdat": "2023-01-20t18:39:45.551z",
"id": "63cadff13fc409d0b026f219",
"userid": "63c13a9ba4c921b78e7d1a3a",
"question": {
"statement": "what is the atomic number of potassium?",
"fileurl": "http://localhost:4000/media/90152d8363424e688ad6e9505194a818.jpg",
"mediatype": 2
},
"answer": {
"statement": "19"
}
}
从示例中可以看到,question 和 answer 具有相同的嵌套字段 statement。 我正在尝试为问题和答案语句建立文本索引
textsearchindexmodel := mongo.indexmodel{
keys: bson.d{
{value: "question.statement", key: "text"},
{value: "answer.statement", key: "text"},
},
options: options.index().setname("textsearchindex"),
}
这不起作用并产生了此错误:
Failed to create index for flashcard collection:....caused by :: The field 'text' appears multiple times in the index key pattern
p.s:如果您不熟悉 go,您也可以上传它在 mongodb 上的方式,因为到 mongodb go 驱动程序的映射非常简单
请注意,一个集合最多可以有一个文本索引.
如果您知道这一点并且想要创建一个涵盖 "question.statement" 和 "answer.statement" 的文本索引,那么这是可行的。
您的错误是索引规范: bson .d 表示一个文档,一个有序的属性列表(名称-值对)。这是 bson.e 的一部分,其中 bson. e 是:
type e struct {
key string
value interface{}
}key 是属性的名称,value 是该属性的值。所以你把它倒过来了,它应该是:
textSearchIndexModel := mongo.IndexModel{
Keys: bson.D{
{Key: "question.statement", Value: "text"},
{Key: "answer.statement", Value: "text"},
},
Options: options.Index().SetName("textSearchIndex"),
}以上就是如何为同名的嵌套字段创建文本索引的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号