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.
Declare the search fields
Section titled “Declare the search fields”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:
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' }, },});nameanddescriptionaretext, so basic search matches their words, withnameweighted higher.nameis also a sort.entityTypeis akeyword, 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).
Create the index
Section titled “Create the index”createIndex() builds the index mapping from the declarations:
import { opensearch, search } from '../src/search.ts';
await search.createIndex();await opensearch.close();node --env-file=.env scripts/create-index.tsRunning 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.
Index documents
Section titled “Index documents”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.