Skip to content
These docs describe arocapi v5, which is in beta. Install it with pnpm add arocapi@beta.

OpenSearch

arocapi answers POST /search through a search backend. This guide uses OpenSearchBackend, which keeps one search document per entity in an OpenSearch index. Your code supplies the documents: arocapi never builds them from the database.

Create the backend in a module of its own, so the server and your scripts share it. Each field is declared once, with a type and the roles clients may use it for:

src/search.ts
import { Client } from '@opensearch-project/opensearch';
import { OpenSearchBackend } from 'arocapi/search/opensearch';
export const opensearch = new Client({ node: process.env.OPENSEARCH_URL });
export const search = OpenSearchBackend({
client: opensearch,
fields: {
name: { type: 'text', weight: 2, sort: true, label: 'Name' },
description: { type: 'text' },
entityType: { type: 'keyword', facet: true, label: 'Type' },
},
});
  • name and description are text, so basic search matches their words, with name weighted higher. name is also a sort.
  • entityType is a keyword, matched exactly. As a facet, the response counts each type, and clients can filter by it.

Nothing else is searchable: a field is only filtered, faceted or sorted on if you declare it. Search lists every type and role, and OpenSearchBackend’s options, such as indexName (default entities).

createIndex() builds the index mapping from the declarations:

scripts/create-index.ts
import { opensearch, search } from '../src/search.ts';
await search.createIndex();
await opensearch.close();
Terminal window
node --env-file=.env scripts/create-index.ts

Running it again leaves a matching index alone. If you later change a declaration, it throws, naming the field; delete the index, create it again and index your entities.

Add an entity to the database first, then index its search document: its id and a value for each declared field you have. search.index([...]) is typed from the declarations, so an undeclared field or a wrong value type fails to compile. arocapi loads each hit’s entity from the database, and leaves out a hit with no entity.

Next, write your first API, which adds an entity to the database and the index.