【问题标题】:MongoDB: sorting by $meta: "textScore" returns no results among documents generated from original $text searchMongoDB:按 $meta 排序:“textScore”在原始 $text 搜索生成的文档中不返回任何结果
【发布时间】:2020-02-25 23:59:44
【问题描述】:

我正在使用 MongoDB 和 Mongoose 创建一个包含业务和评论的网站。评论上有文字索引,用户可以根据相应评论中的文字搜索商家。

  1. 结果应按平均 $meta: "textScore" 排序。

  2. 它们还应附有评价中 $meta 最高的 sn-p:“textScore”。

问题出现在搜索的第二部分:一些商家似乎没有匹配的评论。

我的查询结构如下:

  1. 使用 $text 搜索评论,按业务分组,并按平均“textScore”排序:
Review
    .aggregate([ 
      { $match: { $text: { $search: query } } },
      { $group: { _id: "$businessId", avgScore: { $avg: { $meta: "textScore" } } } },
      { $sort: { avgScore: -1 } }
    ])
  1. 在第一次查询的回调中,找到对应的商家:
 Business
     .find( { id: { $in: resultIds } } )
  1. 在最后的回调中,我搜索每个商家的最佳匹配评论:
Review.find({ 
      businessId: business.id, 
      $text: { $search: query }, 
      score: { $meta: "textScore" }
    })
    .sort( { score: { $meta: "textScore" } } )
    .limit(1)

前两个步骤工作正常。最后一步通常有效,但有时排名最低的企业似乎没有匹配的评论。

最初的 $text 搜索生成的商家如何在后面的 $text 搜索中不返回任何结果?

编辑:后续问题 我可以使用 Mongoose .populate() 实现相同的查询吗?我在下面的代码中遇到了类似的问题:

Business
    .find({ _id: { $in: searchResults} })
    .populate({
      path: "reviews",
      match: { $text: { $search: query } },
      select: { score: { $meta: "textScore" } },
      options: { sort: { score: { $meta: "textScore" } }, limit: 1 }
    })

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    在您的find 调用中,您需要提供score: { $meta: "textScore" } 作为单独的投影对象参数,而不是将其包含在您的查询对象中:

    Review.find({ 
          businessId: business.id, 
          $text: { $search: query }      
        }, {
          score: { $meta: "textScore" }
        })
        .sort( { score: { $meta: "textScore" } } )
        .limit(1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 2021-11-12
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      相关资源
      最近更新 更多