今天在spark中需要将字符型(String)的ip转化为长整型(long)的ip,参考了两篇文章https://blog.youkuaiyun.com/cjuexuan/article/details/54912215和https://blog.youkuaiyun.com/key_xyes/article/details/79818196,通过这两篇文章的抽取出思路。于是封装成UDF函数,如下:
sqlContext.udf.register("Ip2Long",(ip:String)=>{
ip match {
case i if i.matches("""^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$""")=>{
var ip_long = 0l
var parts = i.toString.trim.split(Pattern.quote("."))
for(i <- parts.length to 1 by -1) {
ip_long = ip_long << 8
ip_long |= parts(i - 1).toLong
}
ip_long
}
case _=>0
}
})
这样,我就可以在sql中使用我自定义的函数了。
var df = spark.sql("select ip, Ip2Long(ip), region from mytable").toDF("ipStr", "ipInt", "region")
在此作为小标记,以示记忆。

本文介绍如何在Spark中将字符串类型的IP地址转换为长整型IP,通过正则表达式验证IP格式,然后将每个部分转换为长整型并左移位运算,实现IP地址的有效转化。
1643

被折叠的 条评论
为什么被折叠?



