You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue+Mongoose环境下加泰罗尼亚语多字段搜索引擎实现求助

问题:实现支持加泰罗尼亚语的Mongoose搜索引擎

需求说明

我基于Vue和Mongoose开发项目,需要实现适配加泰罗尼亚语的搜索引擎,目标集合包含以下字段:Question、Answer、Alternative answer、Comment,需满足两个核心要求:

  1. 多词搜索时,仅返回所有搜索词都出现在任意字段中的记录;
  2. 带引号的搜索为精确匹配,无引号则为包含匹配,必须区分重音、大小写及变音符号。

预期搜索效果

  • 输入Guardiola Messi,返回同时包含这两个词的记录;
  • 输入"Eufór",返回精确匹配该字符串的结果;输入Eufór,返回包含该字符序列的词(如euforia等)。

当前困境

尝试过MongoDB的$text查询和正则拼接查询,均未达到预期效果。当前核心问题是:正则无法正确匹配独立单词,包括句首、句尾、带标点的场景。

已尝试的代码方案

方案1:使用MongoDB $text查询

$match: {
    $text: {
        $search: filterBy,
        $caseSensitive: caseSensitive == "true",
        $diacriticSensitive: diacriticSensitive == "true",
    },
},

方案2:正则拼接查询

构建强制词的AND查询条件

mandatoryWords.forEach((md) => {
    andQuery.push({
        $or: [
            {
                Question: {
                    $regex: md,
                    $options: "i",
                },
            },
            {
                Answer: {
                    $regex: md,
                    $options: "i",
                },
            },
            {
                Alternative_answer: {
                    $regex: md,
                    $options: "i",
                },
            },
            {
                Comment: {
                    $regex: md,
                    $options: "i",
                },
            },
        ],
    });
});

构建可选词的OR查询条件

let orQuery = [];
filterWords.forEach((fw) => {
    orQuery.push(
        {
            Question: {
                $regex: fw,
                $options: "i",
            },
        },
        {
            Answer: {
                $regex: fw,
                $options: "i",
            },
        },
        {
            Alternative_answer: {
                $regex: fw,
                $options: "i",
            },
        },
        {
            Comment: {
                $regex: fw,
                $options: "i",
            },
        },
    );
});

组合最终查询条件

// 检查是否同时存在强制和可选条件
if (andQuery.length > 0 && orQuery.length > 0) {
    search = {
        $match: {
            $and: [
                ...andQuery, // 加入所有强制条件
                { $or: orQuery }, // 加入至少包含一个可选词的条件
            ],
        },
    };
} else if (andQuery.length > 0) {
    // 仅存在强制条件
    search = {
        $match: {
            $and: andQuery,
        },
    };
} else if (orQuery.length > 0) {
    // 仅存在可选条件
    search = {
        $match: {
            $or: orQuery,
        },
    };
}

内容的提问来源于stack exchange,提问作者Argoitz Estebanez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 05:55:31