【发布时间】:2015-03-15 07:08:05
【问题描述】:
我有以下文档结构。
{
content: 'cat dog bird',
uid: <another_unique_id>
cid: <another_unique_id>
}
我正在尝试搜索此集合并希望按uid 和/或cid 过滤结果。我想运行的一些查询:
1) db.mycollection.find({uid: '1', cid: '2', $text: {$search: 'cat'}});
2) db.mycollection.find({cid: '2', $text: {$search: 'cat'}});
3) db.mycollection.find({uid: '1', $text: {$search: 'cat'}});
4) db.mycollection.find({$text: {$search: 'cat'}});
//etc...
我试图创建一个像这样的复合索引
db.mycollection.ensureIndex({uid: 1, cid: 1, content: 'text'});
但它仅适用于查询 #1,如果我不提供其中一个字段,我会收到以下错误。
planner returned error: failed to use text index to satisfy $text query
(if text index is compound, are equality predicates given for all prefix fields?)
我尝试过的其他事情:
在
uid/cid上创建非复合索引 = 会导致大量文档被扫描-
将
uidcid索引移到文本索引之后,即db.mycollection.ensureIndex({content: 'text', uid: 1, cid: 1});与 #1 相同,未使用 uid 和 cid 索引。
关于我正在尝试的信息: http://docs.mongodb.org/manual/tutorial/limit-number-of-items-scanned-for-text-search/
我是否遗漏了什么,或者这对于使用索引的 MongoDB 来说是不可能的?
【问题讨论】:
-
不确定这是否可行。阅读:docs.mongodb.org/manual/tutorial/…。如果查询的字段只是索引的一部分,则查询不能使用索引。设计有关您实际使用情况的索引。可能检查索引交集。
-
我正在查看 stackoverflow.com/questions/24257390/… 即在
contentuid和cid的 3 个字段上创建文本索引,但我还没有找到一种方法来使用它进行查询还没有。 -
索引的声明顺序很重要。在您的第一个声明中,仅当您的查询使用 uid 或 (uid and cid) 或 (uid and cid and text) 时才会使用索引。
标签: mongodb mongodb-query