查询DSL
1 Match 查询(全文搜索)
对文本字段进行全文搜索,会自动分词
# 基本match查询
{
  "query": {
    "match": {
      "title": "elasticsearch guide"
    }
  }
}

# match with operator
{
  "query": {
    "match": {
      "title": {
        "query": "elasticsearch guide",
        "operator": "and"
      }
    }
  }
}

# multi_match(多字段搜索)
{
  "query": {
    "multi_match": {
      "query": "search engine",
      "fields": ["title^3", "content", "tags"],
      "type": "best_fields"
    }
  }
}
2 Term 查询(精确匹配)
对keyword字段进行精确值匹配,不会分词
# term查询
{
  "query": {
    "term": {
      "status": "published"
    }
  }
}

# terms查询(多值匹配)
{
  "query": {
    "terms": {
      "tags": ["elasticsearch", "search", "database"]
    }
  }
}

# range查询(范围查询)
{
  "query": {
    "range": {
      "publish_date": {
        "gte": "2024-01-01",
        "lte": "2024-12-31",
        "format": "yyyy-MM-dd"
      }
    }
  }
}
3 Bool 查询(组合查询)
使用布尔逻辑组合多个查询条件
# bool查询结构
{
  "query": {
    "bool": {
      "must": [
        # 必须匹配(AND)
      ],
      "should": [
        # 应该匹配(OR),可指定minimum_should_match
      ],
      "must_not": [
        # 必须不匹配(NOT)
      ],
      "filter": [
        # 过滤条件(不计算评分,可缓存)
      ]
    }
  }
}

# 实际示例
{
  "query": {
    "bool": {
      "must": [
        { "match": { "title": "elasticsearch" } },
        { "match": { "content": "search" } }
      ],
      "should": [
        { "match": { "tags": "tutorial" } },
        { "match": { "tags": "guide" } }
      ],
      "must_not": [
        { "term": { "status": "draft" } }
      ],
      "filter": [
        { "range": { "publish_date": { "gte": "2024-01-01" } } },
        { "term": { "category": "technology" } }
      ]
    }
  }
}
4 模糊与通配符查询
# wildcard(通配符)
{
  "query": {
    "wildcard": {
      "title": "el*search"
    }
  }
}

# regexp(正则表达式)
{
  "query": {
    "regexp": {
      "title": "elasticsearch.*guide"
    }
  }
}

# fuzzy(模糊查询)
{
  "query": {
    "fuzzy": {
      "title": {
        "value": "elasticsearch",
        "fuzziness": "AUTO"
      }
    }
  }
}

# prefix(前缀查询)
{
  "query": {
    "prefix": {
      "title": "elastic"
    }
  }
}
5 嵌套查询
查询嵌套对象和数组字段
# nested查询
{
  "query": {
    "nested": {
      "path": "comments",
      "query": {
        "bool": {
          "must": [
            { "match": { "comments.author": "john" } },
            { "match": { "comments.content": "thanks" } }
          ]
        }
      }
    }
  }
}

# has_child(父子文档)
{
  "query": {
    "has_child": {
      "type": "comment",
      "query": {
        "match": {
          "comment_text": "helpful"
        }
      }
    }
  }
}
查询类型对比
  • match - 全文搜索,会分词,用于text字段
  • term - 精确匹配,不分词,用于keyword字段
  • range - 范围查询(数字、日期)
  • bool - 组合多个查询条件
  • filter - 过滤条件,不计算评分,可缓存