NestJS
Search (Elasticsearch)
Integrating Elasticsearch for advanced search capabilities in NestJS.
Search Module: Registering the Elasticsearch module.
search.module.ts
typescript
import { Module } from '@nestjs/common';
import { ElasticsearchModule } from '@nestjs/elasticsearch';
import { SearchService } from './search.service';
@Module({
imports: [
ElasticsearchModule.register({
node: 'http://localhost:9200',
}),
],
providers: [SearchService],
exports: [SearchService],
})
export class SearchModule {}
Search Service: Using ElasticsearchService to perform queries.
search.service.ts
typescript
import { Injectable } from '@nestjs/common';
import { ElasticsearchService } from '@nestjs/elasticsearch';
@Injectable()
export class SearchService {
constructor(private readonly elasticsearchService: ElasticsearchService) {}
async indexPost(post: any) {
return this.elasticsearchService.index({
index: 'posts',
document: {
id: post.id,
title: post.title,
content: post.content,
},
});
}
async searchPosts(text: string) {
const result = await this.elasticsearchService.search({
index: 'posts',
query: {
multi_match: {
query: text,
fields: ['title', 'content'],
},
},
});
return result.hits.hits.map((hit: any) => hit._source);
}
}