检索IP地理位置 [英] Retrieving the IP geo location
本文介绍了检索IP地理位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个.CSV文件,其中一个包含IP地址:
I have two .CSV files, one including IP addresses :
-
76.83.179.64
76.83.179.64
76.83.179.64
76.83.179.64
187.42.62.209
187.42.62.209
89.142.219.5
89.142.219.5
,另一个包括IP范围和国家/地区名称,如下所示:
and the other includes IP ranges and country names as follow:
ip_from| ip_to| country_name|
|16777216|16777471|Australia|
到目前为止,我所做的是:
What I have done so far is as follow:
加载数据:ip_from,ip_to和国家/地区名称
load the data : ip_from, ip_to and country name
val rdd1 = sqlContext.read.format("csv").option("inferSchema",
"true").load("/FileStore/tables/locations.CSV")
val df2 = rdd1.toDF()
加载数据并从IP转换为Long
load the data and converts from IP to Long
val rdd2 = sc.textFile("/FileStore/tables/ipaddress.csv")
def ipToLong(ipAddress: String): Long = {
ipAddress.split("\\.").reverse.zipWithIndex
.map(a=>a._1.toInt*math.pow(256,a._2).toLong).sum
}
val df1 = rdd2.map(x=>ipToLong(x)).toDF()
现在,我应该编写什么用户定义的函数来加入两个DF(或查找)并根据IP地址检索国家/地区名称?
Now, what user defined function should I write to join both DFs(or look up) and retrieve the country name according the ip address?
推荐答案
对于您的情况,您只需使用以下逻辑
for your case you simply use following logic
df1.join(df2, df1("value") >= df2("ip_from") && df1("value") <= df2("ip_to"), "left")
这篇关于检索IP地理位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文