定义
语法
wildcard 通过以下语法实现:
{ $search: { "index": <index name>, // optional, defaults to "default" "wildcard": { "query": "<search-string>", "path": "<field-to-search>", "allowAnalyzedField": <boolean>, "score": <options> } } }
选项
wildcard 使用以下词条来构造查询:
字段 | 类型 | 说明 | 必要性 | 默认 |
|---|---|---|---|---|
| 字符串或字符串数组 | 要搜索的一个或多个字符串。 | 是 | |
| 字符串或字符串数组 | 要搜索的一个或多个带索引字段。您还可以指定通配符路径进行搜索。 | 是 | |
| 布尔 | Set to | no |
|
| 对象 | 修改分配给匹配搜索词结果的分数。选项包括:
有关在查询中使用 | no |
行为
wildcard is a term-level operator, meaning that the query field isn't analyzed. Use the wildcard operator on fields indexed with tokenizing analyzers by setting allowAnalyzedField to true. Fields indexed with the Keyword Analyzer already treat the field value as a single term, so allowAnalyzedField: true isn't required.
If you use wildcard with allowAnalyzedField: true, MongoDB Search applies character filters and token filters based on the specified analyzer or custom analyzer for the field. MongoDB Search skips the tokenization and the output is always a single token.
以下示例显示 wildcard 操作符在对已分析字段执行搜索时的行为方式:
例子
标准分析器
foo bar baz假设使用标准分析器对字段 进行了索引。MongoDB Search 会分析字段并将其索引为 foo、bar 和 baz。在此字段中搜索 foo bar* 找不到任何结果,因为通配符操作符将 foo bar* 视为结尾带有通配符的单个搜索术语。换句话说, MongoDB Search 在字段中搜索以 foo bar 开头的任何术语,但找不到任何结果,因为不存在这样的术语。
例子
转义字符行为
在 mongosh 中或驱动程序中使用转义字符时,必须在要转义的字符前使用双反斜杠。
例子
要创建一个通配符表达式来搜索聚合管道中包含字面星号的任何字符串,请使用以下表达式:
"*\\**"
第一个和最后一个星号作为通配符,可匹配任何字符,而 \\* 则匹配文字星号。
注意
使用以下表达式对文本反斜杠进行转义:
"*\\\*"
示例
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 字段中的 * 字符与任何字符匹配,而 \\? 字符串与文字问号匹配。