es的配套工具为Kibana
image.png
es的储存和mysql有所不同叫法也不太一样 用法也不太一样
mysql用的是sql语法 而es使用的是RESTful 风格的操作
例如get post put delete请求

入门:查询和聚合的基础使用

从索引文档开始

  1. PUT /customer/_doc/1
  2. {
  3. "name": "John Doe"
  4. }
  1. GET /customer/_doc/1

查询所有

match_all表示所有数据 sort表示按照什么字段排序著作权归
相关解释

  • took – Elasticsearch运行查询所花费的时间(以毫秒为单位)
  • timed_out –搜索请求是否超时
  • _shards - 搜索了多少个碎片,以及成功,失败或跳过了多少个碎片的细目分类。
  • max_score – 找到的最相关文档的分数
  • hits.total.value - 找到了多少个匹配的文档
  • hits.sort - 文档的排序位置(不按相关性得分排序时)
  • hits._score - 文档的相关性得分(使用match_all时不适用)

    分页查询

    本质上就是from和size两个字段
    1. GET /bank/_search
    2. {
    3. "query": { "match_all": {} },
    4. "sort": [
    5. { "account_number": "asc" }
    6. ],
    7. "from": 10,
    8. "size": 10
    9. }

    指定字段查询

    match 他可以使用分词器 也就是关键词查询
    1. GET /bank/_search
    2. {
    3. "query": { "match": { "address": "mill lane" } }
    4. }
    5. 查询 address中包含 milllane的数据

    查询段落匹配

    match_phrase:条件是 address字段中包含 “mill lane”,则可以使用match_phrase

    多条件查询 bool

    构造更复杂的查询,可以使用bool查询来组合多个查询条件 ```json 以下请求在bank索引中搜索40岁客户的帐户,但不包括居住在爱达荷州(ID)的任何人

GET /bank/_search { “query”: { “bool”: { “must”: [ { “match”: { “age”: “40” } } ], “must_not”: [ { “match”: { “state”: “ID” } } ] } } }

  1. must, should, must_not filter 都是bool查询的子句。那么filter和上述query子句有啥区别呢
  2. <a name="DKmnh"></a>
  3. #### 查询条件
  4. ```json
  5. GET /bank/_search
  6. {
  7. "query": {
  8. "bool": {
  9. "must": [
  10. {
  11. "match": {
  12. "state": "ND"
  13. }
  14. }
  15. ],
  16. "filter": [
  17. {
  18. "term": {
  19. "age": "40"
  20. }
  21. },
  22. {
  23. "range": {
  24. "balance": {
  25. "gte": 20000,
  26. "lte": 30000
  27. }
  28. }
  29. }
  30. ]
  31. }
  32. }
  33. }
  34. 查询 state包含ND age等于40 Balance 大于2000 小于3000的人

聚合查询(类似于聚合函数)

简单聚合

比如我们希望计算出account每个州的统计数量, 使用aggs关键字对state字段聚合,被聚合的字段无需对分词统计,所以使用state.keyword对整个字段统计

GET /bank/_search
{
  "size": 0,
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "state.keyword"
      }
    }
  }
}

嵌套函数

ES还可以处理个聚合条件的嵌套。
比如承接上个例子, 计算每个州的平均结余。涉及到的就是在对state分组的基础上,嵌套计算avg(balance):

GET /bank/_search
{
  "size": 0,
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "state.keyword"
      },
      "aggs": {
        "average_balance": {
          "avg": {
            "field": "balance"
          }
        }
      }
    }
  }
}

对聚合结果排序

可以通过在aggs中对嵌套聚合的结果进行排序
比如承接上个例子, 对嵌套计算出的avg(balance),这里是average_balance,进行排序

GET /bank/_search
{
  "size": 0,
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "state.keyword",
        "order": {
          "average_balance": "desc"
        }
      },
      "aggs": {
        "average_balance": {
          "avg": {
            "field": "balance"
          }
        }
      }
    }
  }
}