面试题答案
一键面试-
日期直方图聚合(按周划分数据):
- 使用
date_histogram
聚合来按周对数据进行分组。
{ "aggs": { "weekly_purchases": { "date_histogram": { "field": "timestamp", "calendar_interval": "week", "format": "yyyy - w" } } } }
- 这里
field
指定包含时间戳的字段(假设为timestamp
),calendar_interval
设置为week
表示按周聚合,format
指定输出的日期格式为年份 - 周数。
- 使用
-
嵌套子聚合以分析不同行为类型占比:
- 在
date_histogram
聚合下嵌套terms
聚合来统计不同行为类型(浏览、点击、购买)的数量。
{ "aggs": { "weekly_purchases": { "date_histogram": { "field": "timestamp", "calendar_interval": "week", "format": "yyyy - w" }, "aggs": { "action_type_count": { "terms": { "field": "action_type.keyword" } } } } } }
- 这里
action_type.keyword
假设是存储行为类型的字段(确保该字段已被正确映射为keyword
类型以进行精确匹配)。terms
聚合会统计每种行为类型在每周出现的次数。
- 在
-
计算占比:
- 在
action_type_count
聚合下再嵌套bucket_script
聚合来计算每种行为类型在每周中的占比。
{ "aggs": { "weekly_purchases": { "date_histogram": { "field": "timestamp", "calendar_interval": "week", "format": "yyyy - w" }, "aggs": { "action_type_count": { "terms": { "field": "action_type.keyword" }, "aggs": { "percentage": { "bucket_script": { "buckets_path": { "doc_count": "_count" }, "script": "params.doc_count / params._parent.sum_other_doc_count * 100" } } } } } } } }
bucket_script
聚合中,buckets_path
指定了要使用的桶路径,_count
表示当前行为类型桶的文档数量,_parent.sum_other_doc_count
表示父级(即每周)的总文档数量。通过计算当前行为类型文档数占每周总文档数的比例,并乘以100得到百分比。
- 在
-
分析购买行为趋势:
- 在
weekly_purchases
聚合下可以添加sum
聚合来统计每周购买行为的总数,以分析购买行为趋势。
{ "aggs": { "weekly_purchases": { "date_histogram": { "field": "timestamp", "calendar_interval": "week", "format": "yyyy - w" }, "aggs": { "purchase_count": { "sum": { "script": { "source": "doc['action_type.keyword'].value == '购买'? 1 : 0" } } } } } } }
- 这里通过
script
来判断行为类型是否为“购买”,如果是则计数为1,否则为0,然后通过sum
聚合统计每周的购买行为总数。
- 在
通过以上ElasticSearch聚合的嵌套结构和操作,可以实现分析每周的用户购买行为趋势以及每周不同行为类型的占比情况。