Low*_*wie 5 search autocomplete mongodb mongodb-atlas mongodb-atlas-search
在 MongoDB Atlas 搜索的文档中,它对autocomplete运算符做了以下说明:
query:要搜索的一个或多个字符串。如果字符串中有多个术语,Atlas Search 还会分别为字符串中的每个术语查找匹配项。
对于text操作员来说,同样的事情也适用:
query:要搜索的一个或多个字符串。如果字符串中有多个术语,Atlas Search 还会分别为字符串中的每个术语查找匹配项。
对我来说,单独匹配每个术语似乎很奇怪。我们需要在应用程序中进行多次搜索,对于每次搜索,我们预计您输入的单词越多,结果就越少,而不是更多。
示例:搜索“John Doe”时,我期望只包含“John”和“Doe”的结果。目前,我得到与“John”或“Doe”匹配的结果。
使用 MongoDB Atlas Search 是不可能的,还是我做错了什么?
更新 目前,我已经通过在空格('')上拆分搜索词并将每个单独的关键字添加到单独的必须子子句(使用复合运算符)来解决它。但是,如果一个关键字只有一个字符,则搜索查询将不再返回任何结果。考虑到这一点,我将包含一个字符的关键字与包含多个字符的关键字分开。下面的代码片段有效,但为此我需要在每个文档上保存两个生成的字段:
const must = [];
const searchTerms = 'John D'.split(' ');
for (let i = 0; i < searchTerms.length; i += 1) {
    if (searchTerms[i].length === 1) {
      must.push({
        regex: {
          path: 'searchArray',
          query: `${searchTerms[i].toUpperCase()}.*`,
        },
      });
    } else if (searchTerms[i].length > 1) {
      must.push({
        autocomplete: {
          query: searchTerms[i],
          path: 'searchString',
          fuzzy: {
            maxEdits: 1,
            prefixLength: 4,
            maxExpansions: 20,
           },
         },
       });
    }
}
db.getCollection('someCollection').aggregate([
  {
    $search: {
      compound: { must },
    },
  },
]).toArray();
更新 2 - 意外行为的完整示例
使用以下文档创建集合:
db.getCollection('testing').insertMany([{
    "searchString": "John Doe ExtraTextHere"
    }, {
    "searchString": "Jane Doe OtherName"
    }, {
    "searchString": "Doem Sarah Thisistestdata"
    }])
在此集合上创建搜索索引“default”:
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "searchString": {
        "type": "autocomplete"
      }
    }
  }
}
执行以下查询:
db.getCollection('testing').aggregate([
  {
    $search: {
      autocomplete: {
        query: "John Doe",
        path: 'searchString',
        fuzzy: {
          maxEdits: 1,
          prefixLength: 4,
          maxExpansions: 20,
        },
      },
    },
  },
]).toArray();
当用户搜索“John Doe”时,此查询将返回路径“searchString”中包含“John”或“Doe”的所有文档。在此示例中,这意味着所有 3 个文档。用户输入的单词越多,返回的结果就越多。这不是预期的行为。我希望更多的单词匹配更少的结果,因为搜索词变得更加精确。
标记化策略edgeGram可能更适合您的用例,因为它从左到右工作。
尝试从文档中获取这个索引定义:
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "searchString": [
        {
          "type": "autocomplete",
          "tokenization": "edgeGram",
          "minGrams": 3,
          "maxGrams": 10,
          "foldDiacritics": true
        }
      ]
    }
  }
}
另外,添加将查询子句从“must”更改为“filter”。这将排除不包含所有标记的文档。