Elasticsearch 的查询 DSL(Domain Specific Language)提供了一种强大而灵活的方式来执行各种搜索和分析操作。查询 DSL 以 JSON 格式表示,支持多种查询类型、过滤器和聚合。以下是一些常用查询类型及其示例。

 

查询结构

一个典型的查询 DSL 请求结构如下:

GET /index_name/_search
{
  "query": {
    "query_type": {
      "field": "value"
    }
  }
}

 

常用查询类型

1. Match Query

match 查询是最常用的查询之一,它用于查找与给定文本匹配的文档。

GET /my_index/_search
{
  "query": {
    "match": {
      "field_name": "search_text"
    }
  }
}

 

2. Term Query

term 查询用于精确匹配字段的值,适用于结构化数据的精确匹配。

GET /my_index/_search
{
  "query": {
    "term": {
      "field_name": "exact_value"
    }
  }
}

 

3. Range Query

range 查询用于查找在特定范围内的文档。

GET /my_index/_search
{
  "query": {
    "range": {
      "age": {
        "gte": 10,
        "lte": 20
      }
    }
  }
}

 

4. Bool Query

bool 查询将多个查询组合在一起,可以包含 must(必须匹配),should(可以匹配),must_not(必须不匹配),和 filter(过滤)。

GET /my_index/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "field1": "value1" } }
      ],
      "filter": [
        { "term": { "field2": "value2" } }
      ],
      "must_not": [
        { "range": { "field3": { "lt": 10 } } }
      ],
      "should": [
        { "term": { "field4": "value4" } }
      ]
    }
  }
}

 

 5. Wildcard Query

wildcard 查询允许使用通配符 *(匹配零个或多个字符)和 ?(匹配单个字符)。

GET /my_index/_search
{
  "query": {
    "wildcard": {
      "field_name": "search*"
    }
  }
}

 

6. Aggregation

聚合用于执行复杂的数据分析,例如统计、求和、分组等。

GET /my_index/_search
{
  "size": 0,
  "aggs": {
    "age_stats": {
      "stats": {
        "field": "age"
      }
    }
  }
}

 

7. Nested Query

nested 查询用于查询嵌套对象和数组。

GET /my_index/_search
{
  "query": {
    "nested": {
      "path": "nested_field",
      "query": {
        "bool": {
          "must": [
            { "match": { "nested_field.sub_field": "value" } }
          ]
        }
      }
    }
  }
}

 

复杂示例

一个综合的复杂查询示例如下,结合了多种查询类型和聚合:

GET /my_index/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "field1": "value1" } },
        { "range": { "date_field": { "gte": "2020-01-01", "lte": "2020-12-31" } } }
      ],
      "filter": [
        { "term": { "status": "active" } }
      ]
    }
  },
  "aggs": {
    "avg_age": {
      "avg": { "field": "age" }
    },
    "status_count": {
      "terms": { "field": "status" }
    }
  }
}

 

解释

通过这些查询和聚合,Elasticsearch 可以灵活处理和分析各种数据需求。