Splunk条件统计:基于文件访问时间的占比计算需求
Splunk 文件访问时间占比统计解决方案
我来帮你搞定这个文件访问时间的占比统计需求,直接给你可复用的Splunk查询语句,再一步步拆解逻辑,确保你能快速适配自己的环境:
基础版查询(满足核心需求)
这个查询会直接输出你要的两个占比:6个月至3年前的文件占比,以及其他文件的占比:
# 替换成你的实际搜索范围,比如index=your_file_index sourcetype=csv_file_data <你的基础搜索语句> | eval epoch_LastAccessTime=strptime(Last_access, "%d/%m/%Y %H:%M:%S") # 你已有的时间转换步骤 | eval three_years_ago = relative_time(now(), "-3y") # 计算当前时间往前推3年的epoch时间 | eval six_months_ago = relative_time(now(), "-6mon") # 计算当前时间往前推6个月的epoch时间 | eval is_target_range = if(epoch_LastAccessTime >= three_years_ago AND epoch_LastAccessTime <= six_months_ago, 1, 0) | stats count as total_files sum(is_target_range) as target_files | eval target_percentage = round((target_files / total_files) * 100, 2) # 计算目标范围占比,保留2位小数 | eval other_percentage = round(100 - target_percentage, 2) # 其他文件占比 | table total_files target_files target_percentage other_percentage
关键步骤解释
- 使用
relative_time而非硬算天数:因为不同月份、年份的天数不同,用-3y和-6mon能自动适配时间差异,结果更准确 is_target_range字段:用1/0标记符合条件的文件,方便后续用sum统计数量- 最后通过简单的除法计算占比,用
round控制小数位数,让结果更直观
进阶版查询(细化"其他文件"分类)
如果需要更清晰地知道"其他文件"具体包含哪些类别(比如6个月内访问、3年以上访问、无访问时间的文件),可以用这个版本:
<你的基础搜索语句> | eval epoch_LastAccessTime=strptime(Last_access, "%d/%m/%Y %H:%M:%S") | eval epoch_LastAccessTime = if(isnull(epoch_LastAccessTime), -1, epoch_LastAccessTime) # 把空访问时间标记为特殊值 | eval three_years_ago = relative_time(now(), "-3y") | eval six_months_ago = relative_time(now(), "-6mon") | eval file_category = case( epoch_LastAccessTime >= three_years_ago AND epoch_LastAccessTime <= six_months_ago, "6个月-3年前", epoch_LastAccessTime > six_months_ago, "6个月以内", epoch_LastAccessTime < three_years_ago AND epoch_LastAccessTime != -1, "3年以上", epoch_LastAccessTime == -1, "无访问时间" ) | stats count as file_count by file_category | eventstats sum(file_count) as total_files | eval percentage = round((file_count / total_files) * 100, 2) | table file_category file_count percentage
注意事项
- 确保
strptime的格式字符串和你Last_access字段的实际格式完全匹配,如果你的时间格式是其他样式(比如月/日/年),要对应调整%d/%m/%Y部分 - 如果你的数据中存在
Last_access为空的情况,进阶版会单独统计这类文件,避免影响占比计算的准确性
内容的提问来源于stack exchange,提问作者cyborked
相关产品推荐
相关产品推荐

