Geospatial Best Practices

This page is a guide to getting correct, fast answers from Waratah’s spatial index: how to load geometry the index can use, how to write a spatial filter so the index is used, which settings to leave alone, and what to check when a spatial query returns nothing — or takes minutes. Every example runs on the small dataset in [example-setup], and every answer shown is what that dataset returns.

The Geospatial Data page describes the feature itself.

The short version

  • Write coordinates as CRS84, longitude first, or name the CRS and follow its own axis order. A latitude written first without a CRS prefix is stored as given, in the wrong place.

  • Reproject to a supported CRS before loading. Projected CRSs such as Web Mercator are rejected at load.

  • Load valid geometry. Waratah rejects at load what it cannot index; fix the source rather than working around the error.

  • Keep the window a constant on one side of the comparison: a literal, a single VALUES row, or BIND of a constant. A comparison between two variables, inside ! or ||, or inside a sub-SELECT is answered one row at a time.

  • Leave the four covering flags at their defaults. Disabling edge densification makes indexed filters silently drop rows near the edges of large shapes.

  • Check a query with waratah explain before running it on a large store: the plan of an indexed filter contains geo_scan.

  • A geometry in the query that the engine cannot read — an unsupported CRS, an invalid shape, an EMPTY geometry, text that is not WKT — returns no rows and raises no error.

Example setup

The examples use three places (Turtle: save it as places.ttl):

@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 the file and open the store:

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

The examples compare against one window, a rectangle over greater Brisbane, and use this query. It answers Ipswich and Brisbane; Sydney is outside:

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))
}

geof:sfWithin(a, b) is true when a is inside b, and the arguments keep that meaning wherever they are written. Swapping them asks the other question: geof:sfWithin("POLYGON(…)"^^geo:wktLiteral, ?loc) asks which places contain the whole rectangle, and answers nothing.

Write coordinates in the order the CRS says

Bare WKT is CRS84: longitude first, latitude second. Nothing checks that the values are plausible. A place written the other way round is stored exactly as given:

ex:swapped ex:name "Latitude written first" ;
    geo:hasGeometry "POINT(-27.46 153.02)"^^geo:wktLiteral .

The Brisbane window does not find it, and it raises no error. It sits at longitude -27.46 on a "latitude" of 153.02, where only a window over those numbers finds it.

To write latitude first, name EPSG:4326 in the literal:

ex:epsg4326 ex:name "EPSG:4326 (lat lon)" ;
    geo:hasGeometry "<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.46 153.02)"^^geo:wktLiteral .

Waratah transforms it to the same place as the bare Brisbane literal, so the Brisbane window finds both. The rule is by CRS, so the prefix does not excuse a guess: a window with the same EPSG:4326 prefix but written longitude first is the wrong place again, and it returns nothing.

Three consequences for a window written in the query:

  • Write it in the same CRS as the data’s coordinates, or name its CRS. An EPSG:4326 window written latitude first finds the same places as the bare one.

  • A window in a CRS Waratah does not list — Web Mercator, for example — returns no rows and raises no error.

  • Spell it carefully. Text that is not WKT, a self-intersecting polygon, or POINT EMPTY as the window all return no rows, with no error.

Reproject to a supported CRS before loading

Waratah accepts CRS84 and six geographic CRSs: EPSG:4326, 4283, 7844, 9309, 4167, and 4272. Every other CRS is rejected when the data is loaded, with an error that names the CRS:

waratah: invalid RDF literal: geo literal at quad 1 (subject <http://ex/webmercator>, predicate <http://www.opengis.net/ont/geosparql#hasGeometry>): unsupported CRS: http://www.opengis.net/def/crs/EPSG/0/3857

Reproject in the source system first, to CRS84 or EPSG:4326. A projected CRS cannot be loaded and fixed up afterwards.

The CRS a literal was loaded with is kept and written back out. The EPSG:4326 point above is returned as "<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.46 153.02)", and a CRS84 point as bare WKT.

The same place spelled under two CRSs gives two different RDF terms: = and DISTINCT see them as different, while every spatial function sees the same place. With these two literals added to the example data — the Brisbane point again, once with a CRS84 prefix and once with the EPSG:4326 prefix — the Brisbane window answers four rows:

ex:crs84spelled ex:name "CRS84 spelled" ;
    geo:hasGeometry "<http://www.opengis.net/def/crs/OGC/1.3/CRS84> POINT(153.02 -27.46)"^^geo:wktLiteral .

ex:epsg4326 ex:name "EPSG:4326 (lat lon)" ;
    geo:hasGeometry "<http://www.opengis.net/def/crs/EPSG/0/4326> POINT(-27.46 153.02)"^^geo:wktLiteral .
Name Geometry as returned

Brisbane

POINT(153.02 -27.46)

CRS84 spelled

POINT(153.02 -27.46)

EPSG:4326 (lat lon)

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

Ipswich

POINT(152.9 -27.6)

COUNT(?loc) over that window is 4 and COUNT(DISTINCT ?loc) is 3: the first two spellings are one term, the third is another. FILTER(?ga = ?gb) says the same — Brisbane equals "CRS84 spelled", and the EPSG:4326 spelling equals only itself. Load one spelling consistently, so that grouping and de-duplication behave as expected.

Load valid geometry

Waratah refuses to store a geometry it cannot index, because an indexed filter would then silently omit it. The refusal happens at load, names the quad and the problem, and nothing from the batch that contains it is written:

Problem in the source Error

Text that does not parse

unparseable geometry literal

An unsupported CRS

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

A self-intersecting polygon

invalid geometry: geometry validation failed: exterior ring has a self-intersection

MULTIPOLYGON members overlapping 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 covering more than 1024 cells

unsupported geometry shape: geometry collection covering has 1575 distinct cells, above the 1024 cell limit

A load over the console’s Ingest page or the HTTP ingest API answers 400 with the same message. Fix the source and load again; nothing can be skipped at load time.

Two defects are tolerated instead, and load with a warning:

  • An exactly retraced, zero-area spike in a ring, a common clipping artifact. The stored value and STR() keep the original coordinates; the spatial functions use the reduced shape. waratah import prints the number of literals reduced.

  • Contact between the members of one MULTIPOLYGON up to 0.00000001 square degrees of overlap or 0.00000001 degrees of shared, exactly collinear boundary.

Three more things are accepted silently, so check them in the source:

  • Coordinate ranges. A latitude of -100 is stored.

  • A ring that is not closed. It is closed automatically.

  • A MULTIPOINT above 1024 points. It is stored and indexed as one covering rather than point by point.

The index stores one set of postings per distinct geometry value, not per triple. Two features that share one geometry value share its postings, and both are found by a window.

Write the filter so the index is used

The index answers a comparison between stored geometries and a constant. The constant must be visible when the query is planned, and the filter must be a plain FILTER conjunct. These forms use the index:

Form Index

A literal in the filter: FILTER(geof:sfWithin(?loc, "POLYGON(…)"^^geo:wktLiteral))

Yes

The literal first: FILTER(geof:sfContains("POLYGON(…)"^^geo:wktLiteral, ?loc))

Yes

One VALUES row, or BIND of a literal, bound to a variable that the filter uses

Yes

The filter inside an OPTIONAL body, a UNION arm, an EXISTS body, or a GRAPH block

Yes

Two variables: FILTER(geof:sfWithin(?a, ?b))

No

Inside another expression: !, ||, or BIND(geof:sfWithin(…) AS ?flag)

No

A window picked from a VALUES with two or more rows

No

The filter inside a sub-SELECT

No

Every form answers correctly. The "No" rows compare each row’s geometry one at a time, and the cost is not small. 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. A negation, an alternative, or a choice among several windows is better written as several indexed queries, or as NOT EXISTS:

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 .
  FILTER NOT EXISTS {
    ?place 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))
  }
}

Answers: Sydney. The filter inside the NOT EXISTS body uses the index.

To see which kind a query is, plan it without a server and look for geo_scan:

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

The indexed window query from [example-setup] plans as follows (abridged):

(project ~248
  (?name)
  (join ~248
    (broadcast ?place)
    ...
      (custom-op ~248 geosparql geo_scan ?loc cost=drain~248,unit~8)
      (scan ~248
        (triple ?place <#36d211e4> ?loc DEFAULT)
    ...

The same query with the filter negated has no geo_scan; the comparison appears as a residual:

    (filter ~2000000
      (residual
        (!
          (<http://www.opengis.net/def/function/geosparql/sfWithin> ?loc "POLYGON((152.8 -27.7, 153.2 -27.7, 153.2 -27.2, 152.8 -27.2, 152.8 -27.7))"^^<http://www.opengis.net/ont/geosparql#wktLiteral>)))

Keep the covering settings at their defaults

waratah start and waratah standalone take four flags that control how the server covers geometry: --geo-min-level, --geo-max-level, --geo-max-cells, and --geo-densify-step. Keep them at their defaults.

waratah import and waratah geo rebuild-index accept none of the four. Data loaded by waratah import, and every rebuild, uses the defaults, whatever the server runs with. A server started with other settings then disagrees with the index in two ways: it covers its query windows differently, and it covers the geometry loaded through it differently. A 24°-wide polygon loaded by waratah import has 40 postings; the same polygon loaded through a server started with --geo-max-cells 8 has 8.

For densification that difference changes answers. The index models a polygon’s edges as curved lines on the sphere, while WKT means straight lines in longitude and latitude. Densification subdivides long edges so the index covers the straight-line region too. With it disabled, a point well inside a large polygon stops being a candidate. This polygon is about 24° wide:

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

SELECT ?name WHERE {
  ?p ex:name ?name ;
     geo:hasGeometry ?g .
  FILTER(geof:sfWithin(?g, "POLYGON((-120.05194 58.28306, -126.05194 68.67536, -138.05194 68.67536, -144.05194 58.28306, -138.05194 47.89075, -126.05194 47.89075, -120.05194 58.28306))"^^geo:wktLiteral))
}

Against a store holding three points — one in the centre of the polygon, one about 18 km inside its south-east edge, one outside — the answers depend on the server’s setting:

Server setting Points inside, by the filter Same comparison as a BIND expression

Default

Centre, and the point near the edge

Same

--geo-densify-step 0

Centre only

Centre, and the point near the edge

The filter misses the point near the edge, while the same comparison written as an expression still says it is inside. No command in this release builds an index without densification, so there is no setting under which disabling it on the server is consistent with the index.

Mind the graph scope

A spatial filter sees exactly the graphs the rest of the query sees. With Ipswich and Sydney loaded into a named graph ex:g:qld, and Brisbane into the default graph:

  • A bare pattern finds Brisbane only.

  • GRAPH ex:g:qld { … } around the pattern and the filter finds Ipswich.

  • GRAPH ?g { … } answers ex:g:qld with Ipswich.

  • With --default-union on the server, a bare pattern finds Ipswich and Brisbane.

All four use the index.

Test a single value

The comparison also works as an expression, which is the way to test one value or to flag each row:

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

SELECT ?name ?inside WHERE {
  ?place ex:name ?name ;
         geo:hasGeometry ?loc .
  BIND(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) AS ?inside)
}

Answers: Sydney false, Ipswich true, Brisbane true. The value tested can come from the query rather than the store: with VALUES ?p { "POINT(153.02 -27.46)"^^geo:wktLiteral "POINT(1 1)"^^geo:wktLiteral } the expression answers true for the first and false for the second. The expression form is not indexed, so use it to test a value, not to scan a large store.

Combine with other patterns

A spatial filter composes with the rest of the query, and keeps the index in each of the positions below.

Inside an OPTIONAL body, it constrains the optional part only. Sydney is answered with ?inWindow unbound, the other two with yes:

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

SELECT ?name ?inWindow WHERE {
  ?place ex:name ?name .
  OPTIONAL {
    ?place 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))
    BIND("yes" AS ?inWindow)
  }
}

The other positions:

  • In each arm of a UNION, each arm with its own window. One arm with the Brisbane window and one with a window over Sydney answer Brisbane and Ipswich from the first arm and Sydney from the second.

  • Inside FILTER EXISTS and FILTER NOT EXISTS, as above.

  • Alongside other conditions in one FILTER (&&), under DISTINCT, ORDER BY, and LIMIT, and in an aggregate such as COUNT.

Maintain the index

The index follows the data: every load adds its postings, and a store loaded by this release is ready to query when the load finishes. Three commands cover the rest.

waratah geo rebuild-index recomputes every posting on a stopped store, and prints the settings it used:

waratah geo rebuild-index --data-dir ./waratah-data
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 })
waratah geo: geometry index rebuild done: 3 old posting(s) deleted, 3 new posting(s) written, epoch 1795874374039; 3 native term(s) re-covered, 0 orphan(s) upgraded, 0 posting(s) written

Rebuild once after upgrading from a release that indexed differently; the release notes say when that is the case. The rebuild stops, and leaves the index untrusted, if it meets a stored geometry it cannot index.

waratah geo census reports what the index holds. For the example data, three points:

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 blob verify --data-dir ./waratah-data checks the store that holds the value of every geometry other than a two-dimensional point. The example holds only such points, so it has no entries to check. Output without the log timestamps:

index entries: 0 (0 inline, 0 segment); 0 segment byte(s) scanned
orphan segment records: 0
blob store at ./waratah-data/main/blobs is consistent

At startup, a store that has not been stamped as indexed is rebuilt before queries are served; the log says so:

geo index epoch missing; auto-upgrade/rebuild starting (startup blocks until it lands)

When a spatial query returns nothing

A window the engine cannot read is not an error; it is an empty answer. Work down this list, each item a cause this page has shown:

  1. Are the arguments the right way round? sfWithin(a, b) is a inside b.

  2. Is the window written in the order its CRS says? Latitude first without a CRS prefix, or longitude first under an EPSG:4326 prefix, both answer nothing.

  3. Is the window’s CRS one Waratah accepts? A projected CRS answers nothing.

  4. Does the window parse, validate, and use a supported CRS? Pass it to waratah geo census --window. A window the query would silently answer with nothing fails there with the reason: unparseable geometry literal, invalid geometry, unsupported CRS, or unsupported geometry shape.

  5. Is the variable a geometry? A filter on a name or another string answers nothing.

  6. Is the data in a named graph the query does not name?

  7. If rows near the edges of a large shape are missing: is the server running with densification disabled, or was the index built before release 0.5.1, which introduced densification? Restart it with the default, or rebuild.

A PROJ message such as hgridshift: could not find required grid(s) during a load or query means a datum shift ran without its grid file. The load or query still completes, with the position given by the less precise fallback.

When a spatial query is slow

Run waratah explain on the query. If the plan has no geo_scan, the comparison is evaluated row by row; move the window into the filter as a constant, or take the filter out of a sub-SELECT.

Limits of this release

  • The exact computation is planar on longitude and latitude, and is wrong near the antimeridian and the poles. Split rings at the ±180 meridian in the source data.

  • A geometry collection whose covering exceeds 1024 cells cannot be stored.

  • Only sfContains, sfWithin, and sfIntersects exist, under the slash-form geof: IRIs.