Skip to content

S2 spatial queries (idx:spatial) aren't reachable from any query surface #2152

Open

Description

@aaj3f

The geospatial docs described an S2 query for complex geometries (idx:spatial with within / contains / intersects / nearby), and it doesn't work end to end today. A query written exactly as documented returns [], with no error, whether the polygon is in an index or only in novelty, and the polygon itself still reads back as a plain triple. Reproduced at main fdf6ccd01 (the file:line references below are at 4a0d14a1a; the spatial code is the same in both):

{
  "@context": { "ex": "http://example.org/", "idx": "https://ns.flur.ee/index#" },
  "where": [{
    "idx:spatial": "within",
    "idx:property": "ex:boundary",
    "idx:geometry": "POLYGON((1.0 47.0, 4.0 47.0, 4.0 50.0, 1.0 50.0, 1.0 47.0))",
    "idx:result": "?place"
  }],
  "select": ["?place"]
}

over ex:parcel ex:boundary "POLYGON((2.0 48.0, 2.5 48.0, 2.5 48.5, 2.0 48.5, 2.0 48.0))"^^geo:wktLiteral. That's on a file-backed ledger with an explicit incremental build, and again with the polygon in novelty only. intersects answers the same. #2153 marks the S2 section of geospatial.md as not yet available in the meantime.

As far as I can tell there are five separate gaps here, plus a design question. I don't think any one of them alone would make the query work, so I've listed them together:

1. No query surface ever builds an S2 search. S2SearchPattern (fluree-db-query/src/ir/adapters.rs:433) is matched throughout the planner, and where_plan.rs:3280 builds S2SearchOperator from it, but nothing constructs one outside the operator's own unit tests in s2_search.rs. That's true in git log -S too.

  • JSON-LD's node-map parser recognizes BM25 and vector search (fluree-db-query/src/parse/node_map.rs:211, :228, both keyed on f:graphSource). There's no idx: / https://ns.flur.ee/index# vocabulary anywhere in the parser or fluree-vocab, so the documented node-map is read as ordinary triple patterns over a fresh subject and matches nothing.
  • SPARQL implements geof:distance only. geof:sfWithin and friends lower to Function::Custom and are refused as an unknown function (fluree-db-query/src/eval/dispatch.rs:227).
  • Cypher has nothing.

2. The syntax itself needs a decision. The docs used idx:spatial / idx:property / idx:geometry / idx:result in their own namespace. The search patterns we do support (BM25, vector) use the f: vocabulary with f:graphSource (fluree-vocab/src/lib.rs:2109). I wonder if we'd want S2 to follow the f: shape, so the three read alike. Whether SPARQL's geof:sf* functions should lower to the same pattern is part of the same question.

3. The operator and the provider map key providers differently. S2SearchOperator looks a provider up by format!("g{g_id}:{pred_iri}") (fluree-db-query/src/s2_search.rs:295), and with no predicate given, by a "g{g_id}:" prefix scan (:325). BinaryIndexStore::spatial_provider_map inserts them under format!("{g_id}:{p_id}") (fluree-db-binary-index/src/read/binary_index_store.rs:2697). So once 1 is fixed, a query naming its predicate would fail with "no spatial index for key", and one without a predicate would find nothing. Minimally we'd want one key function both sides call, with the operator resolving the predicate IRI to its p_id through the store it already has in context.

4. Novelty never reaches the provider. The provider has a novelty layer (set_novelty, fluree-db-spatial/src/provider.rs:649), but its only callers are the spatial crate's own tests and benches. A geometry written since the last index build isn't findable even with 1 and 3 fixed.

5. A full rebuild drops the spatial index. Only incremental builds write it (fluree-db-indexer/src/build/incremental.rs:1918). build_and_upload_spatial_indexes is #[expect(dead_code)] (fluree-db-indexer/src/build/spatial.rs:30), and the rebuild collects the entries into an unused _spatial_entries (fluree-db-indexer/src/build/rebuild.rs:466). So a reindex, a clone's or restore's first build, or any rebuild fallback publishes a root without spatial indexes, and later incremental builds rebuild them from their own window only, which leaves an incomplete index. Wiring it in changes what a reindex writes and costs (an S2 covering per polygon), so it's worth measuring.

6. The cell index keys a cell by (cell_id, subject_id), with no value. That's CellEntry (fluree-db-spatial/src/cell_index.rs:56), and replay keeps one entry per (cell, subject) (fluree-db-spatial/src/replay.rs:122). So a subject with two geometries that share a cell, where one of them is retracted at t and nothing is asserted, reads as absent in that cell even though the other geometry still covers it. #2153 handles the more common shape, a geometry edited within its own cells, by resolving that cell's same-t retract and assert by the same-t rule. Fixing the general case means a value (or geometry handle) in the cell key, which is an index-format change, so it needs a decision as well.

Some history, fwiw: the operator's key, the provider map's key, spatial_provider_map itself and the documented idx:spatial syntax all first appear in the v4 baseline (5985d0f01), and no test exercises the path end to end. Each layer is tested on its own (fluree-db-spatial drives the provider directly, and s2_search.rs builds the operator by hand), so the seams between them never were. Whoever picks this up, I think an api-level test that runs the documented query over an indexed polygon, a novelty-only one and a reindexed ledger should come first, since that's the test that would have caught all of 1, 3, 4 and 5.

The two calls that need a decision rather than an implementation are the syntax (2) and the cell key (6). Everything else follows from wiring what's there. Happy to talk through any of it.

Activity

  1. aaj3f commented on Oct 26, 2026

    @aaj3f
    ContributorAuthor

    Parking this here from #2153's review, where it sat as an ignored test. It's written against the query shape the geospatial docs describe (idx:spatial with idx:property / idx:geometry / idx:result), for within and intersects over one polygon, both indexed and in novelty only, with a control that reads the polygon back. Today every case comes back [] since nothing parses idx:spatial, so whoever picks up the query surface can drop it into grp_query and un-ignore it as a first acceptance test.

    fluree-db-api/tests/it_spatial_query.rs
    //! The S2 spatial query planned in the geospatial docs (`idx:spatial` with
    //! `idx:property`, `idx:geometry` and `idx:result`), run against a polygon
    //! the ledger holds: indexed, and in novelty only.
    //!
    //! Ignored until the query exists. No query surface parses `idx:spatial`
    //! yet, so today the query reads as ordinary triple patterns and returns
    //! `[]` in every case while the control still reads the polygon back. The
    //! spatial-query issue tracks the work (a parser, provider routing, novelty
    //! geometries and the full rebuild). Un-ignore this when it lands.
    //!
    //! File-backed with `without_indexing()`, so every index build is the one
    //! the test asks for.
    
    use crate::support;
    use fluree_db_api::{Fluree, FlureeBuilder, ReindexOptions};
    use serde_json::{json, Value};
    
    const PFX: &str = "PREFIX ex: <http://example.org/>\n";
    const WKT: &str = "http://www.opengis.net/ont/geosparql#wktLiteral";
    const PARCEL: &str = "POLYGON((2.0 48.0, 2.5 48.0, 2.5 48.5, 2.0 48.5, 2.0 48.0))";
    const REGION: &str = "POLYGON((1.0 47.0, 4.0 47.0, 4.0 50.0, 1.0 50.0, 1.0 47.0))";
    
    fn open(path: &str) -> Fluree {
        FlureeBuilder::file(path.to_string())
            .without_indexing()
            .build()
            .expect("open")
    }
    
    async fn write(fluree: &Fluree, id: &str, body: &str) {
        fluree
            .graph(id)
            .transact()
            .sparql_update(&format!("{PFX}{body}"))
            .commit()
            .await
            .unwrap_or_else(|e| panic!("{body}: {e}"));
    }
    
    /// The docs' query shape for one operation, over `ex:boundary`.
    async fn spatial(fluree: &Fluree, id: &str, op: &str) -> Result<Value, String> {
        let query = json!({
            "@context": {
                "ex": "http://example.org/",
                "idx": "https://ns.flur.ee/index#"
            },
            "where": [{
                "idx:spatial": op,
                "idx:property": "ex:boundary",
                "idx:geometry": REGION,
                "idx:result": "?place"
            }],
            "select": ["?place"]
        });
        fluree
            .graph(id)
            .query()
            .jsonld(&query)
            .execute_formatted()
            .await
            .map_err(|e| e.to_string())
    }
    
    /// The polygon itself, read back as a plain triple: the control.
    async fn boundary(fluree: &Fluree, id: &str) -> Value {
        let query = json!({
            "@context": {"ex": "http://example.org/"},
            "where": [{"@id": "ex:parcel", "ex:boundary": "?g"}],
            "select": ["?g"]
        });
        fluree
            .graph(id)
            .query()
            .jsonld(&query)
            .execute_formatted()
            .await
            .expect("control query")
    }
    
    async fn answers(path: &str, id: &str) -> Vec<String> {
        let fluree = open(path);
        let mut out = vec![format!("control boundary: {}", boundary(&fluree, id).await)];
        for op in ["within", "intersects"] {
            let got = match spatial(&fluree, id, op).await {
                Ok(rows) => rows.to_string(),
                Err(e) => format!("error: {e}"),
            };
            out.push(format!("{op}: {got}"));
        }
        out
    }
    
    /// A polygon inside the query region is found by `within` and
    /// `intersects`, whether the index or novelty holds it.
    #[tokio::test]
    #[ignore = "no query surface parses idx:spatial yet; see the S2 spatial-query issue"]
    async fn a_spatial_query_finds_a_polygon_in_its_region() {
        let mut failures = Vec::new();
        for indexed in [true, false] {
            let dir = tempfile::tempdir().expect("tempdir");
            let path = dir.path().to_string_lossy().to_string();
            let id = "it/spatial-query:main";
            {
                let fluree = open(&path);
                fluree.create_ledger(id).await.expect("create");
                write(&fluree, id, "INSERT DATA { ex:filler ex:k \"keep\" }").await;
                fluree
                    .reindex(id, ReindexOptions::default())
                    .await
                    .expect("base index");
                write(
                    &fluree,
                    id,
                    &format!("INSERT DATA {{ ex:parcel ex:boundary \"{PARCEL}\"^^<{WKT}> }}"),
                )
                .await;
                if indexed {
                    support::build_incrementally_and_publish_index(&fluree, id).await;
                }
                fluree.disconnect_ledger(id).await;
            }
            let got = answers(&path, id).await;
            let label = if indexed { "indexed" } else { "novelty" };
            if !got[0].contains("POLYGON") {
                failures.push(format!("{label}: the control lost the polygon: {got:?}"));
                continue;
            }
            for line in &got[1..] {
                if !line.contains("ex:parcel") {
                    failures.push(format!("{label}: {line}"));
                }
            }
        }
        assert!(failures.is_empty(), "{failures:#?}");
    }
  2. bplatz commented on Nov 11, 2026

    @bplatz
    Contributor

    Two notes from #2274, which fixes item 5:

    • fix(indexer): a reindex keeps the ledger's spatial index #2274 also fixes two incremental-build bugs in the spatial index. Each incremental build multiplied the prior cell entries by up to the covering size (8), and geometries written since the base index were indexed under chunk-local subject ids. A ledger indexed before fix(indexer): a reindex keeps the ledger's spatial index #2274 should be reindexed once it lands; the wrong-subject entries don't correct themselves.
    • A cost for whoever picks up the query side: every index load from a v6 root fetches every spatial blob into memory and builds each snapshot (fluree-db-binary-index/src/read/binary_index_store.rs:4028-4065), for a provider nothing queries yet. Now that a reindex writes the spatial index too, reindexed ledgers pay that as well. Loading a predicate's spatial snapshot on first use seems worth doing alongside 1 and 3.
  3. added
    P2
    area:query
    on Nov 11, 2026
  4. added this to the 5.0.0 milestone on Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2area:query

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions