Geospatial Data

Waratah knows geometry natively: geometry values are literals in your data, spatial questions are SPARQL functions, and an S2 cell index makes those questions fast. The support follows GeoSPARQL conventions, so existing geo RDF tends to work unchanged.

The plugin is always active — no setup, no flag. For a worked setup and the practices that keep spatial queries correct and fast, see Geospatial Best Practices.

Geometry literals

A geometry is a typed literal. The everyday form is WKT text with the geo:wktLiteral datatype:

"POINT(153.02 -27.46)"^^<http://www.opengis.net/ont/geosparql#wktLiteral>

Without a coordinate reference system (CRS) prefix the coordinates are CRS84: longitude first, latitude second. A prefix may name another CRS, and the coordinates then follow that CRS’s own axis order — latitude first for EPSG:4326:

"<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.46 153.02)"^^<http://www.opengis.net/ont/geosparql#wktLiteral>

Waratah accepts CRS84 and the geographic CRSs EPSG:4326, 4283, 7844, 9309, 4167, and 4272. It transforms them to CRS84 internally and transforms back on output, so the two literals above describe the same place. Any other CRS, including projected CRSs such as Web Mercator (EPSG:3857), is rejected when the data is loaded.

Points, lines, polygons, the multi-geometries, and geometry collections are all accepted, and Z and M coordinates are accepted and returned unchanged. Z does not take part in the datum transform. The binary geo:wkbLiteral form is accepted as hex WKB or EWKB, and its coordinates are always longitude/latitude whatever the SRID says.

Query results and STR() render a stored geometry in a canonical spelling — POINT(153.02 -27.46), with no space before the parenthesis and none after commas — in the CRS it was loaded with; CRS84 is written without a prefix. Spacing in the source text is not reconstructible from the stored value.

The same coordinates written under two CRSs are different RDF terms: =, sameTerm, and DISTINCT treat them as different. Every spatial function compares places, so they still match each other.

Attach the literal to your resources like any other value (Turtle syntax, part of an example dataset used throughout this page):

@prefix ex: <http://ex/> .
@prefix geo: <http://www.opengis.net/ont/geosparql#> .

ex:brisbane ex:name "Brisbane" ;
            geo:hasGeometry "POINT(153.02 -27.46)"^^geo:wktLiteral .

ex:ipswich  ex:name "Ipswich" ;
            geo:hasGeometry "POINT(152.90 -27.60)"^^geo:wktLiteral .

ex:sydney   ex:name "Sydney" ;
            geo:hasGeometry "POINT(151.20 -33.87)"^^geo:wktLiteral .

Load it as you would any RDF file — for example into a running cluster:

waratah import places.ttl --connect

For a single-process store instead:

waratah import places.ttl --data-dir ./waratah-data --offline
waratah standalone --data-dir ./waratah-data

Validity and index completeness

A stored geometry must have a native indexed form. Waratah tolerates two narrow classes of defect:

  • Very small contact between polygon members of the same MULTIPOLYGON: cumulative overlap no larger than 0.00000001 square degrees, or cumulative shared boundary no longer than 0.00000001 degrees. A shared edge means exactly collinear boundary segments; near-collinear edges are handled by the normal validity or overlap rule, not by a distance epsilon.

  • An exactly retraced, zero-area spike in a polygon ring. The retraced edges must be exactly collinear. Waratah removes the backtracking only for spatial evaluation, after checking that the reduced geometry is valid and its area is unchanged within floating-point noise. The stored binary geometry and STR() output keep the original coordinates; the spatial functions use the reduced valid region. Each accepted literal produces a warning with its subject and removed-vertex count, and waratah import prints the total number reduced.

Larger contact totals, longer shared boundaries, non-collinear self-intersections, real member overlap, and all other parse, coordinate-reference-system, shape, or validation failures stop the insert or import with an error that identifies the problem. A load over HTTP answers 400 with the same message. The common cases, with the text of the error:

  • Text that is not WKT or WKB — unparseable geometry literal.

  • An unsupported CRS — unsupported CRS: http://www.opengis.net/def/crs/EPSG/0/3857.

  • A self-intersecting or otherwise invalid shape — invalid geometry: geometry validation failed: exterior ring has a self-intersection.

  • MULTIPOLYGON members that overlap by real area — invalid geometry: multi-polygon members at indices 0 and 1 overlap by 5.000e-1 deg².

  • An EMPTY geometry — unsupported geometry shape: EMPTY geometry: POINT EMPTY.

  • A geometry collection whose covering exceeds 1024 S2 cells — unsupported geometry shape: geometry collection covering has 1575 distinct cells, above the 1024 cell limit.

Two things are not checked. Coordinate ranges are taken as given: a latitude of -100 is stored. And a ring that is not explicitly closed is closed automatically.

This is deliberate: storing a geometry without its index postings would let an indexed spatial filter silently omit it. A geo index rebuild follows the same rule. If an existing geometry cannot be upgraded, the rebuild stops and leaves the index untrusted instead of marking an incomplete index as ready. A legacy native geometry with a tolerated spike but without the reduction marker must be re-ingested before it can be rebuilt safely.

An index built before this validation policy may omit a geometry that a new import would accept. Rebuild it on a stopped store after upgrading:

waratah geo rebuild-index --data-dir ./waratah-data

Geometry validation runs once per import chunk. If a chunk contains invalid geometry, that chunk is not written, but earlier chunks remain loaded. Fix the source geometry, re-ingest the corrected file, then rebuild the geo index from scratch on a stopped store with the command above.

The three spatial functions

Function True when

geof:sfContains(a, b)

Geometry a contains geometry b.

geof:sfWithin(a, b)

Geometry a is inside geometry b.

geof:sfIntersects(a, b)

The two geometries share at least one point.

Each takes two geometry literals and returns a boolean; evaluation is an exact geometric computation (DE-9IM), not a bounding-box approximation. It is planar, on longitude and latitude treated as flat coordinates.

These three are the only GeoSPARQL functions, and only under the geof: IRIs that use a slash (http://www.opengis.net/def/function/geosparql/sfWithin). The hash-form IRIs (geosparql#sfWithin) and every other function — sfTouches, sfDisjoint, sfEquals, sfCrosses, sfOverlaps, distance, buffer, and the rest — are a query error.

Unlike text:query, a spatial comparison has a per-row evaluation, so it works anywhere an expression works: inside ! or ||, in a BIND, or between two variables. Only some of those positions can use the index (How it answers fast).

Asking spatial questions

Which of our places are inside a rectangle over greater Brisbane?

PREFIX ex: <http://ex/>
PREFIX geo: <http://www.opengis.net/ont/geosparql#>
PREFIX geof: <http://www.opengis.net/def/function/geosparql/>

SELECT ?name WHERE {
  ?place ex:name ?name ;
         geo:hasGeometry ?loc .
  FILTER(geof:sfWithin(?loc, "POLYGON((152.8 -27.7, 153.2 -27.7, 153.2 -27.2, 152.8 -27.2, 152.8 -27.7))"^^geo:wktLiteral))
}

Brisbane and Ipswich; Sydney is well outside. The same window as sfContains with the arguments swapped answers equivalently:

FILTER(geof:sfContains("POLYGON((...))"^^geo:wktLiteral, ?loc))

The window does not have to be spelled inline — a VALUES row works the same way:

VALUES ?window { "POLYGON((...))"^^geo:wktLiteral }
FILTER(geof:sfWithin(?loc, ?window))

The constant can just as well be a point. Which places sit at these coordinates?

FILTER(geof:sfContains(?loc, "POINT(153.02 -27.46)"^^geo:wktLiteral))

Answers: Brisbane.

How it answers fast

At load time, every geometry literal is covered by a small set of S2 cells (a hierarchical grid over the sphere) and those cell postings are written to the storage index. When a query compares stored geometries against a constant window, the planner uses the window’s cell covering to read only candidate rows from the index, then runs the exact geometric check on those candidates.

The window has to be a constant the planner can see. These forms all use the index:

  • a literal written in the filter, on either side of the comparison;

  • a variable bound to one geometry by a VALUES row or by BIND of a constant;

  • the filter inside an OPTIONAL body, a UNION arm, an EXISTS body, or a GRAPH block.

These forms cannot use the index. They still answer correctly, by comparing every row’s geometry one at a time:

  • two variables — geof:sfWithin(?a, ?b);

  • the comparison inside another expression: !, ||, or BIND(geof:sfWithin(…) AS ?flag);

  • a window chosen from a multi-row VALUES;

  • the filter inside a sub-SELECT.

The difference in cost is large. On the project’s ten-million-triple benchmark store an indexed sfWithin filter took 0.03 s; the same filter negated took 594 s, because about 789,000 points were each parsed and compared individually.

To see which kind a query is, plan it without a server:

waratah explain -q 'SELECT … WHERE { … }' -f estimate -p

An indexed plan contains a geo_scan operator; the others show the comparison as a plain FILTER residual.

Tuning the covering

Four flags on waratah start and waratah standalone control how the server covers geometry: the window of every spatial query it plans, and every geometry loaded through it.

Flag Default Meaning

--geo-min-level

0

Coarsest S2 cell level in a covering.

--geo-max-level

24

Finest S2 cell level (points always sit at the level-30 leaf).

--geo-max-cells

40

Maximum cells per covering — higher is finer-grained but larger indexes.

--geo-densify-step

0.1

Planar edge densification step in degrees: polygon and line-string edges longer than this are subdivided before the covering so the geodesic candidate index also covers the planar (WKT) region — on continental-scale rings the geodesic and planar readings of the same coordinates differ by up to about 1°, and without densification the index silently misses geometries near such edges. 0 or false disables densification (raw geodesic interpretation only). Values below 0.0001 are rejected: finer than the covering’s own cell resolution buys no accuracy, only covering time.

Keep these at their defaults. waratah import and waratah geo rebuild-index accept none of them: data loaded by waratah import, and every rebuild, uses the default settings, whatever the server runs with. waratah geo rebuild-index prints the settings it used:

waratah geo: rebuilding geometry index for 3 geo term(s) (coverer CovererConfig { min_level: 0, max_level: 24, max_cells: 40, densify_step_deg: 0.1 })

A server started with other settings then disagrees with that index: it covers its query windows differently, and for densification that difference changes answers (see the best-practice page). The flags are also accepted by waratah geo census, so a census can be taken under any settings in use.

Rebuilding wipes and recomputes every spatial posting on a stopped store:

waratah geo rebuild-index --data-dir ./waratah-data

Diagnosing the index

A store loaded by this release is stamped as indexed when the load finishes. At startup, a store without the stamp is rebuilt before queries are served.

waratah geo census is a read-only inspection of the spatial index: posting counts per S2 level, envelope coverage, and the statistics histogram’s incidence mass. For the example data — three points:

waratah geo census --data-dir ./waratah-data
waratah geo: posting census of ./waratah-data/main/o (process coverer config: min_level=0 max_level=24 max_cells=40 densify_step=0.1° (0 = off); the POSTINGS were built by the config live at ingest)
waratah geo: raw rows 3 — distinct (cell,term) postings 3 (puts 3, deletes 0, undecodable cell ids 0)
waratah geo: distinct live terms 3 — 1.00 cells per live term on average (the drain's distinct seen-set collapses these per window)
waratah geo: level |      puts |  share | envelopes | L11-incidences
waratah geo:    30 |         3 | 100.0% |         0 |         3

Each point has one posting, at level 30, the leaf cells. With --window it takes one query window (a WKT literal, like a geof: conjunct would carry) and decomposes the estimate the planner would make against what the index actually returns:

waratah geo census --data-dir ./waratah-data \
  --window 'POLYGON((152.8 -27.7, 153.2 -27.7, 153.2 -27.2, 152.8 -27.2, 152.8 -27.7))'
waratah geo: window: 40 covering cells (levels 8–15), 11 merged L11 ranges, 118 buckets wide
waratah geo:   estimate total: 2 — the number the planner stamps on the geo scan when the profile histogram is exact
waratah geo: drain truth over the same intervals: 2 candidate postings, 2 distinct candidate terms (one geometry = one candidate, the estimate's target unit)

The estimate of 2 matches the two candidates, Ipswich and Brisbane. A window that does not parse, validate, or name a supported CRS fails here with the reason, where the same window in a query would return nothing without an error.

Geometry values other than two-dimensional points are kept in a blob store beside the registry. waratah blob verify --data-dir DIR checks its integrity and reports whether the store is consistent.

Limits of this release

  • The exact computation is planar on longitude and latitude. It is wrong near the antimeridian and the poles, and longitude is not wrapped into the range −180 to 180.

  • A geometry collection whose covering exceeds 1024 cells cannot be stored. A MULTIPOINT above 1024 points is stored, as one covering.

  • There is no distance, buffer, or any other GeoSPARQL function — only the three in the table above.