我在MonogDB中有如下事件对象:
{
"start": 2010-09-04T16:54:11.216Z,
"title":"Short descriptive title",
"description":"Full description",
"score":56
}
我需要查询三个参数:
时间窗口(事件
start
在两个日期之间)分数阈值(
score
为> x)title
和description
的全文本搜索有效解决此问题的正确方法是什么?我认为前两个是通过聚合完成的,但是我不确定文本搜索将如何考虑在内。
最佳答案
假设您的start
字段是date
类型(应该是),而不是string
,这是您要使用的基本组件。实际上,考虑到MongoDB日期的ISO 8601结构,基于字符串的比较也将同样有效。
// create your text index
db.collection.ensureIndex({
description: "text",
title: "text"
})
// optionally create an index on your other fields
db.collection.ensureIndex({
start: 1,
score: 1
})
x = 50
lowerDate = ISODate("2010-09-04T16:54:11.216Z") // or just the string part for string fields
upperDate = ISODate("2010-09-04T16:54:11.216Z")
// simple find to retrieve your result set
db.collection.find({
start: {
$gte: lowerDate, // depending on your exact scenario, you'd need to use $gt
$lte: upperDate // depending on your exact scenario, you'd need to use $lt
},
score: { $gt: x }, // depending on your exact scenario, you'd need to use $gte
$text: { // here comes the text search
$search: "descriptive"
}
})
但是,关于性能/索引有一个重要的话题需要理解,在这里有很好的记录:Combine full text with other index
这就是为什么我最初写“您想要玩的组件”的原因。因此,根据应用程序的其余部分,您可能需要创建不同的索引。