登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-05 21:36:36 449浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《如何为同名的嵌套字段创建文本索引》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我正在尝试在具有相同名称的 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 驱动程序的映射非常简单


正确答案


请注意,一个集合最多可以有一个文本索引.

如果您知道这一点并且想要创建一个涵盖 "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"),
}

今天关于《如何为同名的嵌套字段创建文本索引》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>