【问题标题】:unique compound text indexes on mongodbmongodb 上的唯一复合文本索引
【发布时间】:2017-09-05 13:57:48
【问题描述】:

我在 f1, f2db.test.createIndex({"f1":"text","f2":"text"},{unique:true}) 的两个字段上创建了索引

{
    "v" : 2,
    "unique" : true,
    "key" : {
        "_fts" : "text",
        "_ftsx" : 1
    },
    "name" : "f1_text_f2_text",
    "ns" : "test.test",
    "weights" : {
        "f1" : 1,
        "f2" : 1
    },
    "default_language" : "english",
    "language_override" : "language",
    "textIndexVersion" : 3
}

当我插入两个文档时

db.test.insert({f1:"hello",f2:"there"})
db.test.insert({f1:"hello",f2:"there2"})

我收到重复键错误

"E11000 duplicate key error collection: test.test index: f1_text_f2_text dup key: { : \"hello\", : 1.1 }"

但是db.test.insert({f1:"hello2",f2:"there"}) 有效。

复合文本索引不应该像常规复合索引那样工作吗?

【问题讨论】:

    标签: mongodb indexing


    【解决方案1】:

    您确定要一个唯一的文本索引吗?

    如果您创建标准复合索引:

    db.test.createIndex({"f1": 1, "f2": 1}, {unique: true})
    

    那么下面的插入都会成功:

    db.test.insert({f1:"hello",f2:"there"})
    db.test.insert({f1:"hello",f2:"there1"})
    db.test.insert({f1:"hello",f2:"there2"})
    

    然后此插入将失败并显示E11000 duplicate key error collection

    db.test.insert({f1:"hello",f2:"there"})
    

    您不必为了索引字符串字段而创建文本索引。 text index 在支持文本搜索方面具有非常特殊的作用,但并非所有字符串搜索都需要文本索引。所以,如果你必须...

    • 促进涵盖f1f2 的“快速”文本匹配
    • f1f2 之间强制执行唯一性

    ...那么我怀疑您需要创建两个索引:

    • db.test.createIndex({"f1":"text", "f2":"text"})
    • db.test.createIndex({"f1": 1, "f2": 1}, {unique: true})

    【讨论】:

    • 我不需要文本索引,标准索引适用于我的用例,但我开始使用文本索引(因为我阅读了一些 stackoverflow 讨论而不是文档),我只是想知道为什么它不尊重复合索引的预期行为。官方文档在文本索引页面上提到了复合索引,并且没有任何地方声明不应期望与标准复合索引具有相同的行为(仅提供排序方向)。
    • 昨天偶然发现了同样的问题。通过将两个字段之一切换为 ASCENDING 而不是 TEXT 来修复它。仍然无法理解为什么当两个字段都有 TEXT 索引时它会以这种方式运行?
    猜你喜欢
    • 1970-01-01
    • 2012-03-24
    • 2020-09-22
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    相关资源
    最近更新 更多