- 添加 Spark 代码以读取 HDFS 上的日志文件 - 实现日志行解析函数以提取 IP 地址 - 使用 RDD操作过滤并计算唯一主机数量- 打印结果并停止 SparkContext
31 lines
751 B
Python
31 lines
751 B
Python
import re
|
|
from pyspark import SparkContext
|
|
|
|
sc = SparkContext.getOrCreate()
|
|
|
|
LOG_PATTERN = re.compile(r'^(\S+) (\S+) (\S+) \[([\w:/]+\s[+-]\d{4})\] "(\S+) (\S+)\s*(\S*)\s?" (\d{3}) (\S+)')
|
|
|
|
|
|
def parse_log_line(line):
|
|
match = LOG_PATTERN.match(line)
|
|
if not match:
|
|
return None
|
|
|
|
return {
|
|
'ip': match.group(1)
|
|
}
|
|
|
|
|
|
logFile = "hdfs://master:9000/user/root/apache.access.log.PROJECT"
|
|
raw_logs = sc.textFile(logFile)
|
|
|
|
parsed_logs = raw_logs.map(parse_log_line).filter(lambda x: x is not None)
|
|
|
|
# 提取 IP 地址并统计唯一主机数量
|
|
unique_hosts = parsed_logs.map(lambda log: log['ip']).distinct()
|
|
unique_host_count = unique_hosts.count()
|
|
|
|
print("Total number of unique hosts: {0}".format(unique_host_count))
|
|
|
|
sc.stop()
|