如何使用复合 MongoDB Atlas 搜索查询在整数数组中进行搜索?

How can I search in arrays of integers with a compound MongoDB Atlas search query?

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

我将 collection 索引设置为“动态”。

我正在寻找文本字段中的相似之处,例如“名称”或“描述”,但我还想查看另一个字段“专题”,它存储专题的整数值 (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 查询?


编辑:

经过大量搜索,我找到了这个 here and here:

Atlas Search cannot index numeric or date values if they are part of an array.

在考虑更改 objects 的整个数据结构之前,我想确保没有解决方法。

比如custom analyzers可以吗?

我通过向 collection 添加触发器解决了这个问题。每次插入或更新文档时,我都会更新 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;
};

我很确定它可以用更简洁的方式完成,所以如果有人 post 它,我会将所选答案切换为 her/his。

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

欢迎选择!