elasticsearch - 具有过滤和聚合的 Elasricsearch 查询
问题描述
我有一个包含简单汽车广告数据的 Elasticsearch 索引。我做了一个映射:
"mappings": {
"properties": {
"brand": {"type": "keyword"},
"model": {"type": "keyword"},
"year of production": {"type": "integer"},
"mileage": {"type": "integer"},
"color": {"type": "keyword"},
"engine capacity": {"type": "double"},
"horse power": {"type": "integer"},
"type of fuel": {"type": "keyword"},
"condition": {"type": "keyword"},
"accident history": {"type": "boolean"},
"price": {"type": "integer"}
}
}
我想创建两个查询:
- 显示 2010 年至 2012 年间制造的二手车的平均里程
- 显示 2005 年至 2007 年期间制造的里程超过 200000 的最受欢迎的汽车模型
我尝试创建两者,这是我尝试第一个查询的结果:
GET /gielda/_search?pretty
{
"query": {
"match": {
"stan": "Used"
}
},
"aggs": {
"production_ranges": {
"range": {
"field": "year of production",
"ranges": [
{
"from": 2010,
"to": 2012
}
]
},
"aggs": {
"avg_mileage": {
"avg": {
"field": "mileage"
}
}
}
}
}
}
我发现这个查询不能正常工作。我在 Elastic docs 和 Stack 上寻找答案,但我仍然不知道如何将聚合与过滤器或范围混合。
解决方案
您需要使用range、filter、avg和top_hits聚合的组合
添加带有索引数据、搜索查询和搜索结果的工作示例
指数数据:
{
"mileage": 10,
"year of production": 2011
}
{
"mileage": 30,
"year of production": 2012
}
{
"mileage": 20,
"year of production": 2013
}
{
"mileage": 200001,
"year of production": 2005,
"model": "ABC"
}
{
"mileage": 400000,
"year of production": 2006,
"model": "DEF"
}
{
"mileage": 400000,
"year of production": 2008,
"model": "GHI"
}
搜索查询:
{
"size": 0,
"aggs": {
"production_ranges": {
"range": {
"field": "year of production",
"ranges": [
{
"from": 2010,
"to": 2013
}
]
},
"aggs": {
"avg_mileage": {
"avg": {
"field": "mileage"
}
}
}
},
"Popular_car_model": {
"filter": {
"bool": {
"must": [
{
"range": {
"year of production": {
"gte": 2005,
"lte": 2007
}
}
},
{
"range": {
"mileage": {
"gte": 200000
}
}
}
]
}
},
"aggs": {
"top_sales_hits": {
"top_hits": {
"sort": [
{
"mileage": {
"order": "desc"
}
}
],
"_source": {
"includes": [
"model",
"mileage",
"year of production"
]
},
"size": 1
}
}
}
}
}
}
搜索结果:
"aggregations": {
"Popular_car_model": {
"doc_count": 2,
"top_sales_hits": {
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"max_score": null,
"hits": [
{
"_index": "67650682",
"_type": "_doc",
"_id": "5",
"_score": null,
"_source": {
"year of production": 2006,
"model": "DEF",
"mileage": 400000
},
"sort": [
400000
]
}
]
}
}
},
"production_ranges": {
"buckets": [
{
"key": "2010.0-2013.0",
"from": 2010.0,
"to": 2013.0,
"doc_count": 2,
"avg_mileage": {
"value": 20.0
}
}
]
}
}
推荐阅读
- ios - UIPickerView BarButton 文本颜色没有改变,但是当点击按钮时,颜色在 Objective-C 中改变
- react-native - React Native:在视频流顶部显示 OpenTok Publisher 的名称
- javascript - 如何将json数组对象转换为json数组
- gulp - 为什么我不能让 BrowserSync 与 Gulp 版本 4 一起使用?
- sql-server - 如果由于 order by 子句中的 case 语句导致 SELECT DISTINCT 错误,则 ORDER BY 项目必须出现在选择列表中
- c - MDK-ARM C:中断后循环不会中断
- javascript - 每月第一个日期的 X 范围图表上未正确显示绘制的点标签 - Highcharts
- javascript - 使用 javascript 获取完整的信用卡数据
- php - 如果条件似乎不适用于在线托管,则嵌套中的 MySQL 查询?
- python - spacy 标记化合并了错误的标记