【问题标题】:Mongo $text query: return docs "starting with" string before othersMongo $text查询:在其他人之前返回文档“以”字符串开头
【发布时间】:2017-07-17 01:19:20
【问题描述】:

假设我有一个 mongo 集合,在 itemName 字段上有一个 text index,其中包含这 3 个文档:

{
    _id: ...,
    itemName: 'Mashed carrots with big carrot pieces',
    price: 1.29
},
{
    _id: ...,
    itemName: 'Carrot juice',
    price: 0.79
},
{
    _id: ...,
    itemName: 'Apple juice',
    price: 1.49
}

然后我执行如下查询:

db.items.find({ $text: { $search: 'Car' } }, { score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } );

如何强制 mongo 返回以“Car”开头的文档(不区分大小写)返回任何其他在 itemName 某处也包含“Car”的文档之前字符串?

所以我想按以下顺序检索文档:

[
    {..., itemName: 'Carrot Juice', ...},
    {..., itemName: 'Mashed carrots with big carrot pieces', ...}
]

当然,这是在搜索功能中使用的,因此在显示之后的任何其他项目之前,向用户显示他的搜索字符串开头的项目是完全有意义的。

直到现在我都在使用标准的正则表达式,但这里的性能当然要差得多! + 因为我必须搜索不区分大小写,根据文档,正常的正则表达式根本不使用任何索引?!

编辑:

另外,有时$text 的行为很奇怪。 例如,我有大约 10-15 个项目,其中itemName 以单词“Zwiebel”开头。 这个查询

db.items.find({ $text: { $search: "Zwiebel" }, supplier_id: 'iNTJHEf5YgBPicTrJ' }, { score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } );

像一个魅力一样工作并返回所有这些文档,而这个查询

db.items.find({ $text: { $search: "Zwie" }, supplier_id: 'iNTJHEf5YgBPicTrJ' }, { score: { $meta: "textScore" } }).sort( { score: { $meta: "textScore" } } );

不返回任何东西!只需将$search 中的“Zwiebel”更改为“Zwie”即可。

我真的不明白这怎么可能?!

最好的,P

【问题讨论】:

  • 按textScore排序有什么作用?
  • 请检查我的编辑! :-) 谢谢!
  • @PatrickDaVader 查看我的编辑
  • @PatrickDaVader 全文搜索不适用于子字符串匹配 - 如果“Zwei”和“Zweibel”是完全不同的词,那么搜索“Zwei”应该匹配带有“Zweibel”的记录,即您所看到的是正确的行为。

标签: mongodb indexing fulltext-index


【解决方案1】:

一种解决方案是使用 MongoDB 3.4 中引入的 $indexOfCP 运算符

该运算符返回一个字符串在另一个字符串中出现的索引,如果没有出现则返回-1

它是如何工作的:

  1. 使用正则表达式过滤掉所有不包含“汽车”的文档:/car/gi(不区分大小写)
  2. 创建一个名为index的字段,它将'car'的索引存储在itemName
  3. index 字段中对文档进行排序

查询将如下所示:

db.items.aggregate([
   {
      $match:{
         itemName:/car/gi
      }
   },
   {
      $project:{
         index:{
            $indexOfCP:[
               {
                  $toLower:"$itemName"
               },
               "car"
            ]
         },
         price:1,
         itemName:1
      }
   },
   {
      $sort:{
         index:1
      }
   }
])

这会返回:

{ "_id" : 2, "itemName" : "Carrot juice", "price" : 0.79, "index" : 0 }
{ "_id" : 1, "itemName" : "Mashed carrots with big carrot pieces", "price" : 1.29, "index" : 7 }

在线试用:mongoplayground.net/p/FqqCUQI3D-E

编辑:

对于$text索引的行为,这是完全正常的

文本索引使用分隔符标记文本(默认分隔符是空格和标点符号)。它只能用于搜索整个世界,因此它不适用于单词的子部分

来自mongodb text index documentation

$text 将使用空格和大多数 标点符号作为分隔符,并对所有此类标记执行逻辑或 在搜索字符串中。

【讨论】:

  • 感谢您的回复!还请检查我在 OP 中的编辑!谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-03-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多