在spark中通过UDF转字符串ip

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

在此作为小标记,以示记忆。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值