ES教程-高级搜索

作者: gavin 分类: ES 发布时间: 2024-07-05 10:58

一、通过filter只搜索age=13的数据,需要注意的是term是不做分词处理,如果换成match就是做分词处理

GET /employee/_search
{
  "query": {
    "bool": {
      "filter": [
        {"term": {"age": 13}}
      ]
    }
  }
}

//目前实际测试下来和下面查询方式效果一样
GET /employee/_search
{
	"query":{
		"match":{"age":18}
	}
}

二、加上排序和分组功能

//按age倒序排列,并以age做为分组显示分组数据

GET /employee/_search
{
	"query":{
		"match":{"name":"任"}
	},
	"sort":[
		{"age":{"order":"desc"}}
	],
	"aggs":{
		"group_by_age":{
			"terms":{
				"field":"age"
			}
		}
	}
}

//分组数据如下(以下示例去掉了name筛选)
{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 4,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "employee",
        "_id": "1",
        "_score": 1,
        "_source": {
          "name": "Casey",
          "age": "13"
        }
      },
      {
        "_index": "employee",
        "_id": "2",
        "_score": 1,
        "_source": {
          "name": "Gavin",
          "age": 18
        }
      },
      {
        "_index": "employee",
        "_id": "3",
        "_score": 1,
        "_source": {
          "name": "任子隆",
          "age": "18"
        }
      },
      {
        "_index": "employee",
        "_id": "4",
        "_score": 1,
        "_source": {
          "name": "任刚",
          "age": "28"
        }
      }
    ]
  },
  "aggregations": {
    "group_by_age": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 18,
          "doc_count": 2
        },
        {
          "key": 13,
          "doc_count": 1
        },
        {
          "key": 28,
          "doc_count": 1
        }
      ]
    }
  }
}