mongodb 上独特的复合文本索引

njL*_*jLT 3 indexing mongodb

f1, f2我已经在两个字段上创建了索引db.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
}
Run Code Online (Sandbox Code Playgroud)

当我插入两个文档时

db.test.insert({f1:"hello",f2:"there"})
db.test.insert({f1:"hello",f2:"there2"})
Run Code Online (Sandbox Code Playgroud)

我收到重复密钥错误

"E11000 duplicate key error collection: test.test index: f1_text_f2_text dup key: { : \"hello\", : 1.1 }"
Run Code Online (Sandbox Code Playgroud)

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

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

gly*_*ing 5

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

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

db.test.createIndex({"f1": 1, "f2": 1}, {unique: true})
Run Code Online (Sandbox Code Playgroud)

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

db.test.insert({f1:"hello",f2:"there"})
db.test.insert({f1:"hello",f2:"there1"})
db.test.insert({f1:"hello",f2:"there2"})
Run Code Online (Sandbox Code Playgroud)

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

db.test.insert({f1:"hello",f2:"there"})
Run Code Online (Sandbox Code Playgroud)

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

  • f1促进涵盖和的“快速”文本匹配f2
  • 强制执行唯一f1f2

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

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