Elasticsearch查询数据常用语句

单条件查询,以下两种查询结果相同

GET cms_5/_search
{
  "query":{
    "bool": {
      "must": [
        {"match": {
          "year": "2018"
        }}
      ]
    }
  }
}

GET cms_5/_search
{
  "query": {
    "term": {
      "year": {
        "value": "2017"
      }
    }
  }
}

多条件查询:

1.一个查询条件,条件值有多个,类似sql语句的in

GET cms_5/_search
{
  "query": {
    "terms": {
      "year": [
        "2017",
        "2018",
        "2019"
      ]
    }
  },
  "sort": [
    {
      "contentId": {
        "order": "desc"
      }
    }
  ]
}

2.多条件查询,有必须满足的条件和必须不满足的条件

GET cms_test2/_search
{
  "query": {
    "bool": {
      "must":{"match":{"age":"50"}},
      "must_not":{"match":{"sex":"女"}}
    }
  },
  "from" : 0,
  "size" : 5
}

3.多条件查询,必须满足条件多个

GET cms_bak/_search
{
  "query":{
    "bool":{
      "must":[
        {"term":{"classify.second":"预告片"}},
        {"term": {
          "year": {
            "value": "2020"
          }
        }},
        {"term": {
          "area": {
            "value": "内地"
          }
        }},
        {"term": {
          "channelCode": {
            "value": "50000138"
          }
        }}]
    }
  }
}

聚合函数查询:

查询最大值

GET testa/_search
{
  "aggs": {
    "max_value": {
      "max": {
        "field": "age"
      }
    }
  }
}

平均值

GET testa/_search
{
  "aggs": {
    "ang": {
      "avg": {
        "field": "age"
      }
    }
  }
}

按年龄分组统计

GET testa/_search
{
  "aggs": {
    "terms_value": {
      "terms": {
        "field": "age",
        "size": 10
      }
    }
  }
}

Elasticsearch查询数据常用语句