Skip to content

Spatial Relations ​

etter supports 21 built-in spatial relations across four categories.

Containment ​

RelationBehaviorDefault distance
inExact geometry match — passthrough for polygons—

Example: "restaurants in Geneva" → returns Geneva's boundary polygon as-is.

Point and line references: a point or line cannot meaningfully contain anything, so apply_spatial_relation() falls back to a boundary buffer sized from the smallest area bracket (500 m, see Area-Based Distance Inference).

Buffer / Proximity ​

RelationBehaviorDefault distance
aroundCircular buffer from centroid1 km
nearCircular buffer from centroid5 km
alongLinear buffer along a feature500 m
left_bankLeft bank of a linear feature (relative to flow direction)500 m
right_bankRight bank of a linear feature (relative to flow direction)500 m
on_shores_ofRing buffer around a water boundary, excluding the water body1 km ring
in_the_heart_ofNegative buffer (erosion) toward center−500 m
borderingThin ring just outside the reference boundary, for land-border adjacency2 km ring

One-sided buffers: left_bank and right_bank produce a buffer on a single side of a linear feature (river, road) relative to its direction of flow.

Ring buffer: on_shores_of and bordering use ring_only=True — the reference geometry itself is subtracted, leaving only the surrounding ring.

Example: "cities bordering Germany" → 2 km ring just outside Germany's boundary, excluding Germany itself.

Clipping ​

Clipping relations clip the reference geometry to a directional half-plane. They answer "what is in the northern/southern/eastern/western portion of X?" — as opposed to directional relations, which answer "what is north/south/east/west of X?".

RelationBehavior
northern_part_ofClip reference geometry to its northern bbox half (above midpoint latitude)
southern_part_ofClip reference geometry to its southern bbox half (below midpoint latitude)
eastern_part_ofClip reference geometry to its eastern bbox half (right of midpoint longitude)
western_part_ofClip reference geometry to its western bbox half (left of midpoint longitude)

Example: "ski resorts in the northern part of Switzerland" → Switzerland's polygon clipped to the area north of its bbox midpoint.

Directional ​

All directional relations produce a 90° sector wedge extending outward from the reference geometry centroid.

RelationDirectionDefault distance
north_of0°10 km
northeast_of45°10 km
east_of90°10 km
southeast_of135°10 km
south_of180°10 km
southwest_of225°10 km
west_of270°10 km
northwest_of315°10 km

Example: "5km north of Lausanne" → 90° sector polygon extending 5km north from Lausanne's centroid.

The 10 km default only applies until the geometry is known: when the query states no distance, apply_spatial_relation() replaces it with a value sized to the reference geometry (see Area-Based Distance Inference).

Area-Based Distance Inference ​

The "Default distance" values above are what the parser writes into buffer_config.distance_m when the query states no distance; the config is then flagged inferred=True. When the query does state a distance ("within 5km", "30 min walk"), SpatialRelation.explicit_distance overrides the default and the config is flagged inferred=False.

At geometry time, apply_spatial_relation() replaces an inferred default for near, in_the_heart_of and the directional relations: it estimates the area of the reference geometry (its area in square degrees scaled to metres at its latitude, within 0.2% of the geodesic area for Swiss cantons) and picks a distance from area-based brackets instead. An explicit distance is never changed:

Geometry areaProximity defaultErosion default
< 1 km² (station, pond)500 m−200 m
1–50 km² (town, small lake)1 500 m−500 m
50–500 km² (city, medium region)5 000 m−1 000 m
≥ 500 km² (canton, country)15 000 m−2 000 m

This means the same relation (e.g. near) produces a smaller buffer around a village than around a canton, when the query doesn't state a distance explicitly.

The other buffer relations (around, along, left_bank, right_bank, on_shores_of, bordering) describe a fixed width, so they keep their default: the shore of a large lake is still a 1 km ring. A point or line reference (a peak, a river) has no area to size from, so it keeps the relation's default too: near a peak stays 5 km.

Registering Custom Relations ​

Register additional relations on a SpatialRelationConfig and pass it to the parser:

python
from etter import GeoFilterParser, RelationConfig, SpatialRelationConfig

config = SpatialRelationConfig()
config.register_relation(RelationConfig(
    name="close_to",
    category="buffer",
    description="Very close proximity, under 1km",
    default_distance_m=1000,
    buffer_from="center",
))

parser = GeoFilterParser(llm=llm, spatial_config=config)

The description is shown to the LLM, so write it as guidance for when to pick the relation. Other options depend on the category:

  • Buffer: ring_only=True subtracts the reference geometry to leave only the surrounding ring (requires buffer_from="boundary"); side="left" or "right" buffers one side of a linear feature only.
  • Directional: direction_angle_degrees sets the sector's direction (0 = N, 90 = E, 180 = S, 270 = W) and sector_angle_degrees its width.
  • Buffer and directional: scale_with_area=True sizes the distance to the reference polygon when the query states none (see Area-Based Distance Inference); by default the relation keeps default_distance_m.

For directional and clipping relations, and for scale_with_area, apply_spatial_relation() reads these options from the config, so pass the same one to it — otherwise it only knows the built-ins, and raises UnknownRelationError for a custom directional or clipping relation:

python
area = apply_spatial_relation(
    geometry, relation, buffer_config, spatial_config=config
)

See SpatialRelationConfig and RelationConfig for all available options.

Geometry Formats ​

apply_spatial_relation() takes the reference geometry, in WGS84, as a GeoJSON dict, a WKT or hex-encoded WKB string, WKB as bytes, bytearray or memoryview (what database drivers return for a binary column) or a shapely geometry, alone or in a list. By default it returns a GeoJSON geometry dict. Use the geometry_format parameter to request WKT, WKB or a shapely geometry instead:

python
from etter import apply_spatial_relation

geo_query = parser.parse("near Lausanne")
ref = geo_query.reference_location
geometry = datasource.search(ref.name)[0]["geometry"]
relation = geo_query.spatial_relation
buffer_config = geo_query.buffer_config

# GeoJSON dict (default)
result = apply_spatial_relation(geometry, relation, buffer_config)

# WKT string
result_wkt = apply_spatial_relation(
    geometry, relation, buffer_config, geometry_format="wkt"
)

# WKB hex string
result_wkb = apply_spatial_relation(
    geometry, relation, buffer_config, geometry_format="wkb"
)

# shapely geometry
result_shape = apply_spatial_relation(
    geometry, relation, buffer_config, geometry_format="shapely"
)

To convert raw datasource feature dicts, use convert_feature_geometry():

python
from etter import convert_feature_geometry

feature = datasource.search("Lausanne")[0]
feature_wkt = convert_feature_geometry(feature, "wkt")
# feature_wkt["geometry"] is now a WKT string

Using the area in SQL ​

If the reference geometry comes from your database, fetch it as WKB (ST_AsBinary(geometry)) and ask for WKB back: on a large outline (a canton, 24,000 vertices), GeoJSON parsing and serialisation take most of the time, about 30 ms against 2 ms in WKB for in.

python
row = conn.execute(text("SELECT ST_AsBinary(geometry) FROM canton WHERE name = :name"), {"name": ref.name}).one()
area = apply_spatial_relation(row[0], geo_query.spatial_relation, geo_query.buffer_config, geometry_format="wkb")

Pass the area as a bound parameter and parse it in a scalar subquery, so the database parses it once per query:

sql
SELECT id FROM hike
WHERE ST_Intersects(geometry, (SELECT ST_GeomFromWKB(decode(:area, 'hex'), 4326)))

:area is the hex string from geometry_format="wkb"; with "wkt", use ST_GeomFromText(:area, 4326). Written without the subquery, ST_Intersects(geometry, ST_GeomFromWKB(...)) can be evaluated again for every candidate row: once a driver such as asyncpg reuses a prepared statement with a generic plan, the parse is not folded into a constant, and a large area (a canton, a merged river) makes each query take seconds.

If you also need the area as GeoJSON (to return it, or to log it), ask for geometry_format="shapely" and write each format once from the result, instead of parsing one back to get the other: shapely.to_wkb(area, hex=True) for :area in the query above, and shapely.geometry.mapping(area) for GeoJSON.

Querying Available Relations ​

python
# All relations
parser.get_available_relations()

# By category
parser.get_available_relations(category="directional")

# Description of a specific relation
parser.describe_relation("on_shores_of")

If your own code handles relations itself, branch on geo_query.spatial_relation.category (containment, buffer, directional or clipping) rather than on a list of relation names: a name list falls behind as relations are added or registered, while every relation has one of these four categories.

Released under the BSD-3-Clause License.