Elasticsearch is a powerful search and analytics engine. This guide covers implementing Elasticsearch for production applications.
Setup
Install Elasticsearch
bash
npm install @elastic/elasticsearchClient Configuration
typescript
import { Client } from '@elastic/elasticsearch';
const client = new Client({
node: process.env.ELASTICSEARCH_URL || 'http://localhost:9200',
});Indexing Documents
Create Index
typescript
export async function createIndex(index: string) {
await client.indices.create({
index,
body: {
mappings: {
properties: {
title: { type: 'text' },
description: { type: 'text' },
timestamp: { type: 'date' },
},
},
},
});
}Index Document
typescript
export async function indexDocument(index: string, document: any) {
await client.index({
index,
id: document.id,
body: document,
});
}Search Queries
Basic Search
typescript
export async function search(index: string, query: string) {
const response = await client.search({
index,
body: {
query: {
multi_match: {
query,
fields: ['title^2', 'description'],
},
},
},
});
return response.hits.hits;
}Conclusion
Elasticsearch provides powerful full-text search. Use proper mappings for optimal performance. Implement aggregations for analytics.