Skip to content
Page cover
For the complete documentation index, see llms.txt. This page is also available as Markdown.

SQL Database

How AISdb organizes decoded AIS messages across SQLite and PostgreSQL/TimescaleDB tables, and how to query them directly with SQL.

AISdb stores decoded AIS messages in a relational database rather than flat files, which is what makes range queries, joins across message types, and multi-year aggregations practical. Two backends are supported. SQLite is the default for local work, a single-file database that needs no server and is easy to copy or drop into version control for small projects. PostgreSQL is the option for shared or production deployments, and it can optionally run on top of TimescaleDB for large, high-ingest-rate collections. Both backends expose the same table layout and the same DBQuery/TrackGen query interface, so switching between them later mostly means swapping the connection object.

Choosing a Database Backend

Every AISdb database connection is opened through one of two classes in aisdb.database.dbconn, both of which subclass a shared DBConn base and both of which support the context manager protocol (with ... as dbconn:).

SQLiteDBConn wraps a sqlite3.Connection and only needs a filesystem path. If the file does not exist yet, it will be created the first time you decode messages into it.

from aisdb import SQLiteDBConn

dbpath = "AIS.db"

with SQLiteDBConn(dbpath) as dbconn:
    # decode_msgs, DBQuery, and custom SQL all use this connection
    ...

PostgresDBConn wraps a psycopg connection and accepts either a libpq connection string or individual keyword arguments (host, port, user, dbname, password, and any other keyword recognized by libpq).

import os
from aisdb import PostgresDBConn

# Option 1: keyword arguments
with PostgresDBConn(
    host="127.0.0.1",
    port=5432,
    user="postgres",
    dbname="postgres",
    password=os.environ.get("POSTGRES_PASSWORD"),
) as dbconn:
    ...

# Option 2: a libpq connection string
with PostgresDBConn(libpq_connstring="postgresql://localhost:5432/postgres") as dbconn:
    ...

Pick SQLite for quick exploration on your own machine, and PostgreSQL when several people or processes need to read and write the same database, when the collection grows past what a single SQLite file handles comfortably, or when you plan to enable TimescaleDB (see below). Regardless of the backend, decode_msgs accepts either connection type as its dbconn argument, and the same DBQuery/TrackGen code works unchanged against both.

Table Naming

When loading data into the database, messages are sorted into SQL tables determined by the message type and month. The table names follow this format, where {YYYYMM} is the four-digit year and two-digit month.

Some additional tables containing computed data may be created depending on the indexes used. Examples include an aggregate of vessel static data by month and a virtual table used as a covering index.

Additional tables are also included for storing data not directly derived from AIS message reports.

For quick reference to data types and detailed explanations of these table entries, please see the Detailed Table Description.

Custom SQL Queries

In addition to querying the database using the DBQuery module, there is an option to customize the query with your own SQL code. The examples below connect directly with sqlite3, which works against an SQLite database file. Against PostgreSQL, swap sqlite3.connect(dbpath) for psycopg.connect(...) (or reuse the connection already opened through aisdb.PostgresDBConn) and the same SQL runs unchanged, since both backends share identical table and column names.

Example of listing all the tables in your database:

As messages are separated into tables by message type and month, queries spanning multiple message types or months should use UNIONs and JOINs to combine results as appropriate.

Example of querying tables with JOIN:

Each row in results is a plain tuple, one element per selected column, in the order listed in the SELECT. A row from the query above looks like this.

The exact rows you see depend on what is in your database. Rows come back in whatever order SQLite returns them unless you add an ORDER BY clause, and vessel_name/ship_type will be None for any MMSI with no matching row in the static table (since the query uses a LEFT JOIN).

More information about SQL queries can be found in online tutorials.

The ais_{YYYYMM}_dynamic tables are created with a composite primary key over (mmsi, time, longitude, latitude, sog, cog, source) on SQLite, which acts as a covering index for the queries DBQuery generates. Filtering on a narrow range of MMSIs, timestamps, longitudes, and latitudes lets SQLite satisfy most of the query directly from that index, so query performance improves the more you narrow those bounds. Broad, unbounded queries will scan a much larger share of the table and will not benefit as much. If you need custom indexes for a specific manual query, define them directly on the monthly ais_{YYYYMM}_dynamic and ais_{YYYYMM}_static tables rather than trying to add a separate index structure alongside them.

Timestamps are stored as epoch seconds in the database (seconds since 1970-01-01 UTC), matching the time column described in the Detailed Table Description. To facilitate querying the database manually, use the dt_2_epoch() function to convert datetime values to epoch seconds and the epoch_2_dt() function to convert epoch seconds back to datetime values. Here is how you can use dt_2_epoch() with the example above:

For more examples, please see the SQL code in aisdb_sql/ that is used to create database tables and associated queries.

Optional TimescaleDB Backend

TimescaleDB is a PostgreSQL extension for time-series data, and AISdb can use it in place of the plain PostgreSQL table layout described above. It is entirely optional. If your PostgreSQL server has the extension installed, opt in when decoding messages by passing timescaledb=True to decode_msgs:

With timescaledb=True, AISdb creates the monthly ais_{YYYYMM}_dynamic and ais_{YYYYMM}_static tables as hypertables partitioned on time (and space-partitioned on mmsi), rather than as plain PostgreSQL tables. This is what lets TimescaleDB spread the ingest and query workload for a large, continuously growing AIS collection across many chunks instead of one ever-larger table. The column layout is identical to the plain PostgreSQL schema, so DBQuery, custom SQL, and everything else on this page works the same way regardless of whether TimescaleDB is enabled underneath.

PostgresDBConn also exposes a few maintenance methods that are aware of the timescaledb flag, useful when you are managing indexes or cleaning up a bulk ingest by hand.

Dropping the indexes before a large bulk insert and rebuilding them afterward is significantly faster than maintaining the indexes row by row during the insert. Pass timescaledb=False (the default) for these same methods against a plain PostgreSQL database, which manages indexes named idx_{YYYYMM}_dynamic_mmsi, idx_{YYYYMM}_dynamic_time, idx_{YYYYMM}_dynamic_longitude, and idx_{YYYYMM}_dynamic_latitude instead of the two combined TimescaleDB indexes.

Detailed Table Description

ais_{YYYYMM}_dynamic tables
Column
Data Type
Description

mmsi

INTEGER

Maritime Mobile Service Identity, a unique identifier for vessels.

time

INTEGER

Timestamp of the AIS message, in epoch seconds.

longitude

REAL

Longitude of the vessel in decimal degrees.

latitude

REAL

Latitude of the vessel in decimal degrees.

rot

REAL

Rate of turn, indicating how fast the vessel is turning.

sog

REAL

Speed over ground, in knots.

cog

REAL

Course over ground, in degrees.

heading

REAL

Heading of the vessel, in degrees.

maneuver

BOOLEAN

Indicator for whether the vessel is performing a special maneuver.

utc_second

INTEGER

Second of the UTC timestamp when the message was generated.

source

TEXT

Source of the AIS data.

ais_{YYYYMM}_static tables
Column
Data Type
Description

mmsi

INTEGER

Maritime Mobile Service Identity, a unique identifier for vessels.

time

INTEGER

Timestamp of the AIS message, in epoch seconds.

vessel_name

TEXT

Name of the vessel.

ship_type

INTEGER

Numeric code representing the type of ship.

call_sign

TEXT

International radio call sign of the vessel.

imo

INTEGER

International Maritime Organization number, another unique vessel identifier.

dim_bow

INTEGER

Distance from the AIS transmitter to the bow (front) of the vessel.

dim_stern

INTEGER

Distance from the AIS transmitter to the stern (back) of the vessel.

dim_port

INTEGER

Distance from the AIS transmitter to the port (left) side of the vessel.

dim_star

INTEGER

Distance from the AIS transmitter to the starboard (right) side of the vessel.

draught

REAL

Maximum depth of the vessel's hull below the waterline, in meters.

destination

TEXT

Destination port or location where the vessel is heading.

ais_version

INTEGER

AIS protocol version used by the vessel.

fixing_device

TEXT

Type of device used for fixing the vessel's position (e.g., GPS).

eta_month

INTEGER

Estimated time of arrival month.

eta_day

INTEGER

Estimated time of arrival day.

eta_hour

INTEGER

Estimated time of arrival hour.

eta_minute

INTEGER

Estimated time of arrival minute.

source

TEXT

Source of the AIS data (e.g., specific AIS receiver or data provider).

static_{YYYYMM}_aggregate tables
Column
Data Type
Description

mmsi

INTEGER

Maritime Mobile Service Identity, a unique identifier for vessels.

imo

INTEGER

International Maritime Organization number, another unique vessel identifier.

vessel_name

TEXT

Name of the vessel.

ship_type

INTEGER

Numeric code representing the type of ship.

call_sign

TEXT

International radio call sign of the vessel.

dim_bow

INTEGER

Distance from the AIS transmitter to the bow (front) of the vessel.

dim_stern

INTEGER

Distance from the AIS transmitter to the stern (back) of the vessel.

dim_port

INTEGER

Distance from the AIS transmitter to the port (left) side of the vessel.

dim_star

INTEGER

Distance from the AIS transmitter to the starboard (right) side of the vessel.

draught

REAL

Maximum depth of the vessel's hull below the waterline, in meters.

destination

TEXT

Destination port or location where the vessel is heading.

eta_month

INTEGER

Estimated time of arrival month.

eta_day

INTEGER

Estimated time of arrival day.

eta_hour

INTEGER

Estimated time of arrival hour.

eta_minute

INTEGER

Estimated time of arrival minute.

Where to go next

The database loading tutorial walks through decoding raw AIS messages into these tables from scratch, and the data querying tutorial covers DBQuery and TrackGen in more depth than the quick reference above. Reach for the custom SQL approach on this page when you need a query shape those two interfaces do not support directly.

Last updated