【问题标题】:How can I search in arrays of integers with a compound MongoDB Atlas search query?如何使用复合 MongoDB Atlas 搜索查询在整数数组中进行搜索?
【发布时间】:2021-01-18 05:42:09
【问题描述】:

我正在使用 MongoDB Atlas 的全文搜索功能帮助我查找类似文档,按分数排序。

我将我的收藏索引设置为“动态”。

我正在寻找文本字段中的相似之处,例如“名称”或“描述”,但我也想查看另一个字段“主题”,它存储主题的整数值 (id)。


示例:

假设我有一个参考文件如下:

{
 name: "test",
 description: "It's a glorious day!",
 thematic: [9, 3, 2, 33]
}

我希望我的搜索与主题字段中的这些int 匹配,并将它们的权重包含在分数计算中。

例如,如果我将我的参考文档与:

{
 name: "test2",
 description: "It's a glorious night!",
 thematic: [9, 3, 6, 22]
}

我想提高分数,因为主题字段与参考文档共享 93 值。


问题:

我应该使用什么search operator 来实现这一目标?我可以使用text 运算符输入字符串数组作为查询,但我不知道如何处理整数。

我应该采用另一种方法吗?喜欢将数组拆分为多个 compound.should.term 查询进行比较?


编辑

经过大量搜索,我找到了herehere

如果数值或日期值是数组的一部分,则 Atlas Search 无法索引它们。

在考虑更改对象的整个数据结构之前,我想确保没有变通方法。

例如,可以用custom analyzers 完成吗?

【问题讨论】:

    标签: mongodb search full-text-search mongodb-atlas mongodb-atlas-search


    【解决方案1】:

    我通过在我的收藏中添加触发器来解决它。每次插入或更新文档时,我都会更新 thematic 和其他类似字段对应项,例如_thematic,我存储整数的字符串值。然后我使用这个_thematic 字段进行搜索。

    这是一个演示它的示例代码:

    exports = function (changeEvent) {
    
    const fullDocument = changeEvent.fullDocument;
    const format = (itemSet) => {
        let rst = [];
        Object.keys(itemSet).forEach(item => rst.push(itemSet[item].toString()));
        return rst;
    };
    let setter = {      
        _thematic: fullDocument.thematic ? format(fullDocument.thematic) : [],      
    };
    const docId = changeEvent.documentKey._id;
    
    const collection = context.services.get("my-cluster").db("dev").collection("projects");
    
    const doc = collection.findOneAndUpdate({ _id: docId },
        { $set: setter });
    
    return;
    };
    

    我很确定它可以以更简洁的方式完成,所以如果有人发布它,我会将所选答案切换为她/他的。

    解决此问题的另一种方法是制作一个带有字符映射的自定义分析器,它将每个数字替换为其对应的字符串。我还没试过这个。见https://docs.atlas.mongodb.com/reference/atlas-search/analyzers/custom/#mapping

    欢迎替代品!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-01
      • 2015-06-29
      • 1970-01-01
      • 2021-12-26
      • 2021-04-22
      • 2014-06-10
      • 2020-02-01
      • 1970-01-01
      相关资源
      最近更新 更多