查询和聚合

创建索引

PUT /test/_doc/1
{
    "name":"hassan"
}

查询数据

查询所有

match_all 表示查询所有的数据,sort 即按照什么字段排序

GET /test/_serach
{
    "query":{"match_all":{}},
    "sort":[
        {"account_id":"asc"}
    ]
}

分页查询

本质上就from和size两个字段

GET /test/_search
{
    "query":{"match_all":{}},
    "sort":[
        {"account_id":"ase"}
    ],
    "from":10,
    "size":10
}

查询指定字段

使用 match 查询特定字词,如下语句将查询address 字段中包含 mill 或者 lane的数据。

GET /test/_search
{
    "query":{"match":{"address":"mill lane"}}
}

查询段落匹配

如果我们希望查询的条件是 address字段中包含 "mill lane",则可以使用 match_phrase

GET /bank/_search
{
  "query": { "match_phrase": { "address": "mill lane" } }
}

多条件查询:bool

如果要构造更复杂的查询,可以使用 bool 查询来组合多个查询条件。

例如,以下请求在bank索引中搜索40岁客户的帐户,但不包括居住在爱达荷州(ID)的任何人

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

其中must, should, must_not 和 filter 都是bool查询的子句。

查询条件:query or filter

先看下如下查询, 在bool查询的子句中同时具备query/must 和 filter

GET /bank/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "state": "ND"
          }
        }
      ],
      "filter": [
        {
          "term": {
            "age": "40"
          }
        },
        {
          "range": {
            "balance": {
              "gte": 20000,
              "lte": 30000
            }
          }
        }
      ]
    }
  }
}

两者都可以写查询条件,而且语法也类似。区别在于,query 上下文的条件是用来给文档打分的,匹配越好 _score 越高;filter 的条件只产生两种结果:符合与不符合,后者被过滤掉。

聚合查询:Aggregation

简单聚合

比如我们希望计算出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"
          }
        }
      }
    }
  }
}

参考

https://pdai.tech/md/db/nosql-es/elasticsearch-x-usage.html