我正在尝试在具有相同名称的 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 驱动程序的映射非常简单
最佳答案
请注意,一个集合最多可以有一个 text index .
如果您知道这一点并且想要创建一个涵盖 "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"),
}
关于mongodb - 如何为同名的嵌套字段创建文本索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75193671/