Skip to main content

2  Look inside the file

You learn

  • the schemas and tables of a network file, the columns and their descriptions, the numbers of a table, the mode views, edges and nodes as GeoDataFrames, SQL on the file, your own DuckDB connection, what edge_id is

Extras duckosm[gis]

Run this chapter in Colab

Install duckOSM (for Colab)
# Install duckOSM when it is not installed (for example in Colab). It takes approximately 1 minute.
# Until duckOSM 0.9.0 is on PyPI, the SDK of these notebooks is in the nightly wheel of main (the GitHub pre-release "nightly").
# roadstyle (the maps) also comes from its nightly wheel, so the newest roadstyle parts work with no roadstyle release.
import importlib.util, json, os, urllib.request
def nightly_wheel(repo="Khoshkhah/duckOSM", name=".whl"):        # the address of the newest nightly wheel of a repository
    release = json.load(urllib.request.urlopen(f"https://api.github.com/repos/{repo}/releases/tags/nightly"))
    return next(a["browser_download_url"] for a in release["assets"] if name in a["name"] and a["name"].endswith(".whl"))
if importlib.util.find_spec("duckosm") is None:      # not installed: install it with the extras of this notebook
    %pip install -q "duckosm[gis] @ {nightly_wheel()}"
    %pip install -q --force-reinstall --no-deps "roadstyle @ {nightly_wheel('Khoshkhah/roadstyle', 'manylinux')}"
import duckosm             # the SDK
if not hasattr(duckosm, "network"):                    # an old duckOSM (0.8.0 or older), without the SDK
    %pip install -q --force-reinstall --no-deps "duckosm @ {nightly_wheel()}"
    raise SystemExit("duckOSM is updated: restart the session (in Colab: Runtime > Restart session), then run this cell again")
print("duckosm", duckosm.__version__)    # the version
# The network of chapter 1 (monaco.duckdb). The chapter opens it. When you run this chapter alone (in Colab), the file
# is not there, so this cell makes it one time.
if not os.path.exists("monaco.duckdb") or not duckosm.open("monaco.duckdb").has_mode("driving", "walking", "cycling"):
    duckosm.network(osm_id=2220322, modes=["driving", "walking", "cycling"], path="monaco.duckdb")

2.1 What is in a network file

A network file is one DuckDB database. A schema is a group of tables in it, as a folder holds files. Each mode that you build is one schema, with the same table names. The other schemas hold the data that all modes share.

Schema What it holds The main tables
driving, walking, cycling the network of one mode edges (the roads), nodes (the junctions), edge_graph (the turns from edge to edge), ways and way_nodes (the OSM ways of the mode), private_edges (roads that the mode cannot use)
main the facts of the area boundary (the polygon), global_junctions (the nodes of all modes), osm_source (the OSM file of the build), visualization_metadata (the build time, the version, the config)
raw the OSM data of the cut nodes, ways, relations
features the base map buildings, water_polygons, land, ocean, pois and more
visualization the drawing order edge_levels (which road is drawn over which: bridges over tunnels)
bus the bus lines routes, route_edges

The driving schema has three more tables: turn_restrictions (the “no left turn” rules of OSM), lane_profile (the lanes) and turn_path_restrictions. A build option that you turn off removes its schema (chapter 1, “The build options”).

The two tables that you use most are <mode>.edges and <mode>.nodes. An edge is one direction of a road between two nodes. A node is a point where edges meet. Each edge has a source node and a target node, so the edges and the nodes make a directed graph.

ImportantKey idea

A network file is a normal DuckDB database. Everything in this chapter is a read of its tables. You can read the same tables with SQL, with pandas or GeoPandas, or with any other DuckDB tool.

2.2 Open the network of chapter 1

Chapter 1 builds Monaco with three modes (driving, walking and cycling) and saves it as monaco.duckdb. This chapter opens that file with duckosm.open. It builds nothing.

net = duckosm.open("monaco.duckdb")
net
Network monaco
file monaco.duckdb (37.0 MB)
OSM data 2026-11-18 (Geofabrik monaco)
fixes none
saved yes
mode edges nodes km oneway_km
driving 2840 1768 96.2 35.5
walking 11938 4589 260.6 0.0
cycling 11305 4650 250.0 35.5

The card names the file and its size (37.0 MB), and says that it is saved. The table has one row for each mode: driving has 2840 edges, walking 11938 and cycling 11305.

2.3 The file and its modes

A Network is also the path of its file. net.path is a pathlib.Path, and each function that takes a file name takes net too. net.modes lists the schemas that have a road table. net.boundary is the polygon of the area as a GeoDataFrame. net.osm_version gives the version of the OSM data of the file: the time of the data, the Geofabrik extract and the SHA-256 of the OSM file (the table main.osm_source).

print(net.path.name)
print(net.modes)
net.boundary
monaco.duckdb
['driving', 'walking', 'cycling']
OGC_FID name osm_id admin_level area_km2 source geometry
0 0 Monaco 2220322 None 2.39 Nominatim MULTIPOLYGON (((7.40903 43.72958, 7.40908 43.7...

The boundary is one row: the relation 2220322, “Monaco”, 2.39 km2, from Nominatim. The geometry column is a MultiPolygon in longitude and latitude (EPSG:4326).

2.4 The tables: net.tables() and net.schema()

net.tables() gives the name of each table as schema.table. net.schema() gives one row for each table, with the number of rows, the number of columns and a description. The build writes each description into the file as a DuckDB comment. The text is the same as on the reference page The database schema.

tables = net.tables()
print(len(tables), "tables")
tables[:8]
54 tables
['bus.route_edges',
 'bus.routes',
 'cycling.edge_graph',
 'cycling.edge_id_map',
 'cycling.edges',
 'cycling.nodes',
 'cycling.private_edges',
 'cycling.turn_permission']
import pandas as pd
pd.set_option("display.max_colwidth", 120)
net.schema()
schema table rows columns description
0 bus route_edges 5621 6 One row for each route and edge.
1 bus routes 56 11 One row per route relation.
2 cycling edge_graph 31366 5 The graph of legal turns: one row for each pair of edges you can drive (or walk, or ride) one after the other. Edge-...
3 cycling edge_id_map 0 5 For each merged edge, the edges that it was made from. It can be empty, when no edges merge. Columns and use: edge_i...
4 cycling edges 11305 30 One row per direction of a road: a two-way road has two edges. What each mode keeps: What each network contains.
5 cycling nodes 4650 4 The ends of the routable edges.
6 cycling private_edges 133 24 The roads that the mode cannot use. They are drawn on the maps, but never routed and never exported.
7 cycling turn_permission 0 7 The turns that edge_graph cannot show: the turns of a restriction with an exception, a vehicle class or a condition....
8 cycling virtual_nodes 0 2
9 cycling way_nodes 17128 3 The nodes of ways, one row per node.
10 cycling ways 3001 17 The OSM ways the mode kept, after the road filter and any fixes.
11 driving edge_graph 6754 5 The graph of legal turns: one row for each pair of edges you can drive (or walk, or ride) one after the other. Edge-...
12 driving edge_id_map 0 5 For each merged edge, the edges that it was made from. It can be empty, when no edges merge. Columns and use: edge_i...
13 driving edges 2840 28 One row per direction of a road: a two-way road has two edges. What each mode keeps: What each network contains.
14 driving lane_profile 3318 7 Every driving edge's lanes, and every bus-only edge's (private_edges with access = 'bus'), decided once (design): on...
15 driving nodes 1768 4 The ends of the routable edges.
16 driving private_edges 687 22 The roads that the mode cannot use. They are drawn on the maps, but never routed and never exported.
17 driving turn_path_restrictions 0 8 Driving only. The OSM turn restrictions with a via **way**: they forbid or make necessary a path of edges, not one t...
18 driving turn_permission 0 7 The turns that edge_graph cannot show: the turns of a restriction with an exception, a vehicle class or a condition....
19 driving turn_restrictions 38 8 Driving only. OSM turn restrictions, and the turn rules of a fixes file, mapped to edges. Turn restrictions.
20 driving virtual_nodes 0 2
21 driving way_nodes 8370 3 The nodes of ways, one row per node.
22 driving ways 1205 17 The OSM ways the mode kept, after the road filter and any fixes.
23 features buildings 1259 6
24 features land 246 6
25 features ocean 1 6
26 features paved 83 6
27 features place_labels 10 6
28 features pois 1653 6
29 features public_transport 107 6
30 features sites 86 6
31 features streets 3513 6
32 features traffic 574 7
33 features water_lines 4 6
34 features water_polygons 91 6
35 main boundary 1 7 In a build from a PBF, the boundary file as read by DuckDB: one row per feature, a column per GeoJSON property, and ...
36 main global_junctions 4326 2 The nodes where every mode cuts its ways, so a way has the same edges in every mode. A node is in the table when two...
37 main osm_source 1 6 One row: the version of the OSM data that the database was built from. Only duckosm get and the build write it. The ...
38 main visualization_metadata 1 9 One row: where to open a map, and the time zone of the area.
39 raw nodes 34461 4
40 raw relations 339 5
41 raw ways 5685 3
42 visualization edge_levels 13452 9
43 visualization edge_levels_meta 1 6
44 visualization level_edits 0 6
45 walking edge_graph 35074 5 The graph of legal turns: one row for each pair of edges you can drive (or walk, or ride) one after the other. Edge-...
46 walking edge_id_map 0 5 For each merged edge, the edges that it was made from. It can be empty, when no edges merge. Columns and use: edge_i...
47 walking edges 11938 29 One row per direction of a road: a two-way road has two edges. What each mode keeps: What each network contains.
48 walking nodes 4589 4 The ends of the routable edges.
49 walking private_edges 158 23 The roads that the mode cannot use. They are drawn on the maps, but never routed and never exported.
50 walking turn_permission 0 7 The turns that edge_graph cannot show: the turns of a restriction with an exception, a vehicle class or a condition....
51 walking virtual_nodes 0 2
52 walking way_nodes 16810 3 The nodes of ways, one row per node.
53 walking ways 3205 17 The OSM ways the mode kept, after the road filter and any fixes.
NoteWhat the output shows

The file has 54 tables in eight schemas. The largest tables are the turns of walking (walking.edge_graph, 35074 rows) and the OSM nodes (raw.nodes, 34461 rows). Some tables have 0 rows: Monaco has no turn permissions and no virtual nodes, but the table is there, so the same query works on each file.

TipTip

The row counts of net.schema() are exact: it counts each table. DuckDB’s own duckdb_tables() gives only an estimate.

2.4.1 The tables of one schema

net.schema("driving") gives only the tables of one schema. A wrong name gives an error that lists the schemas of the file.

net.schema("main")
schema table rows columns description
0 main boundary 1 7 In a build from a PBF, the boundary file as read by DuckDB: one row per feature, a column per GeoJSON property, and ...
1 main global_junctions 4326 2 The nodes where every mode cuts its ways, so a way has the same edges in every mode. A node is in the table when two...
2 main osm_source 1 6 One row: the version of the OSM data that the database was built from. Only duckosm get and the build write it. The ...
3 main visualization_metadata 1 9 One row: where to open a map, and the time zone of the area.
NoteWhat the output shows

main has four tables: the boundary (1 row), the junctions of all modes (4326 rows), the OSM file of the build (1 row) and the metadata of the build (1 row). The description of global_junctions starts with “The nodes where every mode cuts its ways”. The description of boundary tells which columns the table has for each type of build.

2.5 The columns: net.columns()

net.columns(table) gives the columns of one table: the name, the DuckDB type and the description. Read it before you write SQL or a filter, to know the names and the types.

net.columns("driving.edges")
column_name column_type description
0 edge_id BIGINT the edge's id: (hash(osm_id, source, target) >> 1)::BIGINT. The same on every rebuild and in every mode. Stable edge...
1 edge_ref VARCHAR a readable id, {osm_id}#{seq} then f or r for the direction (for example 41790239#2f); seq counts the way's edges fr...
2 source BIGINT the node the edge starts at
3 target BIGINT the node the edge ends at
4 osm_id BIGINT the OSM way. A merged edge has the way at its source end. Negative for a connector edge
5 highway VARCHAR the OSM highway value
6 name VARCHAR the OSM name
7 oneway BOOLEAN TRUE when the edge has no reverse twin of the same way. Never NULL. One-way roads
8 lanes INTEGER lanes in this edge's direction. Never NULL, except on connector edges (osm_id < 0). Lanes
9 surface VARCHAR the OSM surface tag
10 access VARCHAR the mode's access: the value of its most specific access tag (driving: motorcar, motor_vehicle, vehicle, access; wal...
11 junction VARCHAR the OSM junction tag (roundabout, circular, …)
12 layer VARCHAR the OSM layer tag; NULL is ground level
13 bridge VARCHAR the OSM bridge tag (yes, viaduct, …)
14 tunnel VARCHAR the OSM tunnel tag (yes, building_passage, …)
15 service VARCHAR the OSM service tag of a highway=service road (driveway, parking_aisle, alley, …)
16 refs BIGINT[] the OSM node ids along the edge, from source to target
17 geometry GEOMETRY the line, from source to target
18 is_reverse BOOLEAN TRUE for the twin that runs against the way's drawing direction. A oneway=-1 way is turned round first, so its edge ...
19 length_m FLOAT length in meters
20 maxspeed_kmh FLOAT speed in km/h. Never NULL. Speeds and travel time
21 cost_s FLOAT travel time in seconds: length_m / (maxspeed_kmh / 3.6)
22 from_cell BIGINT H3 cell of source, at options.h3_resolution
23 to_cell BIGINT H3 cell of target
24 lca_res TINYINT resolution of the smallest H3 cell that holds both from_cell and to_cell
25 from_tile BIGINT tile key of source, at zoom 28
26 to_tile BIGINT tile key of target, at zoom 28
27 lca_zoom TINYINT zoom of the smallest tile that holds both from_tile and to_tile, 0 to 28
NoteWhat the output shows

Each column has its description: for edge_id it is the formula (hash(osm_id, source, target) >> 1)::BIGINT, for source “the node the edge starts at”. The first columns are the keys: edge_id, edge_ref, source, target and osm_id. Then come the OSM tags (highway, name, oneway, lanes, surface …), the geometry, and the values that the build adds: length_m, maxspeed_kmh and cost_s (the travel time in seconds). The last six columns are keys of H3 cells and map tiles, for fast spatial reads.

Column Type What it is
edge_id BIGINT the number of the edge. It is the same in every build and in every mode (section “What edge_id is”)
edge_ref VARCHAR a readable name: <osm_id>#<part>, then f or r for the direction
source, target BIGINT the node where the edge starts, and the node where it ends
osm_id BIGINT the OSM way of the edge
highway VARCHAR the road class of OSM: primary, residential, footway …
oneway BOOLEAN true when the road has one direction only
length_m FLOAT the length in meters
maxspeed_kmh FLOAT the speed limit in km/h: the OSM tag, or a default for the road class
cost_s FLOAT the travel time in seconds at maxspeed_kmh
geometry GEOMETRY the line of the edge, in longitude and latitude

2.5.1 Compare the modes

The edges tables of the modes have almost the same columns. Set operations on the column names show the differences.

driving = set(net.columns("driving.edges").column_name)
walking = set(net.columns("walking.edges").column_name)
cycling = set(net.columns("cycling.edges").column_name)
print("walking only:", walking - driving)
print("cycling only:", cycling - driving)
walking only: {'walk_type'}
cycling only: {'cycle_type', 'dismount'}

Walking adds walk_type (for example sidewalk, crossing or steps). Cycling adds cycle_type and dismount (true where you must push the bicycle). Every other column is the same in the three modes, so one query works on each mode.

2.6 The numbers of a table: net.summarize()

net.summarize(table) runs DuckDB’s SUMMARIZE. It gives one row for each column: the minimum, the maximum, the approximate number of distinct values, the average, the quartiles, the count and the percentage of NULL values. The geometry columns are left out. Use it to find the range of a column and the columns that are often empty.

s = net.summarize("driving.edges")
s[["column_name", "min", "max", "approx_unique", "null_percentage"]]
column_name min max approx_unique null_percentage
0 edge_id 414242052250797 9219879820648908565 2548 0.00
1 edge_ref 1000930347#1f 992499988#1f 2114 0.00
2 source -3945920869720410719 14358208416 1611 0.00
3 target -3945920869720410719 14358208416 1611 0.00
4 osm_id 4097656 1551240830 1187 0.00
5 highway living_street unclassified 11 0.00
6 name Accès Villa Yéyé Virage Antony Nogues 184 32.04
7 oneway false true 2 0.00
8 lanes 1 3 3 0.00
9 surface asphalt paving_stones 3 30.00
10 access customers yes 5 95.25
11 junction roundabout roundabout 1 94.58
12 layer -1 2 6 92.57
13 bridge yes yes 1 99.05
14 tunnel building_passage yes 2 92.99
15 service alley slipway 4 88.91
16 refs [21911886, 1737366161, 21911883, 6485591442, 1737366158, 1726583800, 1690130866] [14358208416, 9153994021, 3883559129, 25194134] 2810 0.00
17 is_reverse false true 2 0.00
18 length_m 0.7747368 1078.3915 2108 0.00
19 maxspeed_kmh 10.0 70.0 7 0.00
20 cost_s 0.05693591 77.64419 2119 0.00
21 from_cell 613499563497488383 613499564206325759 7 0.00
22 to_cell 613499563497488383 613499564206325759 7 0.00
23 lca_res 5 8 4 0.00
24 from_tile 1778020870636521500 1778021017797647580 1880 0.00
25 to_tile 1778020870323704732 1778021017787051612 1853 0.00
26 lca_zoom 12 24 10 0.00
NoteWhat the output shows

The driving edges are from 0.77 m to 1078 m long. The speed limits are from 10 to 70 km/h, with 7 different values. name is NULL for 32% of the edges (most of them are service roads), bridge is NULL for 99%: only 1% of the driving edges are on a bridge. approx_unique is an estimate: edge_id shows 2548, but each of the 2840 edges has its own edge_id.

2.7 The view of one mode

net.summary() gives one row for each mode (chapter 1). net.driving, net.walking and net.cycling (or net["driving"]) are mode views: a ModeView has the calls of the network, without mode=.

Calls of a mode view Same as
net.walking.edges(), .nodes() net.edges("walking"), net.nodes("walking")
net.walking.map(), .plot(), .dashboard() net.map("walking") … (chapter 3)
net.walking.route(a, b) and the other routes net.route(a, b, mode="walking") (chapter 7)
net.walking.to_sumo(...) and the other exports net.to_sumo(..., mode="walking") (chapter 6)
net.walking.summary() the row of walking in net.summary()
walk = net["walking"]
walk.summary()
mode edges nodes km oneway_km
0 walking 11938 4589 260.6 0.0

The view gives only the row of walking: 11938 edges, 4589 nodes and 260.6 km.

WarningWarning

A call that needs one network (a route, a graph, an export) stops with a DuckOSMError when the file has more modes and you give none. The message lists the modes and shows net['driving'].route(...). Use a mode view, or mode=. edges(), nodes(), map() and plot() work on all modes at once.

2.8 Edges and nodes as tables

net.edges() and net.nodes() read a table into a GeoDataFrame: a pandas DataFrame with a geometry column. edge_id comes as int64, the float columns as float64, and the rows are in the order of edge_id (of node_id for the nodes). You can then use all of pandas and GeoPandas.

Argument Default What it does
mode None one mode. None gives the one mode of the file, or all modes with a mode column
where None a SQL filter on the columns, for example "highway = 'primary'" (only edges)
crs EPSG:4326 the coordinate system of the result: an EPSG number, or "utm" for the UTM zone of the area
edges = net.driving.edges()
print(edges.shape, edges.crs)
edges[["edge_id", "edge_ref", "osm_id", "highway", "name", "length_m", "maxspeed_kmh", "cost_s"]].head()
(2840, 28) EPSG:4326
edge_id edge_ref osm_id highway name length_m maxspeed_kmh cost_s
0 414242052250797 4230114#3r 4230114 residential Boulevard du Ténao 44.240875 30.0 5.308905
1 2214154189574909 177052163#2f 177052163 service None 24.298845 20.0 4.373792
2 15757195119014288 128273233#1f 128273233 residential Rue du Ténao 9.057960 30.0 1.086955
3 16871577064511426 167625756#1f 167625756 residential None 3.996883 30.0 0.479626
4 21502429769987032 833633729#1f 833633729 residential None 3.554246 30.0 0.426510

2840 rows and 28 columns, in EPSG:4326 (longitude and latitude). The first rows are the smallest edge_id values.

2.8.1 Filter with where

where puts a SQL filter into the read. DuckDB reads only the rows that you ask for, and Python gets only these rows, not the full table.

primary = net.edges("driving", where="highway IN ('primary', 'primary_link')")
print(len(primary), "edges,", round(primary.length_m.sum() / 1000, 1), "km")
218 edges, 12.3 km

218 edges, 12.3 km: the primary and primary_link rows of the SQL table in the section “SQL on the file” below.

WarningWarning

The text of where goes into the query as it is. Give only text that you write yourself, never text that a user of your program types.

2.8.2 Lengths in meters: crs="utm"

The geometry in longitude and latitude has degrees, not meters. crs="utm" gives the edges in the UTM zone of the area (EPSG:32632 for Monaco), so .length and .area are in meters.

utm = net.edges("driving", crs="utm")
print(utm.crs)
print(round(utm.length.sum() / 1000, 1), "km from the geometry")
print(round(utm.length_m.sum() / 1000, 1), "km from length_m")
EPSG:32632
96.3 km from the geometry
96.2 km from length_m

The geometry gives 96.3 km and length_m gives 96.2 km. The small difference comes from the UTM projection: length_m is measured on the sphere.

2.8.3 All modes in one table

With more modes in the file and no mode, net.edges() gives the edges of all modes in one GeoDataFrame, with a mode column. A road that more modes can use is in it once for each mode, with the same edge_id.

all_edges = net.edges()
all_edges["mode"].value_counts()
mode
walking    11938
cycling    11305
driving     2840
Name: count, dtype: int64

26083 rows: 11938 walking, 11305 cycling and 2840 driving. The table has the columns of all modes. walk_type is empty for driving and cycling.

2.8.4 The nodes

net.nodes(mode) gives the junctions of a mode: node_id, the point geometry, and the keys h3_cell and tile. The node ids are OSM node ids. A negative id is a node that the build added (for example to split a road that comes back to its start).

nodes = net.nodes("walking")
print(len(nodes), "nodes")
nodes.head(3)
4589 nodes
node_id h3_cell tile geometry
0 -4477278223805530165 613499563497488383 1778020967615141660 POINT (7.4142 43.73102)
1 -4385765079388595572 613499563499585535 1778020965166870812 POINT (7.42126 43.73148)
2 -3945920869720410719 613499563587665919 1778020871309990684 POINT (7.42338 43.74088)

The walking network has 4589 nodes. The rows are in the order of node_id, so the first rows are the nodes that the build added, with negative ids. h3_cell and tile are the keys of the H3 cell and of the map tile of the node.

2.9 SQL on the file: net.sql()

net.sql(query) runs a SQL query on the file and gives a pandas DataFrame. The connection is read-only, so a query cannot change the file. The DuckDB extension spatial is loaded, so the ST_ functions work. Use SQL for counts, sums and joins: DuckDB computes them in the file, and Python gets only the result. The query below puts the driving edges into groups by road class (GROUP BY highway), and gives the number of edges and their length in km for each group.

net.sql("""
    SELECT highway, count(*) AS edges, round(sum(length_m) / 1000, 1) AS km
    FROM driving.edges
    GROUP BY highway
    ORDER BY edges DESC
""")
highway edges km
0 residential 919 31.7
1 service 855 23.7
2 secondary 429 14.9
3 tertiary 387 12.5
4 primary 197 11.2
5 primary_link 21 1.1
6 unclassified 13 0.6
7 secondary_link 13 0.4
8 tertiary_link 3 0.1
9 living_street 3 0.1

Residential streets (919 edges, 31.7 km) and service roads (855 edges, 23.7 km) are more than half of the driving network. The primary roads have 197 edges and 11.2 km.

2.9.1 Values in a query: params

Put a value into a query with $name (or ?) and params, not with Python text. DuckDB then reads the value as a value, and a quote in a name cannot break the query.

net.sql("SELECT edge_id, edge_ref, length_m FROM driving.edges WHERE name = $name ORDER BY edge_ref",
        {"name": "Boulevard Albert 1er"})
edge_id edge_ref length_m
0 5502834370235035868 1019174508#1f 41.102180
1 4394827224625659348 1019174508#2f 4.882707
2 8440276820059948046 1019174508#3f 90.155556
3 8561693764026542227 1019174508#4f 5.178436
4 8037909646003515605 1453878835#1f 23.786472
5 2037729375342856465 161882794#1f 34.672100
6 8365478864863133107 166399479#1f 5.890634
7 1873918904400324117 166399479#2f 87.658560
8 3622281415122805437 166399479#3f 15.597761
9 3325892313673521836 166399479#4f 3.941422
10 4551155039579564675 166399479#5f 102.818760
11 8490008389062041083 176776331#1f 11.562247
12 4645040206921207372 176776331#2f 91.228760
13 7631432005107543199 176776331#3f 5.231566
14 4357090561864510735 176776331#4f 5.962183
15 4535601100623855388 176776331#5f 101.914030
16 7103909789242648383 176776331#6f 5.132938
17 2478527519211067132 176776331#7f 105.471190
18 570930183709886355 176776331#8f 25.228455
19 8511077704723192952 4226740#1f 45.404037

The Boulevard Albert 1er has 20 driving edges, from 6 OSM ways. All of them are one-way: each edge_ref ends with f.

2.9.2 Spatial SQL

The spatial functions work on the geometry columns. The query below counts the driving edges within 200 m of the casino square of Monte Carlo. The geometry is in degrees, so the query first changes it to meters (the UTM zone of Monaco, EPSG:32632).

Function What it does
ST_Point(lon, lat) a point
ST_Transform(g, 'EPSG:4326', 'EPSG:32632', always_xy := true) the geometry g in meters. always_xy := true tells DuckDB that the points are longitude first
ST_DWithin(a, b, 200) true when a and b are 200 m apart or less
net.sql("""
    SELECT count(*) AS edges
    FROM driving.edges
    WHERE ST_DWithin(ST_Transform(geometry, 'EPSG:4326', 'EPSG:32632', always_xy := true),
                     ST_Transform(ST_Point(7.4280, 43.7393), 'EPSG:4326', 'EPSG:32632', always_xy := true), 200)
""")
edges
0 223

223 driving edges are within 200 m of the casino square.

2.10 Your own DuckDB connection: net.connect()

net.sql() opens a connection for each query and gives pandas. net.connect() gives a read-only DuckDB connection that stays open, with spatial loaded. Use it for many queries in a row, for DuckDB relations, for Arrow (.arrow()) or for Polars (.pl()). Close it after use: a with block closes it for you.

with net.connect() as con:
    steps = con.sql("SELECT edge_id, name, length_m FROM walking.edges WHERE highway = 'steps'")
    table = steps.to_arrow_table()
    frame = steps.df()
print(table.num_rows, "steps in Arrow,", len(frame), "steps in pandas")
1038 steps in Arrow, 1038 steps in pandas

The walking network has 1038 edges that are steps. steps is a DuckDB relation: a query, not data. DuckDB runs it each time that you ask for a result: to_arrow_table() gives a pyarrow Table, df() gives pandas, and pl() gives Polars.

WarningWarning

In DuckDB 1.5, .arrow() gives a RecordBatchReader, which reads the rows only when you use it. Read it to the end (.read_all()) before the connection closes. A reader that you do not read keeps the query open, and the next query on the file can wait for it. to_arrow_table() reads all rows at once.

TipTip

You can also open the file with duckdb.connect(str(net.path), read_only=True). Then load the extension yourself: con.load_extension("spatial").

2.11 What edge_id is

edge_id is the key of an edge. It is a number of type BIGINT (64 bits). The build computes it from three values of the edge: the OSM way (osm_id) and the two nodes (source, target).

A two-way road is two edges: each direction has its own edge_ref and edge_id

A two-way road is two edges: each direction has its own edge_ref and edge_id

The edge_id has four properties. The table says why each one is important for your data.

Property Why it is important
It comes from the OSM data, not from the row number a new build of the same OSM data gives the same edge_id to each edge
Each direction has its own number source and target change places, so the two edges of a two-way road get different numbers
It is the same in each mode a street with a sidewalk has the same edge_id in driving.edges and in walking.edges
It is a BIGINT keep it as int64 in pandas. A float64 loses the last digits (chapter 4)

edge_ref is a second name of an edge that people can read. It can change when a way gets more nodes in OSM, so join your data on edge_id, not on edge_ref.

ImportantKey idea

edge_id is the key between duckOSM and your data. It stays the same when you build the area again and it is the same in each mode, so data that you join on it stays correct.

2.11.1 Two edges for a two-way road

The OSM way 4230114 is a two-way street. Each part of the way between two nodes gives two edges: f in the drawing direction of the way, r against it.

net.sql("""
    SELECT edge_id, edge_ref, source, target, is_reverse
    FROM driving.edges WHERE osm_id = 4230114 ORDER BY edge_ref
""")
edge_id edge_ref source target is_reverse
0 925170278510060820 4230114#1f 21921299 3625063392 False
1 7518368909814682313 4230114#1r 3625063392 21921299 True
2 3093664370798973039 4230114#2f 3625063392 1080509801 False
3 8638126748304063112 4230114#2r 1080509801 3625063392 True
4 4950030941241418106 4230114#3f 1080509801 1868723946 False
5 414242052250797 4230114#3r 1868723946 1080509801 True

Three parts of the way give six edges. The two edges of each part have the same nodes in the other order, and two very different numbers: 4230114#3f is 4950030941241418106, 4230114#3r is 414242052250797. is_reverse is true for the r edges.

2.11.2 Compute an edge_id

duckosm.edge_id_hash(osm_id, source, target) computes the edge_id in Python. The same formula is in each file as the SQL macro edge_id_hash. duckosm.edge_id_expr() gives the SQL text of the formula, for your own queries.

row = edges.iloc[0]
print(row.edge_id, duckosm.edge_id_hash(row.osm_id, row.source, row.target))
print(duckosm.edge_id_expr())
414242052250797 414242052250797
(hash(osm_id::BIGINT, source::BIGINT, target::BIGINT) >> 1)::BIGINT
net.sql("SELECT count(*) AS different FROM driving.edges WHERE edge_id <> edge_id_hash(osm_id, source, target)")
different
0 0

The Python function gives the same number as the column. The SQL macro agrees for all 2840 driving edges: 0 are different.

Call Gives
duckosm.edge_id_hash(osm_id, source, target) the edge_id of one edge
duckosm.edge_id_expr("osm_id", "source", "target") the SQL text of the formula, with your column names
duckosm.edge_id_hash_v1(...), duckosm.edge_id_expr_v1(...) the previous formula, with is_reverse: to connect old ids to new ids
duckosm.create_edge_id_macro(con) writes the two SQL macros into a DuckDB database of yours
WarningWarning

The formula uses DuckDB’s hash(). Another DuckDB major version can give other numbers. duckOSM pins DuckDB 1.x for this reason. Outside DuckDB, join on the three columns osm_id, source and target.

2.11.3 The same edge in each mode

A road that more modes can use has the same edge_id in each mode. JOIN ... USING (edge_id) keeps the pairs of rows that have the same edge_id, so a join of two edges tables gives the roads that the two modes share.

net.sql("SELECT count(*) AS edges FROM driving.edges JOIN walking.edges USING (edge_id)")
edges
0 2201
print(len(all_edges), "rows,", all_edges.edge_id.nunique(), "different edges")
26083 rows, 13302 different edges

2201 of the 2840 driving edges are also walking edges. The table of the three modes (section “All modes in one table”) has 26083 rows, but only 13302 different edges, because most roads are in two or three modes.

2.12 Try it yourself

1. Find the five longest walking edges that have a name. Use net.sql.

net.sql("SELECT name, highway, round(length_m) AS m FROM walking.edges WHERE name IS NOT NULL ORDER BY length_m DESC LIMIT 5")

2. Which columns of walking.edges are NULL for more than 90% of the rows?

s = net.summarize("walking.edges")
s[s.null_percentage > 90].column_name.tolist()

3. Get the steps of the walking network as a GeoDataFrame in meters, and give their total length in km.

steps = net.walking.edges(where="highway = 'steps'", crs="utm")
round(steps.length.sum() / 1000, 1)

4. Count the driving edges that are not in the walking network, by road class.

net.sql("""SELECT highway, count(*) AS n FROM driving.edges
           WHERE edge_id NOT IN (SELECT edge_id FROM walking.edges)
           GROUP BY highway ORDER BY n DESC""")

2.13 Words in this chapter

Word Meaning
schema a group of tables in a DuckDB file: one for each mode, and main, raw, features …
table rows and columns in a schema, named schema.table, for example driving.edges
description the text of a table or a column, written into the file as a DuckDB comment
ModeView the view of one mode: net.walking, with the calls of the network and no mode=
GeoDataFrame a pandas DataFrame with a geometry column (GeoPandas)
CRS the coordinate system of a geometry: EPSG:4326 (degrees) or a UTM zone (meters)
edge_ref the readable name of an edge, <osm_id>#<part>f or r. It can change
edge_id the key of an edge: a hash of osm_id, source and target, the same in each build and mode
relation (DuckDB) a query that DuckDB runs only when you ask for its result

2.14 Summary

Call Does
net.path, net.modes, net.boundary the file, the modes, the polygon of the area
net.tables() the tables, as schema.table
net.schema(schema=None) one row for each table: rows, columns, description
net.columns(table) the columns of a table: name, type, description
net.summarize(table) DuckDB’s SUMMARIZE: the range, the distinct values and the NULLs of each column
net.summary(), net.walking, net["walking"] one row for each mode, and the view of one mode
net.edges(mode, where=, crs=) the edges as a GeoDataFrame
net.nodes(mode, crs=) the nodes as a GeoDataFrame
net.sql(query, params=None) a SQL query on the file, as a DataFrame
net.connect() a read-only DuckDB connection with spatial
duckosm.edge_id_hash(...), duckosm.edge_id_expr() the formula of edge_id, in Python and as SQL

The reference: Python SDK, What is in the file and The database schema. Next: 3. Draw maps, the live map, the dashboard and the static picture.