# fao-ferspas

A queryable index of the FAO Essential Remote Sensing Data Product Portal for
Agrifood Systems (FERSPAS) STAC API, as two GeoParquet files.

Upstream API: <https://data.apps.fao.org/geospatial/search/stac>
Portal: <https://data.apps.fao.org/remote-sensing-portal/>

This holds metadata only. Every raster stays on FAO's servers; the tables carry
the URL and the declared size so you can decide what to fetch before fetching
it. Declared size of everything referenced here is about 21 TB.

Snapshot: collections 2026-09-18, items 2026-09-18.

## Files

| File | Rows | What one row is |
| --- | ---: | --- |
| `collections.parquet` | 1921 | one FERSPAS collection |
| `items.parquet` | 639947 | one downloadable file |
| `search.parquet` | 115070 | one term in one field of one collection |

Both are GeoParquet. `geometry` is the footprint, `bbox` is the same extent as a
struct. Footprints in this catalogue are rectangles, so the geometry is built
from the bbox rather than copied from the API.

## Query it without downloading it

```sql
INSTALL spatial; LOAD spatial;

-- collections covering Rome that are split by growing season
SELECT short_id, catalog, item_count, dimensions
FROM read_parquet('https://stac.yuiseki.net/fao-ferspas/collections.parquet')
WHERE ST_Intersects(geometry, ST_Point(12.5, 41.9))
  AND list_contains(dimensions, 'SEASON')
ORDER BY item_count DESC;

-- the 2026 Agricultural Stress Index files for season 1 over cropland
SELECT start_datetime, data_gs_href, file_size
FROM read_parquet('https://stac.yuiseki.net/fao-ferspas/items.parquet')
WHERE short_id = 'ASI-D' AND year = 2026 AND season = 'GS1' AND lct = 'LC-C'
ORDER BY start_datetime;
```

## Everything here is a Cloud Optimized GeoTIFF

Every `data` asset in this catalogue is a COG. All 639947 asset URLs end in
`.tif`:

| extension | files | share |
| --- | ---: | ---: |
| `.tif` | 639947 | 100.0% |

and one item read from each of the 1920 collections that have
items declares the same media type:

| media type | collections |
| --- | ---: |
| `image/tiff; application=geotiff; profile=cloud-optimized` | 1920 |

So a reader does not have to download a whole file to use part of it. Both
GDAL and rasterio can read a window over HTTP:

```python
import rasterio
from rasterio.windows import from_bounds

url = "/vsicurl/https://storage.googleapis.com/..."   # data_href from the table
with rasterio.open(url) as src:
    window = from_bounds(6, 36, 20, 48, src.transform)   # Italy
    data = src.read(1, window=window)
```

Every item also carries `preview` and `thumbnail`, PNGs rendered by FAO's WMTS.
To put a layer on a map, those are enough; the COG is for reading values.

The media type is not in `items.parquet`, because it is identical everywhere
and the column would be 639947 copies of one string. It is not in the
collection records either: `item_assets.data` carries no `type`, so the format
can only be read off an item.

## Searching the catalogue

`search.parquet` is a full-text index over every collection's title,
description and keywords: 115070 rows covering 3595 distinct
stemmed terms, in one file. It scores with BM25, and the scores are the same
ones DuckDB's own `fts` extension produces, which is checked by a test rather
than assumed.

The extension is needed only for its tokenizer and stemmer, so a query is split
and stemmed the way the index was built. There is no index to attach and no
schema to recreate.

There is a search page at <https://stac.yuiseki.net/fao-ferspas/search/>, which runs exactly this against
these files with DuckDB compiled to WebAssembly. Nothing is sent to a server.
It also offers a second mode that matches meaning rather than words; see
below.

```sql
INSTALL fts; LOAD fts;

SELECT c.short_id, c.title, c.item_count, round(s.score, 2) AS score
FROM (
WITH idx AS (SELECT * FROM read_parquet('https://stac.yuiseki.net/fao-ferspas/search.parquet')),
-- num_docs and avgdl come from the index, so a filtered index stays correct.
stats AS (
  SELECT count(*) AS num_docs, avg(len) AS avgdl
  FROM (SELECT DISTINCT doc, len FROM idx)
),
-- The same tokenizer and stemmer the index was built with.
tokens AS (
  SELECT DISTINCT stem(unnest(string_split_regex(
    regexp_replace(lower(strip_accents('soil organic carbon')),
                   '[0-9!@#$%^&*()_+={}\[\]:;<>,.?~\\/\|''"`-]+', ' ', 'g'),
    '\s+')), 'porter') AS t
),
-- tf is summed across fields before scoring. Scoring each field and adding
-- the results double-counts BM25's saturation and inflates every hit that
-- appears in more than one field.
hits AS (
  SELECT i.doc, i.term, sum(i.tf) AS tf,
         any_value(i.df) AS df, any_value(i.len) AS len
  FROM idx i JOIN tokens ON i.term = tokens.t
  GROUP BY i.doc, i.term
)
SELECT doc,
       sum(log(((num_docs - df + 0.5) / (df + 0.5)) + 1)
           * ((tf * (1.2 + 1))
              / (tf + 1.2 * ((1 - 0.75) + 0.75 * (len / avgdl))))) AS score
FROM hits, stats
GROUP BY doc
ORDER BY score DESC
) s
JOIN read_parquet('https://stac.yuiseki.net/fao-ferspas/collections.parquet') c ON c.id = s.doc
LIMIT 10;
```

Add `AND i.field = 'title'` inside `hits` to search titles only; the fields are
`title`, `description` and `keywords`.

Two things to keep if the query is adapted. Sum `tf` across fields before
scoring: scoring each field separately and adding the results double-counts
BM25's saturation, and anything matching in more than one field comes out too
high. And do not split this statement on semicolons, because the tokenizer's
character class contains one inside a quoted string.

`num_docs` and `avgdl` are computed from the index rather than stored, so a
filtered subset of it still scores correctly.

## Searching by meaning

`embeddings.parquet` and `embeddings-title.parquet` hold a 768-dimension
vector per collection, from IBM's granite-embedding-311m-multilingual-r2.
One is built from the titles, the other from the titles plus the
descriptions, and each collection keeps whichever scores better, because
neither wins outright: the title index finds the drought-probability and
greenhouse-gas collections that long boilerplate descriptions bury, and the
full-text one finds soil organic carbon and crop area, where the description
carries what the title leaves out.

This is what BM25 cannot do. A query of "risk of famine" reaches collections
about food insecurity and undernourishment, "how many cattle are there"
reaches gridded livestock density, and a query in Japanese reaches the English
descriptions. It is weaker than BM25 when you already know the term, so the
page offers both rather than replacing one with the other.

```sql
WITH q AS (SELECT [/* 768 floats */]::FLOAT[768] AS v),
scored AS (
  SELECT id, array_cosine_similarity(vec::FLOAT[768], q.v) AS s
  FROM read_parquet('https://stac.yuiseki.net/fao-ferspas/embeddings-title.parquet'), q
  UNION ALL
  SELECT id, array_cosine_similarity(vec::FLOAT[768], q.v)
  FROM read_parquet('https://stac.yuiseki.net/fao-ferspas/embeddings.parquet'), q
)
SELECT c.short_id, c.title, max(s) AS score
FROM scored JOIN read_parquet('https://stac.yuiseki.net/fao-ferspas/collections.parquet') c ON c.id = scored.id
GROUP BY c.short_id, c.title
ORDER BY score DESC LIMIT 10;
```

Use `array_cosine_similarity`, not `array_distance`: the latter is Euclidean.
It ranks the same way for normalised vectors but is not a similarity, so
reporting `1 - array_distance` as a score would be wrong.

The query vector has to come from the same model. The search page loads it
with Transformers.js; offline, `scripts/embed-query.mjs` in the repository
does the same thing.

## Columns worth knowing

`collections.parquet`

- `id` is the full API id, `fao-gismgr:<CATALOG>:raster:<KIND>:<SHORT_ID>`.
  `catalog`, `kind` and `short_id` are that id split up.
- `dimensions` lists the categorical datacube dimensions a collection is split
  by; `dimension_values` maps each one to its full vocabulary. These are the
  axes the upstream API can actually filter on.
- `item_count` comes from the API's aggregation endpoint.

`items.parquet`

- `dims` maps every categorical dimension to the single value this file is
  pinned to. The nine most common ones also have their own column: `season`,
  `lct`, `crop`, `depth`, `stats`, `clim`, `period`, `ssp`, `tech`.
- `data_href` is the HTTPS URL of the COG, `data_gs_href` the same object on
  Google Cloud Storage, `file_size` its declared size in bytes.
- `gismgr_item_id` is FAO's older dotted identifier. Notebooks written against
  the previous naming scheme match on this, not on `id`.

## Counts were checked, not assumed

The number of rows harvested per collection equals the count the API's
aggregation endpoint reports, for all 1921 collections.
`fao-gismgr:GAEZ-V5:raster:mapsets:RES01-RFM-TS` reports zero items upstream and so contributes no rows.

## Licence

These tables are derived metadata. Each collection carries its own upstream
licence in the `license` column:

| licence | collections |
| --- | ---: |
| CC-BY-4.0 | 1074 |
| CC-BY-SA-4.0 | 548 |
| CC-BY-NC-SA-4.0 | 291 |
| notspecified | 3 |
| other-at | 3 |
| other-open | 2 |

Attribution goes to FAO and to the providers named on each collection upstream.
Check the `license` column before redistributing anything derived from a
particular collection; some are non-commercial.

Built by <https://github.com/yuiseki/study-un-fao-ferspas> (metadata only, no
bulk download).
