【问题标题】:How to check if an string IP belongs to subnet in Hive如何检查字符串 IP 是否属于 Hive 中的子网
【发布时间】:2021-10-19 22:52:28
【问题描述】:

我正在编写 Hive 代码来检查 IP 是否属于子网。但是我拥有的 IP 是字符串格式的。在 SQL 中执行此操作的常用方法是:

ip::inet << '1.2.3.4'::inet

如何在 Hive 中做同样的事情?

【问题讨论】:

  • 我不认为 Hive 有像 Postgres 那样直接的方法。也许有人会出现并证明我错了(或发布一个可行但不太简单的解决方案)。

标签: hive hiveql


【解决方案1】:

正如@[Z4-tier] 所指出的,Hive 没有用于执行此操作的内置方法。 我能够在 python 中编写一个 udf,然后通过 hive 中的 ip 调用该函数。

def subnet_to_mask(subnet):
    c = int(subnet)
    mask = (0xffffffff >> (32 - c)) << (32 - c)
    return str((0xff000000 & mask) >> 24) + '.' + str((0x00ff0000 & mask) >> 16) + '.' + str((0x0000ff00 & mask) >> 8) + '.' + str((0x000000ff & mask))


def ip_to_number(ip):
    ip_no = 0
    for i, octet in enumerate(ip.split('.')):
        ip_no += int(octet) << (24 - (8 * i))
    return ip_no


def ip_in_subnet(ip, subnet):
    if len(subnet.split('/')) < 2:
        return ip == subnet.split('/')[0]
    else:
        network_ip, subnet = subnet.split('/')
        subnet = subnet_to_mask(subnet)
        return (ip_to_number(ip) & ip_to_number(subnet)) == (ip_to_number(network_ip) & ip_to_number(subnet))

然后您可以在 hiveql 中使用它,例如:

select ip, ip_in_subnet(ip, subnet) from tableABC;

【讨论】:

  • 这是我想到的“可行但不那么简单的解决方案”:)
猜你喜欢
  • 2014-02-20
  • 1970-01-01
  • 2012-04-12
  • 2017-10-30
  • 2018-09-14
  • 2012-04-17
  • 2013-06-12
  • 2012-09-28
  • 1970-01-01
相关资源
最近更新 更多