An Elastic Search Module for Nest.js
Description
This package wrap features provided by the official elastic search client for Node.js into a nest.js provider ElasticSearchService
in ElasticSearchModule
.
Installation
$ npm install @protocod/nest-elasticsearch --dev
How to use
Go to your favorite module and import ElasticSearchModule
import { Module, Logger } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
import { Product } from './product.entity'
import { ProductTag } from './product.tag.entity'
import { Tag } from './tag.entity'
import { ElasticSearchModule } from '@protocod/nest-elasticsearch'
import { ProductController } from './product.controller'
import { ProductService } from './product.service'
@Module({
imports: [
TypeOrmModule.forFeature([
Product,
ProductTag,
Tag
]),
ElasticSearchModule.setOptions({
node: 'http://localhost:9200',
requestTimeout: 3000
})
],
providers: [
Logger,
ProductService
],
controllers: [
ProductController
]
})
export class ProductModule {}
And simply inject the ElasticSearchService
into your business layer
import { Controller, Get, Query } from '@nestjs/common'
import { ProductIndex } from './index/product.index'
import { ElasticSearchService } from '@protocod/nest-elasticsearch'
import { ApiResponse } from '@elastic/elasticsearch'
@Controller('products')
export class ProductController {
constructor(private readonly elasticSearchService: ElasticSearchService) {}
@Get()
async getAllProducts(@Query('search') search: string): Promise<ReadonlyArray<ProductIndex>> {
const apiResponse: ApiResponse<any> = await this.elasticSearchService.search({
index: 'products',
body: {
query: {
query_string: {
allow_leading_wildcard: true,
query: `*${search}*`
}
}
}
})
return apiResponse.body.hits.hits.map(index => index._source)
}
}