NoSQL 与搜索 / 系统课时

match 全文查询

match 全文查询

本课通过同一组文档对比三种 match 查询,观察查询文本如何被分析为词项,并验证 operator 与 minimum_should_match 怎样改变命中范围。完成后,你能为全文搜索选择合适的宽松度。

学习目标

  • 理解 match 查询会先分析查询文本再执行检索
  • 使用 operator 控制多个词项之间的 OR 或 AND 关系
  • 使用 minimum_should_match 设置最低命中词项数量

match 查询的本质

match 面向经过分析的全文字段。查询文本会使用字段对应的搜索分析器转换为词项,再由这些词项构造布尔查询。因此,它比较的是分析后的词项,而不是整段原始字符串是否完全相等。

match 查询从文本到命中文档的处理流程

默认 operator 是 or,任意一个词项命中即可进入候选结果。改为 and 后,所有词项都必须命中。minimum_should_match 则提供介于两者之间的阈值,例如三个词项至少命中两个。

准备可复现实验数据

在 Kibana Dev Tools 中执行以下请求。三个文档分别覆盖三个、两个和一个查询词项,便于观察参数差异。

http
DELETE /lesson_articles?ignore_unavailable=true

PUT /lesson_articles
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  },
  "mappings": {
    "properties": {
      "content": {
        "type": "text"
      }
    }
  }
}

POST /lesson_articles/_bulk?refresh=wait_for&filter_path=errors,items.index._id,items.index.status
{"index":{"_id":"1"}}
{"content":"distributed search engine tutorial"}
{"index":{"_id":"2"}}
{"content":"distributed storage engine"}
{"index":{"_id":"3"}}
{"content":"search tutorial"}

预期结果

text
DELETE: {"acknowledged":true}
PUT: {"acknowledged":true,"shards_acknowledged":true,"index":"lesson_articles"}
BULK: {"errors":false,"items":[{"index":{"_id":"1","status":201}},{"index":{"_id":"2","status":201}},{"index":{"_id":"3","status":201}}]}

对比 operator 与 minimum_should_match

下面连续执行三次搜索。响应通过 filter_path 只保留命中总数和文档 ID,便于直接比较召回范围。

http
POST /lesson_articles/_search?filter_path=hits.total,hits.hits._id
{
  "query": {
    "match": {
      "content": {
        "query": "distributed search engine",
        "operator": "or"
      }
    }
  }
}

POST /lesson_articles/_search?filter_path=hits.total,hits.hits._id
{
  "query": {
    "match": {
      "content": {
        "query": "distributed search engine",
        "operator": "and"
      }
    }
  }
}

POST /lesson_articles/_search?filter_path=hits.total,hits.hits._id
{
  "query": {
    "match": {
      "content": {
        "query": "distributed search engine",
        "minimum_should_match": "2"
      }
    }
  }
}

预期输出

text
operator=or: total=3, ids=["1","2","3"]
operator=and: total=1, ids=["1"]
minimum_should_match=2: total=2, ids=["1","2"]

第一条查询只要求命中任意词项,所以三个文档都能返回。第二条要求同时包含 distributed、search 和 engine,只剩文档 1。第三条要求至少命中两个词项,因此文档 1 和 2 满足条件。

参数选择与关键边界

追求更高召回率时,可以保留默认 or;查询词较多、噪声结果明显时,可以设置整数或百分比形式的 minimum_should_match;只有确实要求全部词项出现时,才使用 and。

match 不适合订单号、状态码、标签等精确值判断。此类字段通常映射为 keyword 并使用精确查询。对 text 字段盲目使用 and 也可能让正常结果全部消失,因为分词、停用词和同义词都会影响最终词项。

当分析器删除了全部查询词项时,zero_terms_query 默认不返回文档。除非业务明确需要“空词项等于查全部”,否则不要轻易改为 all。

本课总结

  • match 会分析查询文本,并基于分析后的词项执行全文检索
  • operator=or 更宽松,operator=and 要求全部词项命中
  • minimum_should_match 可以在召回率与精确度之间设置中间阈值

下一课预告

下一课将比较全文查询与精确值查询,明确 text、keyword、match 和精确查询之间的对应关系。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

match 全文查询

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通