I am referring to this article in order to lookup IP addresses to country: https://cloud.google.com/blog/products/data-analytics/geolocation-with-bigquery-de-identify-76-million-ip-addresses-in-20-seconds
However, the public data set: fh-bigquery.geocode.201806_geolite2_city_ipv4_locs is no longer available. So I had to import my own look up table.
I have 2 tables in Bigquery:
Row| IP_CIDR (String)| Country_Code
-------------------------
1 | 160.181.205.0/24| ME
2 | 197.157.224.0/24| SL
3 | 196.32.200.0/21 | CF
4 | 160.181.224.0/24| SI
...
has 400K rows in BQ
and
Row| IP (String)
-------------------------
1 | 160.181.205.222
2 | 197.157.224.123
3 | 196.32.200.33
4 | 160.181.224.44
...
has 10k rows in BQ
How can I match the IP address to the IP_CIDR in another table such that the result would be:
Row| IP (String) |Country_Code
-------------------------
1 | 160.181.205.222 | ME
2 | 197.157.224.123 | SL
3 | 196.32.200.33 | CF
4 | 160.181.224.44 | SI
...
and null if IP not found in IP_CIDR
This is the original query recommended by the article:
WITH source_of_ip_addresses AS (
SELECT REGEXP_REPLACE(contributor_ip, 'xxx', '0') ip, COUNT(*) c
FROM `publicdata.samples.wikipedia`
WHERE contributor_ip IS NOT null
GROUP BY 1
)
SELECT country_name, SUM(c) c
FROM (
SELECT ip, country_name, c
FROM (
SELECT *, NET.SAFE_IP_FROM_STRING(ip) & NET.IP_NET_MASK(4, mask) network_bin
FROM source_of_ip_addresses, UNNEST(GENERATE_ARRAY(9,32)) mask
WHERE BYTE_LENGTH(NET.SAFE_IP_FROM_STRING(ip)) = 4
)
JOIN `fh-bigquery.geocode.201806_geolite2_city_ipv4_locs`
USING (network_bin, mask)
)
GROUP BY 1
ORDER BY 2 DESC

