ES常用语法(查询、排序、组合查询、聚合查询)

简单查询

GET order_index/_search

{
  "query": {
      "term": { "user": "liubei" }
  }
}

GET order_index/_search

{
  "query": {
      "term": { "user": "liubei" }
  },
  "from": 0,
  "size": 10
}

排序

GET order_index/_search

{
  "sort": [
      { "createTime": { "order": "desc" } }
  ],
  "from": 0,
  "size": 10
}

组合查询

GET order_index/_search

{
  "query": {
    "bool": {
      "must": {"match": {"title": "quick"} },
      "must_not": {"match": {"title": "lazy"} },
      "should": [
        {"match": {"title": "brown"} },
        {"match": {"title": "dog"} }
      ]
    }
  }
}

聚合查询

常用聚合函数:value_countsummaxminavg

GET order_index/_search

{
  "aggs": {
    "sum_amount": {
      "sum": { "field": "amount" }
    }
  }
}

GET order_index/_search

{
  "query": {
    "term": { "user": "liubei" }
  },
  "aggs": {
    "max_amount": {
      "max": { "field": "amount" }
    }
  }
}

分组统计

统计各产品一季度的销量

GET order_index/_search

{
  "query": {
    "range": {
      "create_time": { "gte": "2020-01-01", "lt": "2020-04-01" }
    }
  },
  "aggs": {
    "max_eday": {
      "terms": {
        "field": "product_id",
        "order" : { "_key" : "asc" }
      }
    }
  }
}

排序字段

"order" : { "_key" : "asc" }
"order" : { "_count" : "asc" }

特殊函数

一次可统计出count/max/min/avg/sum 5个值

GET order_index/_search

{
	"aggs": {
		"age_count": { "stats": { "field": "age" } }
	}
}

extended_stats:平方和、方差、标准差、平均值加/减两个标准差的区间。

{
	"aggs": {
		"age_count": { "extended_stats": { "field": "age" } }
	}
}

自定义脚本

GET order_index/_search

{
  "aggs": {
    "sum_amount": {
      "sum": {
        "field": "amount",
        "script": { "source": "_value * 1.03" }
      }
    }
  }
}

GET order_index/_search

{
  "aggs": {
    "avg_age": {
      "avg": {
        "field": "amount",
        "script": { "source": "doc.age.value" }
      }
    }
  }
}

GET order_index/_search

{
  "aggs": {
    "avg_age_10": {
      "avg": {
        "script": { "source": "doc.age.value + 10" }
      }
    }
  }
}

你可能感兴趣的:(BIGDATA)