1. 准备测试数据,将数据下载到本地:

https://github.com/elastic/el...

数据结构:
{ 
    "account_number": 0, 
    "balance": 16623, 
    "firstname": "Bradshaw", 
    "lastname": "Mckenzie", 
    "age": 29, 
    "gender": "F", 
    "address": "244 Columbus Place", 
    "employer": "Euron", 
    "email": "bradshawmckenzie@euron.com", 
    "city": "Hobucken", 
    "state": "CO"
}

2. 导入数据到es

进入到accounts.json文件的目录执行导入命令,该命令会自动创建bank索引
curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk?pretty&refresh" --data-binary "@accounts.json" 

curl "localhost:9200/_cat/indices?v=true"

3. 查询操作

# 查询bank索引所有数据,默认显示10条
GET /bank/_search

# 分页查询并根据account_number降序
GET /bank/_search
{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "account_number": {
        "order": "desc"
      }
    }
  ],
  "from": 10,
  "size": 1
}

# 查询address包含mill或lane
GET /bank/_search
{
  "query": {
    "match": {
      "address": "mill lane"
    }
  }
}

# 仅匹配包含mill lane的内容
GET /bank/_search
{
  "query": {
    "match_phrase": {
      "address": "mill lane"
    }
  }
}

#使用bool来构造复杂查询,age为40但state不为id
GET /bank/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "age": "40"
          }
        }
      ],
      "must_not": [
        {
          "match": {
            "state": "ID"
          }
        }
      ]
    }
  }
}

# 使用filter过滤数据
GET /bank/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match_all": {}
        }
      ],
      "filter": {
        "range": {
          "balance": {
            "gte": 20000,
            "lte": 30000
          }
        }
      }
    }
  }
}

# 聚合查询
GET /bank/_search
{
  "size": 0,
  "aggs": {
    "group_by_gender": {
      "terms": {
        "field": "gender.keyword"
      }
    }
  }
}

#嵌套聚合查询并排序
GET /bank/_search
{
  "size": 0,
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "city.keyword",
        "order": {
          "average_balance": "desc"
        }
      },
      "aggs": {
        "average_balance": {
          "avg": {
            "field": "balance"
          }
        }
      }
    }
  }
}

靖锅锅
1 声望1 粉丝

什么也不想说