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:
| Resource | What it is |
|---|---|
/api/v4/schemas/{schema}/tables/{table}/search | The 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/jobs | Search index jobs: queued index builds for large relations. |
/api/v4/search/settings | The 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:
- Web App
- HTTP
PUT https://api.gc2.io/api/v4/schemas/music/tables/bands/search HTTP/1.1
Accept: application/json; charset=utf-8
Authorization: Bearer abc123
{
"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
gidcolumn). It becomes the document_id. Without one the build is refused with400(INDEX_BUILD_ERROR). - Check
errorsin the response.truemeans the index exists but OpenSearch rejected some documents; they are listed inerrors_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,
PUTanswers409(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:
- Web App
- HTTP
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
{
"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.
| Parameter | Description |
|---|---|
q | Lucene query string, e.g. properties.name:Guns. |
size | Maximum number of hits to return. Default 10. |
from | Offset of the first hit, for paging. Default 0. |
sort | Comma-separated <field>:<asc|desc> pairs, e.g. properties.name.keyword:asc. |
_source | Comma-separated list of _source fields to return, or false to leave _source out. |
default_operator | Default operator for q: AND or OR. Default OR. |
df | Default field for q when a term has no field prefix. |
default_operatoranddfare only valid together withq. Sent alone, OpenSearch rejects the request with400.- Sort and aggregate text on the
.keywordsub-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:
- Web App
- HTTP
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:
| Code | Meaning |
|---|---|
INSUFFICIENT_PRIVILEGES | The sub-user has no read privilege on the relation. |
GEOFENCE_RULES_APPLY | A 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:
- Web App
- HTTP
DELETE https://api.gc2.io/api/v4/schemas/music/tables/bands/search HTTP/1.1
Accept: application/json; charset=utf-8
Authorization: Bearer abc123
{
"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:
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
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
WriteorNone, which both let anyone read. A relation onRead/writeanswers403(AUTHENTICATION_REQUIRED); search it on the token route instead. - A geofence deny or limit rule for everyone (
*) refuses the search with403(GEOFENCE_RULES_APPLY), as the index cannot apply a row filter. 404isDATABASE_NOT_FOUND,TABLE_NOT_FOUNDorINDEX_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 type | OpenSearch type |
|---|---|
| Text | text with a keyword sub-field |
| Integers | integer / long |
| Decimals | float / double |
| Dates | date |
| Point geometry | geo_point |
| Other geometry | geo_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:
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:
| Key | Description |
|---|---|
elasticsearchtype | OpenSearch 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. |
analyzer | Index-time analyzer, also used at search time unless search_analyzer is set. Text fields only. |
search_analyzer | Search-time analyzer. Text fields only. |
index | Boolean. false makes the field not searchable. |
format | Date format for date fields, e.g. yyyy-MM-dd. |
null_value | Value indexed in place of null. |
fielddata | Boolean. Enables fielddata on a text field, for sorting and aggregation. |
fields | Multi-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.
PATCHreplaces the wholeelasticsearchblock of the relation. Send every column that has overrides, not only the one you change. Read the block withGET /api/v4/meta, modify it and write it back.- Reset one column by sending the block without it. Clear all overrides with
"elasticsearch": {}. - Setting
fieldsreplaces the automatickeywordsub-field, soproperties.<column>.keyworddisappears 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 asdanishorenglish). An unknown analyzer fails the build with400(INDEX_BUILD_ERROR). - A mapping change takes effect on the next build.
- The
elasticsearchblock 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:
- Web App
- HTTP
GET https://api.gc2.io/api/v4/search/settings HTTP/1.1
Accept: application/json; charset=utf-8
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"]
}
},
"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:
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":
- Set
analyzertoauto_complete_analyzerandsearch_analyzertoauto_complete_search_analyzeron the column, as in the mapping example above. - Rebuild the index.
- 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).
POST https://api.gc2.io/api/v4/search/jobs HTTP/1.1
Content-Type: application/json
Authorization: Bearer abc123
{
"schema": "music",
"table": "bands"
}
{
"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).
GET https://api.gc2.io/api/v4/search/jobs/c4a3797e-ec6b-4dac-9474-ada9083620f3 HTTP/1.1
Authorization: Bearer abc123
{
"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"
}
}
| Field | Description |
|---|---|
uuid | The job id. |
schema, table | The relation whose index is built. |
index | The index name clients search: <database>_<schema>_<table>. |
status | pending, running, succeeded, failed or cancelled. |
indexed | Rows sent to the index so far; the total once the job has succeeded. |
errors, errors_in | errors is true if OpenSearch rejected some documents; errors_in lists them, at most 100. |
error | Why the job failed. |
stale | true when a running job has had no heartbeat for 10 minutes, which means the worker is gone. |
username, host | Who queued the job and the node that claimed it. |
created, started, finished, heartbeat, cancel_requested | Timestamps. |
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 stillpendingand is cancelled outright, or it had already finished.202— the job isrunningand its worker has to stop it. The job is not stopped yet: poll it untilstatusiscancelled.
DELETE https://api.gc2.io/api/v4/search/jobs/c4a3797e-ec6b-4dac-9474-ada9083620f3 HTTP/1.1
Authorization: Bearer abc123
{
"success": true,
"message": "Stopping",
"uuid": ["c4a3797e-ec6b-4dac-9474-ada9083620f3"],
"_links": {
"self": "/api/v4/search/jobs/c4a3797e-ec6b-4dac-9474-ada9083620f3"
}
}
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
| Status | Code | Meaning |
|---|---|---|
400 | SEARCH_ERROR | OpenSearch rejected the query. The message says why. |
400 | INDEX_BUILD_ERROR | The 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. |
400 | INVALID_DATA | PUT /search/settings: the body is not an object with an analysis object. |
400 | INVALID_REQUEST | /search/jobs: malformed body or uuid. |
403 | NOT_OWNER | Building, dropping and the analysis settings are for the database owner only. |
403 | SUPER_USER_ONLY | /search/jobs is for the database owner only. |
403 | INSUFFICIENT_PRIVILEGES | The sub-user has no read privilege on the relation. |
403 | GEOFENCE_RULES_APPLY | A deny or limit rule matches the caller (token route) or everyone (token-less route). |
403 | AUTHENTICATION_REQUIRED | Token-less route: reading the relation needs credentials. |
404 | INDEX_NOT_FOUND | The relation exists, but no index has been built for it. |
404 | INDEX_DROP_ERROR | DELETE …/search: there is no index to drop. |
404 | TABLE_NOT_FOUND | The relation does not exist (POST /search/jobs and the token-less route). |
404 | DATABASE_NOT_FOUND | Token-less route: the database in the path does not exist. |
404 | JOB_NOT_FOUND | /search/jobs/{uuid}: unknown uuid. |
409 | JOB_ACTIVE | A search index job for the relation is queued or running (PUT …/search and POST /search/jobs). |