今天在spark中需要将字符型(String)的ip转化为长整型(long)的ip,参考了两篇文章https://blog.csdn.net/cjuexuan/article/details/54912215和https://blog.csdn.net/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")
在此作为小标记,以示记忆。