@sebspark/opensearch
A wrapper for OpenSearch Client to assist with typed queries, indices etc
Add
yarn add @sebspark/opensearch
Usage
Everything starts with an index definition. This must be declared as a const which satisfies OpenSearchIndexMapping. From this you can then derive your documents and search queries.
import type {
IndexDefinition,
DocumentFor,
SearchRequest,
} from '@sebspark/opensearch'
export const personIndex = {
index: 'person',
body: {
mappings: {
properties: {
name: { type: 'keyword' },
age: { type: 'integer' },
},
},
},
} as const satisfies IndexDefinition
export type PersonIndex = typeof personIndex
export type PersonDocument = DocumentFor<PersonIndex>
export type PersonSearch = SearchRequest<PersonIndex>
Using the index definition and your types, you can now start interacting with OpenSearch with typeahead:
import { OpenSearchClient } from '@sebspark/opensearch'
import {
personIndex,
type PersonIndex,
type PersonDocument,
type PersonSearch,
} from './personIndex'
async function run () {
const client = new OpenSearchClient()
const { body: exists } = await client.indices.exists<PersonIndex>({ index: 'person' })
if (!exists) {
await client.indices.create(personIndex)
}
const doc: PersonDocument = {
name: 'John Wick',
age: 52,
}
await client.index<PersonIndex>({
index: 'person',
body: doc,
})
const searchQuery: PersonSearch = {
index: personIndexName,
body: {
query: {
match: {
name: 'John Wick'
}
}
}
}
const result = await client.search(searchQuery)
}
Helpers
Bulk operations
Since bulk operations are a bit tricky to call, this library offers a few utility functions to simplify:
import {
bulkIndex,
bulkCreate,
bulkUpdate,
bulkDelete,
} from '@sebspark/opensearch'
const indexWithAutoId = bulkIndex<PersonIndex>('persons', [
{ name: 'John Wick', age: 52 },
{ name: 'Jason Bourne', age: 50 },
])
await opensearchClient.bulk(indexWithAutoId)
const idGen = (doc: PersonDocument) =>
doc.name.replace(/\s/g, '').toLowerCase()
const indexWithIdGen = bulkIndex<PersonIndex>('persons', [
{ name: 'John Wick', age: 52 },
{ name: 'Jason Bourne', age: 50 },
], idGen)
await opensearchClient.bulk(indexWithIdGen)
const createDocs = bulkCreate<PersonIndex>('persons', [
{ name: 'John Wick', age: 52 },
{ name: 'Jason Bourne', age: 50 },
], idGen)
await opensearchClient.bulk(createDocs)
const updateDocs = bulkUpdate<PersonIndex>('persons', [
{ doc: { name: 'John Wick', age: 53 } },
{ doc: { name: 'Jason Bourne', age: 51 } },
], idGen)
await opensearchClient.bulk(updateDocs)
const deleteDocs = bulkDelete<PersonIndex>('persons', [
'johnwick',
'jasonbourne',
])
await opensearchClient.bulk(deleteDocs)