如何使用全文搜索并在mongodb中对它们进行排序

时间:2020-02-26 14:53:26

标签: mongodb mongoose

我使用mongodb和mongoose从nodejs连接。 我的关键字集合:

keywords
{
  _id: { type: Schema.Types.ObjectId  },
  word: { type: String, index: true },
  rank: {type: Number}, // Rank is count of voting from users.
  source: {type: String},
  link: {type: Schema.Types.ObjectId, ref: 'Content'} // Link to contents collection
}

和内容收集

{
  _id: { type: Schema.Types.ObjectId  },
  title: { type: String },
  content: { type: String }
}

我的想法:

  1. 第1步:使用全文搜索找到匹配的关键字,排序方式 最接近的匹配,排名(按相同的最接近的匹配分组)
  2. 步骤2:获取链接(关键字的链接属性)以查找内容$ in 链接。

但是在步骤1进行排序时并不完全是这样。

我的代码:

// Get keywords
let indexes = await Keyword.aggregate([
  { $match: {
  $text: { $search: 'request query' }
}},
  { $limit: 100 },
  { $sort: { rank: -1, createdAt: -1 } }, // I want to sort by highest rank
  { $group: { _id: '$link' } },
  { $project: { link: 1 } }
]);

return await Content.find({
  _id: {
    $in: indexes.map((item) => {
      return item._id;
    })
  }
});

任何帮助我的想法。非常感谢!

2 个答案:

答案 0 :(得分:0)

为什么不使用单个集合?设置与索引相同的字段。有关索引关键字的查询只会查看索引以选择文档-它不会在搜索过程中打开文档。索引在文档外部单独存在。

看起来您出于索引搜索的原因正在实现拆分成两个集合,但是Mongodb在内部通过在索引中指定一个字段来为您实现此目的.....

答案 1 :(得分:0)

关键字设计并对该字段进行索引是一个很好的主意,并且将非常有效。无需在单独的文档中包含此字段,索引将解决该问题……在输入数据时将关键字字段放入​​其数据的文档中,并在可能的情况下将其保持在一起。