mongodb - 如何为同名的嵌套字段创建文本索引

标签 mongodb go mongo-go

我正在尝试在具有相同名称的 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"
    }
}

从示例中可以看出,questionanswer 都有相同的嵌套字段 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/

相关文章:

go - 计算预定义数字类型之外的大数

amazon-web-services - 如何使用 golang 从 AWS S3 下载

http - Google App Engine Go 对慢速页面的 HTTP 请求

mongodb - mongo-go如何使用arrayFilter在 "array of objects inside array of objects"中查找elem

mongodb - 将字符串 slice 转换为 BSON 数组

mongodb - MongoDB 文档中 "Dynamic schema supports fluent polymorphism"的含义

node.js - Mongoose 聚合查询跳过 getter

mongodb - 在 docker-compose 上使用用户密码配置 graylog mongodb

javascript - asnyc() 不会在 ssh 和 mongoose 中的代码末尾退出

mongodb - Mongo go 驱动的 DocumentCount 不支持 $nearSphere