Skip to main content

Search

The Search API gives a table or view a full-text search index. The index is built from the rows of the relation on request and is queried with the OpenSearch _search syntax, either as a query string or as a query DSL body. Queries and responses are passed to and from OpenSearch unaltered.

The index is a copy, not a live view: it holds the rows as they were when it was last built. Rebuild it after the data changes.

The API has four resources:

ResourceWhat it is
/api/v4/schemas/{schema}/tables/{table}/searchThe index of one relation: PUT builds it, DELETE drops it, GET and POST search it. Requires a Bearer token.
/api/v4/search/database/{database}/schemas/{schema}/tables/{table}Search without a token, for relations anyone may read.
/api/v4/search/jobsSearch index jobs: queued index builds for large relations.
/api/v4/search/settingsThe analysis settings of the database: analyzers, tokenizers and filters.

{table} takes a table or a view. The index is named <database>_<schema>_<table>.

Access model:

  • The super user (the database owner) builds and drops indexes, queues jobs and manages the mapping and the analysis settings.
  • A sub-user can search a relation they have read privilege on. Building and dropping are refused with 403 (NOT_OWNER).
  • Anyone can search a relation on the token-less route when its authentication level lets anyone read it.

Build the index​

PUT drops any existing index, creates a new one with the database's analysis settings and a mapping derived from the columns, indexes every row and refreshes the index. The request has no body. The build happens inside the request, so the index is searchable as soon as the call returns:

Request
PUT https://api.gc2.io/api/v4/schemas/music/tables/bands/search HTTP/1.1
Accept: application/json; charset=utf-8
Authorization: Bearer abc123
Response
{
"index": "mydb_music_bands",
"message": "Indexed 42 documents",
"errors": false,
"errors_in": []
}

Things to know:

  • The relation must have a primary key (a view: a gid column). It becomes the document _id. Without one the build is refused with 400 (INDEX_BUILD_ERROR).
  • Check errors in the response. true means the index exists but OpenSearch rejected some documents; they are listed in errors_in.
  • A relation without rows gives an empty index.
  • A build that fails leaves no index. Searches then answer 404 (INDEX_NOT_FOUND) rather than partial results.
  • A large relation takes minutes. The build runs to the end even if the client stops waiting, and the existing index is dropped first, so search is unavailable meanwhile. For a large relation, queue a search index job instead.
  • While a search index job for the relation is queued or running, PUT answers 409 (JOB_ACTIVE).
  • Rebuild after the data changes, after a mapping change and after an analysis settings change. None of them reach an existing index on their own.

Search​

Rows are indexed as GeoJSON-like documents: _source is an object with properties (the columns) and geometry. Every column is addressed as properties.<column> — in q, in the query DSL, in sort and in _source filters. A bare column name matches nothing.

Search by query string​

GET passes the query string to OpenSearch URI search unaltered, so any _search URI parameter works. With no parameters every document matches:

Request
GET https://api.gc2.io/api/v4/schemas/music/tables/bands/search?q=properties.name:Guns&size=20&sort=properties.name.keyword:asc HTTP/1.1
Accept: application/json; charset=utf-8
Authorization: Bearer abc123
Response
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": null,
"hits": [
{
"_index": "mydb_music_bands",
"_id": "1",
"_score": null,
"_source": {
"properties": {
"id": 1,
"name": "Guns N' Roses",
"genre": "Hard rock"
},
"geometry": null
},
"sort": [
"Guns N' Roses"
]
}
]
}
}

The response is the raw OpenSearch one: hits.total.value is the number of matches and hits.hits holds the documents with _id (the primary key value), _score and _source. _score is null when the query sorts on something other than the score.

ParameterDescription
qLucene query string, e.g. properties.name:Guns.
sizeMaximum number of hits to return. Default 10.
fromOffset of the first hit, for paging. Default 0.
sortComma-separated <field>:<asc|desc> pairs, e.g. properties.name.keyword:asc.
_sourceComma-separated list of _source fields to return, or false to leave _source out.
default_operatorDefault operator for q: AND or OR. Default OR.
dfDefault field for q when a term has no field prefix.
  • default_operator and df are only valid together with q. Sent alone, OpenSearch rejects the request with 400.
  • Sort and aggregate text on the .keyword sub-field (properties.name.keyword), not on the text field itself.

Search by query DSL​

POST passes the JSON body to OpenSearch _search unaltered: query, size, from, sort, _source, aggs, highlight and anything else OpenSearch accepts:

Request
POST https://api.gc2.io/api/v4/schemas/music/tables/bands/search HTTP/1.1
Content-Type: application/json
Accept: application/json; charset=utf-8
Authorization: Bearer abc123

{
"query": {
"match": {
"properties.name": "Roses"
}
},
"sort": [
{ "properties.name.keyword": "asc" }
],
"_source": ["properties.name"],
"size": 20
}

The response has the same shape as for GET, plus aggregations when the query has aggs.

Access for sub-users​

A sub-user can search a relation they have read privilege on. Two cases are refused with 403:

CodeMeaning
INSUFFICIENT_PRIVILEGESThe sub-user has no read privilege on the relation.
GEOFENCE_RULES_APPLYA deny or limit rule matches the sub-user. The index holds every row and cannot apply the rule's row filter, so the search is refused outright rather than filtered. Retrying gives the same answer.

404 (INDEX_NOT_FOUND) means the relation exists but no index has been built for it. Only the database owner can build it.

Drop the index​

DELETE drops the index. The table itself is not touched:

Request
DELETE https://api.gc2.io/api/v4/schemas/music/tables/bands/search HTTP/1.1
Accept: application/json; charset=utf-8
Authorization: Bearer abc123
Response
{
"index": "mydb_music_bands",
"dropped": true
}

Search without a token​

A relation that anyone may read can be searched without a token. The route has the database in the path and takes the same query string (GET), the same body (POST) and gives the same answer as the token route:

Request
GET https://api.gc2.io/api/v4/search/database/mydb/schemas/music/tables/bands?q=properties.name:Guns HTTP/1.1
Accept: application/json; charset=utf-8
Request — query DSL
POST https://api.gc2.io/api/v4/search/database/mydb/schemas/music/tables/bands HTTP/1.1
Content-Type: application/json
Accept: application/json; charset=utf-8

{
"query": {
"match": {
"properties.name": "Roses"
}
}
}

When the route answers:

  • The relation's authentication level must be Write or None, which both let anyone read. A relation on Read/write answers 403 (AUTHENTICATION_REQUIRED); search it on the token route instead.
  • A geofence deny or limit rule for everyone (*) refuses the search with 403 (GEOFENCE_RULES_APPLY), as the index cannot apply a row filter.
  • 404 is DATABASE_NOT_FOUND, TABLE_NOT_FOUND or INDEX_NOT_FOUND.

A token sent to this route is not looked at. The caller is treated as anonymous even when the request carries an Authorization header, so a signed-in user gets no more access here than anyone else. Building and dropping an index stay on the token route.

Use it for a typeahead in a public map or app, where there is no signed-in user.

Per-column mapping​

The build derives the mapping of each column from its PostgreSQL type:

Column typeOpenSearch type
Texttext with a keyword sub-field
Integersinteger / long
Decimalsfloat / double
Datesdate
Point geometrygeo_point
Other geometrygeo_shape

Overrides are laid on top of the derived mapping. They live in the relation's Meta, in the elasticsearch block, keyed by column name. Columns that are not listed keep the derived mapping. Write the block with PATCH /api/v4/meta, which answers 303 with a Location header:

Request
PATCH https://api.gc2.io/api/v4/meta HTTP/1.1
Content-Type: application/json
Authorization: Bearer abc123

{
"relations": {
"music.bands": {
"elasticsearch": {
"name": {
"elasticsearchtype": "text",
"analyzer": "auto_complete_analyzer",
"search_analyzer": "auto_complete_search_analyzer"
},
"genre": {
"elasticsearchtype": "keyword"
}
}
}
}
}

All keys of a column are optional:

KeyDescription
elasticsearchtypeOpenSearch field type, e.g. text, keyword, integer, long, float, double, boolean, date, geo_point, geo_shape or ip. Defaults to the type derived from the column.
analyzerIndex-time analyzer, also used at search time unless search_analyzer is set. Text fields only.
search_analyzerSearch-time analyzer. Text fields only.
indexBoolean. false makes the field not searchable.
formatDate format for date fields, e.g. yyyy-MM-dd.
null_valueValue indexed in place of null.
fielddataBoolean. Enables fielddata on a text field, for sorting and aggregation.
fieldsMulti-fields. Text fields get {"keyword": {"type": "keyword", "ignore_above": 256}} unless this is set.

Any other OpenSearch field-mapping parameter (normalizer, doc_values, copy_to, ...) is passed through as well.

  • PATCH replaces the whole elasticsearch block of the relation. Send every column that has overrides, not only the one you change. Read the block with GET /api/v4/meta, modify it and write it back.
  • Reset one column by sending the block without it. Clear all overrides with "elasticsearch": {}.
  • Setting fields replaces the automatic keyword sub-field, so properties.<column>.keyword disappears unless you include it yourself.
  • An analyzer named in the mapping must exist, either in the database's analysis settings or as an OpenSearch built-in (standard, simple, whitespace, keyword, stop, or a language analyzer such as danish or english). An unknown analyzer fails the build with 400 (INDEX_BUILD_ERROR).
  • A mapping change takes effect on the next build.
  • The elasticsearch block is returned on the token route only; the token-less Meta route leaves it out.

Analysis settings​

Every database has one OpenSearch analysis block (analyzer, tokenizer, filter, char_filter, normalizer), which is used as settings.analysis when an index is built. Both methods are for the database owner only (403 NOT_OWNER).

GET returns the stored block, or the default when none is set:

Request
GET https://api.gc2.io/api/v4/search/settings HTTP/1.1
Accept: application/json; charset=utf-8
Authorization: Bearer abc123
Response
{
"analysis": {
"analyzer": {
"auto_complete_search_analyzer": {
"type": "custom",
"tokenizer": "whitespace",
"filter": ["lowercase", "asciifolding"]
},
"auto_complete_analyzer": {
"type": "custom",
"tokenizer": "whitespace",
"filter": ["lowercase", "asciifolding", "substring"]
}
},
"filter": {
"substring": {
"type": "edge_ngram",
"min_gram": 1,
"max_gram": 20
}
}
}
}

PUT stores a new block and echoes it. It replaces the block wholesale: read it, add to it and write all of it back. A body without an analysis object is rejected with 400 (INVALID_DATA). The new settings apply to indexes built afterwards — rebuild an existing index to pick them up:

Request
PUT https://api.gc2.io/api/v4/search/settings HTTP/1.1
Content-Type: application/json
Authorization: Bearer abc123

{
"analysis": {
"analyzer": {
"auto_complete_search_analyzer": {
"type": "custom",
"tokenizer": "whitespace",
"filter": ["lowercase", "asciifolding"]
},
"auto_complete_analyzer": {
"type": "custom",
"tokenizer": "whitespace",
"filter": ["lowercase", "asciifolding", "substring"]
},
"band_analyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": ["lowercase", "band_synonyms"]
}
},
"filter": {
"substring": {
"type": "edge_ngram",
"min_gram": 1,
"max_gram": 20
},
"band_synonyms": {
"type": "synonym",
"synonyms": ["gnr, guns n roses"]
}
}
}
}

Search as you type​

The default block has two analyzers for prefix search: auto_complete_analyzer splits the text into edge n-grams at index time, and auto_complete_search_analyzer is its search-time counterpart. To make "Gun" find "Guns N' Roses":

  1. Set analyzer to auto_complete_analyzer and search_analyzer to auto_complete_search_analyzer on the column, as in the mapping example above.
  2. Rebuild the index.
  3. Search with q=properties.name:Gun.

Search index jobs​

PUT …/search builds inside the request and drops the live index first. For a large relation, queue the build as a job instead: the request answers 202 at once, and a worker builds the new index beside the live one and switches over when every row is in. Searches are answered by the old index until then, and a job that fails or is cancelled leaves search as it was.

Jobs are for the database owner only (403 SUPER_USER_ONLY) and require a Bearer token.

Queue a job​

POST takes one object with schema and table, or an array of them. Every relation in an array is checked before any job is queued, so one bad element queues nothing. There can be one queued or running job per relation: a second one is refused with 409 (JOB_ACTIVE).

Request
POST https://api.gc2.io/api/v4/search/jobs HTTP/1.1
Content-Type: application/json
Authorization: Bearer abc123

{
"schema": "music",
"table": "bands"
}
Response 202
{
"uuid": "c4a3797e-ec6b-4dac-9474-ada9083620f3",
"schema": "music",
"table": "bands",
"index": "mydb_music_bands",
"status": "pending",
"stale": false,
"indexed": 0,
"errors": false,
"errors_in": [],
"error": null,
"username": "axl",
"host": null,
"created": "2026-12-03T10:15:00+00:00",
"started": null,
"finished": null,
"heartbeat": null,
"cancel_requested": null,
"_links": {
"self": "/api/v4/search/jobs/c4a3797e-ec6b-4dac-9474-ada9083620f3"
}
}

202 means queued, not indexed. Poll _links.self until status is succeeded or failed.

Get jobs​

GET /api/v4/search/jobs lists the jobs of the database, newest first. Filter with ?status=, ?schema= and ?table=. GET /api/v4/search/jobs/{uuid} returns one job as an object; a comma-separated list of uuids returns an array. An unknown uuid is 404 (JOB_NOT_FOUND).

Request
GET https://api.gc2.io/api/v4/search/jobs/c4a3797e-ec6b-4dac-9474-ada9083620f3 HTTP/1.1
Authorization: Bearer abc123
Response
{
"uuid": "c4a3797e-ec6b-4dac-9474-ada9083620f3",
"schema": "music",
"table": "bands",
"index": "mydb_music_bands",
"status": "running",
"stale": false,
"indexed": 1250000,
"errors": false,
"errors_in": [],
"error": null,
"username": "axl",
"host": "gc2-1",
"created": "2026-12-03T10:15:00+00:00",
"started": "2026-12-03T10:15:20+00:00",
"finished": null,
"heartbeat": "2026-12-03T10:19:40+00:00",
"cancel_requested": null,
"_links": {
"self": "/api/v4/search/jobs/c4a3797e-ec6b-4dac-9474-ada9083620f3"
}
}
FieldDescription
uuidThe job id.
schema, tableThe relation whose index is built.
indexThe index name clients search: <database>_<schema>_<table>.
statuspending, running, succeeded, failed or cancelled.
indexedRows sent to the index so far; the total once the job has succeeded.
errors, errors_inerrors is true if OpenSearch rejected some documents; errors_in lists them, at most 100.
errorWhy the job failed.
staletrue when a running job has had no heartbeat for 10 minutes, which means the worker is gone.
username, hostWho queued the job and the node that claimed it.
created, started, finished, heartbeat, cancel_requestedTimestamps.

Rows changed while a job runs may be missing from the new index.

Cancel a job​

DELETE /api/v4/search/jobs/{uuid} cancels a job; a comma-separated list of uuids is allowed, and every uuid is checked before anything is written. A cancelled job leaves the search index as it was.

  • 204 — the job was still pending and is cancelled outright, or it had already finished.
  • 202 — the job is running and its worker has to stop it. The job is not stopped yet: poll it until status is cancelled.
Request
DELETE https://api.gc2.io/api/v4/search/jobs/c4a3797e-ec6b-4dac-9474-ada9083620f3 HTTP/1.1
Authorization: Bearer abc123
Response 202
{
"success": true,
"message": "Stopping",
"uuid": ["c4a3797e-ec6b-4dac-9474-ada9083620f3"],
"_links": {
"self": "/api/v4/search/jobs/c4a3797e-ec6b-4dac-9474-ada9083620f3"
}
}
Self-hosting

Jobs are picked up by a worker (app/scripts/search_worker.php) that is started from cron. A job that stays pending means no worker is running on the server. The worker is tuned with searchIndexer.batchPerDb and searchIndexer.keepDays.

Using the SDK​

The @mapcentia/gc2-sdk (0.3.5+) exposes the API through the Search class. The token-less methods and the job methods need 0.3.15+. Errors are thrown as CentiaApiError with .status and .code (e.g. "INDEX_NOT_FOUND"):

import { createCentiaClient, Search } from '@mapcentia/gc2-sdk'
import type { SearchSource } from '@mapcentia/gc2-sdk'

const search = new Search(createCentiaClient({ baseUrl, auth: { getAccessToken } }))

// (Re)build the index. Synchronous: searchable when the call returns
const built = await search.buildSearchIndex('music', 'bands')
// { index: 'mydb_music_bands', message: 'Indexed 42 documents', errors: false, errors_in: [] }
if (built.errors) console.warn(built.errors_in) // some documents failed

// Search by query string — columns are addressed as properties.<column>
const byUri = await search.search('music', 'bands', {
q: 'properties.name:Guns',
size: 20,
sort: 'properties.name.keyword:asc',
})

// Search by query DSL — the hits can be typed
const byDsl = await search.searchPost<SearchSource<{ name: string }>>('music', 'bands', {
query: { match: { 'properties.name': 'Roses' } },
sort: [{ 'properties.name.keyword': 'asc' }],
_source: ['properties.name'],
})
console.log(byDsl.hits.total.value)
for (const hit of byDsl.hits.hits) {
console.log(hit._id, hit._score, hit._source.properties.name)
}

// Without a token: the database is in the path and no credentials are sent
const anonymous = await search.searchPublic('mydb', 'music', 'bands', { q: 'properties.name:Guns' })
const anonymousDsl = await search.searchPostPublic('mydb', 'music', 'bands', {
query: { match: { 'properties.name': 'Roses' } },
})

// A large relation: queue the build as a job and poll it
const job = await search.postSearchJob({ schema: 'music', table: 'bands' }) // 202
const current = await search.getSearchJob(job.uuid) // status, indexed
const running = await search.getSearchJobs({ status: 'running' })
await search.deleteSearchJob(job.uuid) // null on 204, the stopping info on 202

// Analysis settings — PUT replaces the block wholesale and echoes it
const settings = await search.getSearchSettings()
await search.putSearchSettings({ analysis: { ...settings.analysis } })

// Drop the index; the table is not touched
await search.dropSearchIndex('music', 'bands') // { index, dropped: true }

postSearchJob, getSearchJob and deleteSearchJob also take an array, of relations and of uuids respectively. Per-column mapping overrides are written through the Meta client, patchMetaData, with the same elasticsearch block as in the HTTP example.

Error codes​

StatusCodeMeaning
400SEARCH_ERROROpenSearch rejected the query. The message says why.
400INDEX_BUILD_ERRORThe relation has no primary key, or OpenSearch rejected the index — for example a mapping that names an unknown analyzer. PUT …/search and POST /search/jobs.
400INVALID_DATAPUT /search/settings: the body is not an object with an analysis object.
400INVALID_REQUEST/search/jobs: malformed body or uuid.
403NOT_OWNERBuilding, dropping and the analysis settings are for the database owner only.
403SUPER_USER_ONLY/search/jobs is for the database owner only.
403INSUFFICIENT_PRIVILEGESThe sub-user has no read privilege on the relation.
403GEOFENCE_RULES_APPLYA deny or limit rule matches the caller (token route) or everyone (token-less route).
403AUTHENTICATION_REQUIREDToken-less route: reading the relation needs credentials.
404INDEX_NOT_FOUNDThe relation exists, but no index has been built for it.
404INDEX_DROP_ERRORDELETE …/search: there is no index to drop.
404TABLE_NOT_FOUNDThe relation does not exist (POST /search/jobs and the token-less route).
404DATABASE_NOT_FOUNDToken-less route: the database in the path does not exist.
404JOB_NOT_FOUND/search/jobs/{uuid}: unknown uuid.
409JOB_ACTIVEA search index job for the relation is queued or running (PUT …/search and POST /search/jobs).