定义
wildcardwildcard操作符在搜索字符串中使用可匹配任何字符的特殊字符进行查询。字符说明?匹配任意单个字符。
*匹配 0 个或更多字符。
\转义字符。
wildcardis a term-level operator, meaning that thequeryfield is not analyzed. Term-level operators work well with the Keyword Analyzer, because thequeryfield is treated as a single term, with special characters included. For an example of querying against an analyzedqueryfield, see the analyzed field example.
语法
wildcard 通过以下语法实现:
{ $search: { "index": <index name>, // optional, defaults to "default" "wildcard": { "query": "<search-string>", "path": "<field-to-search>", "allowAnalyzedField": <boolean>, "score": <options> } } }
选项
wildcard 使用以下词条来构造查询:
字段 | 类型 | 说明 | 必要性 | 默认 |
|---|---|---|---|---|
| 字符串或字符串数组 | 要搜索的一个或多个字符串。 | 是 | |
| 字符串或字符串数组 | 要搜索的一个或多个带索引字段。您还可以指定通配符路径进行搜索。 | 是 | |
| 布尔 | 如果对使用分词分析器索引的字段运行查询,则将其设置为 | no |
|
| 对象 | 修改分配给匹配搜索词结果的分数。选项包括:
有关在查询中使用 | no |
行为
wildcard 是术语级操作符,因而不会分析 query 字段。对使用分词分析器索引的字段,将 allowAnalyzedField 设置为 true,使用 wildcard 操作符。使用 关键字分析器 索引的字段已将字段值视为单个术语,因此不需要 allowAnalyzedField: true。
如果您将 wildcard 与 allowAnalyzedField: true 一起使用,MongoDB Search 会根据字段指定的分析器或自定义分析器应用字符过滤器和词元过滤器。MongoDB Search 跳过了词元化,输出始终是单个词元。
以下示例显示 wildcard 操作符在对已分析字段执行搜索时的行为方式:
例子
标准分析器
foo bar baz假设使用标准分析器对字段 进行了索引。MongoDB Search 会分析字段并将其索引为 foo、bar 和 baz。在此字段中搜索 foo bar* 找不到任何结果,因为通配符操作符将 foo bar* 视为结尾带有通配符的单个搜索术语。换句话说, MongoDB Search 在字段中搜索以 foo bar 开头的任何术语,但找不到任何结果,因为不存在这样的术语。
例子
转义字符行为
When using the escape character in mongosh or with a driver, you must use a double backslash before the character to be escaped.
例子
要创建一个通配符表达式来搜索聚合管道中包含字面星号的任何字符串,请使用以下表达式:
"*\\**"
第一个和最后一个星号作为通配符,可匹配任何字符,而 \\* 则匹配文字星号。
注意
使用以下表达式对文本反斜杠进行转义:
"*\\\*"
示例
The following examples use the movies collection in the sample_mflix database with a custom index definition that uses the keyword analyzer. If you have the sample dataset on your cluster, you can create a MongoDB Search index on the movies collection and run the example queries on your cluster.
索引示例
以下索引定义使用关键字分析器对 movies 集合中的 title 字段进行索引:
1 { 2 "mappings": { 3 "fields": { 4 "title": { 5 "analyzer": "lucene.keyword", 6 "type": "string" 7 } 8 } 9 } 10 }
查询示例
以下示例在所有 title 字段中搜索以 Green D 开头、后跟任意数量的其他字符的电影标题。
以下示例在所有 title 字段中搜索以字符串 Wom?n(其中 ? 可以是任意单个字符)开头的电影标题,然后是空格,然后是任意数量的其他字符。
以下示例使用转义字符搜索 title 字段以问号结尾的文档。
query 字段中的 * 字符与任何字符匹配,而 \\? 字符串与文字问号匹配。