【问题标题】:Retrieving the geo location(region or continent) from an IP address using SparkSQL使用 SparkSQL 从 IP 地址检索地理位置(地区或大陆)
【发布时间】:2017-04-30 14:55:18
【问题描述】:

我有一个包含一组 IP 地址的表格列,我需要找出它的区域/大陆,如下所述。

------------------------------------------------------
ip_address      |    region
------------------------------------------------------
217.100.34.222  |   North Holland

为此,我从ip2location.com 下载了一个 IP-Country-Region-City 数据库,但其表和值如下所示。

-----------------------------------------------------
ip_from  | ip_to  | country_code  |  country_name  | region_name  |  city_name
-----------------------------------------------------
16777216 | 16777471 | AU          | Australia      | Queensland   | Brisbane

如何将我的ip_address 列转换为decimal number,如 ip2location 数据库中所示并从中检索数据,或者是否有更好的方法来执行此过程以检索@ 987654326@ 来自ip address

谢谢。

【问题讨论】:

    标签: sql apache-spark apache-spark-sql hiveql


    【解决方案1】:

    执行此过程以检索地理位置的更好方法 从使用 SparkSQL 的 IP 地址?

    选项 1

    正如关于广告分析的数据块所述,这是一种方式。请查看完整文章- an-illustrated-guide-to-advertising-analytics.html

    直接从 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:Hive 表方法,例如带有 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();
    

    【讨论】:

    • 有没有办法在不使用任何网络服务的情况下做到这一点?
    • AFAIK 可能有..你可以下载 ip 和相应的国家代码并放入 hive 表中查找。那会奏效的。
    • 您可以将数据放入配置单元表并使用hiveContext.sql(s"select country from your table where ip =$ip" ),而不是使用网络服务调用
    • 您的解决方案似乎很好,但只有一个问题,如何执行连接功能,因为必须检查两列:ip_from 和 ip_to ??
    • 如果您觉得它非常方便,请使用 hive table 方法,即选项 2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多