使用SparkSQL从IP地址检索地理位置(区域或大陆)
我有一个带有一组IP地址的表列,我需要找出它的地区/大陆,如下所述使用SparkSQL从IP地址检索地理位置(区域或大陆),sql,apache-spark,apache-spark-sql,hiveql,Sql,Apache Spark,Apache Spark Sql,Hiveql,我有一个带有一组IP地址的表列,我需要找出它的地区/大陆,如下所述 ------------------------------------------------------ ip_address | region ------------------------------------------------------ 217.100.34.222 | North Holland 为此,我从下载了IP国家/地区/城市数据库,但其表和值如下所示 -----------
------------------------------------------------------
ip_address | region
------------------------------------------------------
217.100.34.222 | North Holland
为此,我从下载了IP国家/地区/城市数据库,但其表和值如下所示
-----------------------------------------------------
ip_from | ip_to | country_code | country_name | region_name | city_name
-----------------------------------------------------
16777216 | 16777471 | AU | Australia | Queensland | Brisbane
我如何才能将我的ip_地址
列转换为十进制数
,如ip2location数据库所示,并从中检索数据,或者是否有更好的方法来执行此过程,以便从ip地址
检索地理位置
谢谢
执行此过程的更好方法是检索地理位置
从ip地址使用SparkSQL
选项1:
正如databricks在广告分析上所描述的,这是一种方法。请检查完整的文章-
直接从Spark调用Web服务:
# Obtain the unique agents from the accesslog table
ipaddresses = sqlContext.sql("select distinct ip1 from \
accesslog where ip1 is not null").rdd
# getCCA2: Obtains two letter country code based on IP address
def getCCA2(ip):
url = 'http://freegeoip.net/csv/' + ip
str = urllib2.urlopen(url).read()
return str.split(",")[1]
# Loop through distinct IP addresses and obtain two-letter country codes
mappedIPs = ipaddresses.map(lambda x: (x[0], getCCA2(x[0])))
两个字母的国家/地区代码可以通过稍后的查找进行扩展
选项2:配置单元表方法,如带有scala伪代码的示例(而不是web服务方法)
将已下载的数据摄取到配置单元表中
val ipsdf = hiveContext.sql(s"select ip from iptable ")
val countriesWithIp = hiveContext.sql(s"select countryname,ip from countriesWithIPs")
countriesWithIpAddrMapped = ipsdf.join(countriesWithIp , ipsdf("ip")===countriesWithIp("ip"), "inner" )
countriesWithIpAddrMapped.show();
有没有一种不使用任何Web服务的方法可以做到这一点。。您可以下载ip和相应的国家/地区代码,并将其放入配置单元表中进行查找。这就行了。不用webservice调用,您可以将数据放入配置单元表中,然后使用
hiveContext.sql(s“从您的表中选择ip=$ip的国家”)
您的解决方案似乎不错,但只有一个问题,如何执行连接功能,因为必须检查两列:ip_from和ip_to??如果您觉得非常方便,请使用配置单元表方法,即选项2