Introduction
GeoLite2 is a free, monthly updated IP geolocation database offered by MaxMind. It is available to download in binary or CSV formats.
The GeoLite2 database can help you determine the City or Country location of an IP (within a reasonable degree of accuracy) as well as the ISP/Organisation that owns it.
Prerequisites
Before following this tutorial make sure you have:
- An installation of PostgreSQL 9.6 or greater.
Step 1 - Download GeoLite2
Download and unzip the CSV formatted versions of the GeoLite2 databases from MaxMind to a location on your system e.g. /tmp/
Step 2 - Import GeoLite2 CSV files to PostgreSQL
Login to your PostgreSQL database using psql
or your preferred database IDE (e.g. DataGrip, DBeaver) and run the following SQL statements to create the necessary tables and import the Geolite2 (City & ASN) data from the CSV files you extracted in Step 1:
Import GeoLite2’s city and ASN network blocks and city locations
Note: If you don’t require the granularity or resolution of city names or the ASN database you can import only the country geoip blocks and locations by running the statements in the Import GeoLite2’s country network blocks and locations section:
You may encounter the following error (particularly if connecting to a remote database such as AWS RDS or Google Cloud SQL via a client/psql using a non-superuser account):
In this case the simplest option is to run the CREATE
statements and copy
commands independently, but in order. Like the ‘HINT’ states, psql’s \copy meta command can be used to copy the files from your client computer to your database:
If you’re client computer is a Windows system you may need to include an encoding option (UTF8
) with the \copy command when importing the GeoLite2-City-Locations-en.csv
file to avoid encoding compatibility errors:
Note: Since some of GeoLite2’s CSV files are up to 190MB in size, depending on your available bandwidth the \copy commands may take a while when working with remote cloud databases via psql/client
Import GeoLite2's country network blocks and locations
Conclusion
You’ve now successfully imported MaxMind’s GeoLite2 database to your PostgreSQL database.
You can now run various queries against the geoip_blocks
, asn_blocks
and geo_locations
tables to lookup various geolocation info on IP addresses.
Example 1
Lookup the network
, city_name
, country_name
and country_iso_code
of an IP address
Result:
Example 2
Lookup the network
and autonomous_system_organization
of an IP address
Result:
Example 3
A common use case is batch resolving a table (table_with_ips
) containing IP addresses. For example you may have a table containing a column of IPs, ip_address
, each of which requires the corresponding geolocation resolved and stored in the ip_country
column.
Run an UPDATE JOIN
statement using the geoip_locations
and geoip_blocks
tables:
Result: