代码之家  ›  专栏  ›  技术社区  ›  Alexandre Justino

MongoDB文本按单词位置评分

  •  0
  • Alexandre Justino  · 技术社区  · 6 年前

    如何在MongoDB中设置文本搜索,以便在关键字最先出现的结果中获得更高的分数?

    例如,我现在正在做的是:

    db.product.aggregate(
      [
        { $match: { $text: { $search: "notebook acer" }, isAvailable: true } },
        { $sort: { score: { $meta: "textScore" } } },
        { $project: { searchName: 1, _id: 0, score: { $meta: "textScore" } } }
      ]
    )
    

    在我得到的结果中:

    {
        "searchName" : "Mochila para Notebook Acer",
        "score" : 1.25
    },
    {
        "searchName" : "Notebook Acer E5-471-36me Intel Core I3 1.90ghz 4gb Hdd 500gb Linux Hdmi",
        "score" : 1.0625
    }
    

    但我需要第二个结果排在第一位,因为关键字首先出现在索引字段中。

    有没有办法做到这一点?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Mauro Piccotti    6 年前

    我想你必须使用接线员 $indexOfCP ,您可以使用该词计算单词的位置,然后根据计算的位置进行排序。

    https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfCP/

    位置部分是这样的:

    db.product.aggregate(
       [
         { $project: { kwPosition: { $indexOfCP: [ "$searchName", "notebook acer" ] } } },
         { $match: { "kwPosition": {"$ne": -1} } },
         { $sort: { kwPosition: 1 } }
       ]
    )
    

    您可以组合这两种逻辑。