In NestJS, adding an Elasticsearch connection to AppModule typically involves the following steps:
-
Install the Elasticsearch client library.
-
Create an Elasticsearch module.
-
Import the Elasticsearch module into
AppModule.
Here are the specific steps, including example code:
Step 1: Install the Elasticsearch client library
First, install the official Elasticsearch client. You can install it using npm or yarn:
shellnpm install @elastic/elasticsearch
or
shellyarn add @elastic/elasticsearch
Step 2: Create the Elasticsearch module
Create a new module to encapsulate Elasticsearch-related configuration and services. This can be done using the NestJS CLI tool or by manually creating files.
shellnest generate module elasticsearch
Then, in the elasticsearch.module.ts file, configure the Elasticsearch client instance. Here is a simple configuration example:
typescriptimport { Module } from '@nestjs/common'; import { Client } from '@elastic/elasticsearch'; @Module({ providers: [ { provide: 'ELASTICSEARCH_CLIENT', useFactory: async () => new Client({ node: 'http://localhost:9200', // This should be your Elasticsearch node address // If you have other configurations, such as authentication details, you can add them here }), }, ], exports: ['ELASTICSEARCH_CLIENT'], }) export class ElasticsearchModule {}
Step 3: Import the Elasticsearch module into AppModule
Finally, import ElasticsearchModule into the root module AppModule.
typescriptimport { Module } from '@nestjs/common'; import { ElasticsearchModule } from './elasticsearch/elasticsearch.module'; @Module({ imports: [ElasticsearchModule], // Other controllers and providers }) export class AppModule {}
Now, your NestJS application is configured with the Elasticsearch client and can be injected and used where needed.
Example of using the Elasticsearch client in a service or controller:
typescriptimport { Injectable, Inject } from '@nestjs/common'; import { Client } from '@elastic/elasticsearch'; @Injectable() export class SearchService { constructor( @Inject('ELASTICSEARCH_CLIENT') private readonly elasticsearchClient: Client ) {} async search(index: string, query: any) { const result = await this.elasticsearchClient.search({ index, body: query, }); return result.body.hits.hits; } }
In this example, we define a SearchService that can be injected wherever search operations are needed and uses elasticsearchClient to perform search operations. This service can further encapsulate specific Elasticsearch operations, providing a more convenient API for other parts of the application.
This process can be adjusted based on your specific requirements, for example, you may need to add more configuration options, handle authentication and authorization, or create more advanced service encapsulation.