网站可以在手机上做吗/免费模板
1、首先我们拿到一个日志数据,为某网的网站访问日志,对其中的数据进行分析
使用moodle.access.log数据文件
1、日志数据文件:
"27.38.5.159"
"-"
"31/Aug/2015:00:04:37 +0800"
"GET /course/view.php?id=27 HTTP/1.1"
"303"
"440"
-
"http://www.ibeifeng.com/user.php?act=mycourse"
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36"
"-"
"learn.xxxxx.com"
2、以及拿到我们对应字段的含义,也就是字段名称,对数据不进行格式清洗,直接建表测试,
create table IF NOT EXISTS log_source (
remote_addr string,
remote_user string,
time_local string,
request string,
status string,
body_bytes_sent string,
request_body string,
http_referer string,
http_user_agent string,
http_x_forwarded_for string,
host string
)
ROW FORMAT DELIMITED FIELDS TERMINATED BY ' '
stored as textfile ;
加载数据后对数据进行查询,可以发现,字段之间是存在空格的,所以对数据的切分,出现了很多错误,比如我们查询数据来看看,明显可以看出,时间的字段缺失了时区,request却加载了时区,错误
这个时候我们就需要,根据每个日志文件的内容与格式,用相应的正则表达式,对其进行数据匹配与加载
根据这个日志写出来的正则为这个格式regex="(\"[^ ]*\") (\"[-|^ ]*\") (\"[^}]*\") (\"[^}]*\") (\"[0-9]*\") (\"[0-9]*\") ([-|^ ]*) (\"[^ ]*\") (\"[^\"]*\") (\"[-|^ ]*\") (\"[^ ]*\")"
接下来,我们把前面的表drop掉,重新按正则规范建表,
create table IF NOT EXISTS log_src (
remote_addr string,
remote_user string,
time_local string,
request string,
status string,
body_bytes_sent string,
request_body string,
http_referer string,
http_user_agent string,
http_x_forwarded_for string,
host string
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
WITH SERDEPROPERTIES (
"input.regex" = "(\"[^ ]*\") (\"[-|^ ]*\") (\"[^}]*\") (\"[^}]*\") (\"[0-9]*\") (\"[0-9]*\") ([-|^ ]*) (\"[^ ]*\") (\"[^\"]*\") (\"[-|^ ]*\") (\"[^ ]*\")"
)
STORED AS TEXTFILE;
这样我们就得到了我们想要的一个,数据源表,但是这里 我们呢可以看到,日期的格式不够规范,不是我们想要的格式,那么我们就要对日期做一个格式化。
2、对日期的格式化 31/Aug/2015:00:04:37 +0800" ==>20150931 00:04:37 转换为这种格式,这个代码很简单,直接贴出来,
package com.make.format;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;
public class date_format extends UDF {public SimpleDateFormat inputDate = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss", Locale.ENGLISH);public SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");public Text evaluate(Text time){String date = null;if (time == null) {return null;}if (StringUtils.isBlank(time.toString())) {return null;}String parse = time.toString().replaceAll("\"", "");try{Date parseDate = this.inputDate.parse(parse);date = this.outputDate.format(parseDate);}catch (ParseException e){e.printStackTrace();}return new Text(date);}}
然后将程序打包上传到服务器,
添加jar包 : add jar /opt/module/apache/hive-1.2.1/date_format.jar 想要永久的可以将包上传到hdfs中
创建函数:create temporary function date_format as 'make.hadoop.com.format.date_format'; 单引号内为jar包下类的位置
测试,对时间的格式化修改
可以看到这里的日期格式,已经变成了我们想要的格式,到这里我们udf函数就创建完成了,我这里只是临时的,永久的可以修改配置文件,或者将jar包,上传到hdfs中,既可以了