npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@codemask-labs/nestjs-elasticsearch

v2.8.0

Published

Schema based Elasticsearch, NestJS module with utilities, type-safe queries and aggregations builders.

Downloads

1,023

Readme

NestJS Elasticsearch Module

Welcome to Nestjs Elasticsearch module based on @nestjs/elasticsearch package.

The current version (2.x) is fully compatible with Elasticsearch 8. For projects using Elasticsearch 7, use the previous version (1.x).

Motive

This package originates from our experience with using Elasticsearch in production environments, which leaded to maintenance issues when extensively used aggregations, searches and filters (especially aggregations).

The main issues we encountered and which our package fixes are:

  1. Current Elasticsearch NestJS Module does not provide autocompletion for queries.
  2. Elasticsearch response forgets about types of aggregations.
  3. Since Elasticsearch indexes can be schema-less we got no proper feedback about what fields we should expect on the index.
  4. Writing utility methods for all filters and aggregations queries caused a lot of boilerplate code in each project.

Features

  • :rocket: Quick Setup - Get up and running in minutes using our easy-to-understand API.

  • :nerd_face: :computer: Developer Experience - Designed with developers in mind, package prioritizes ease of use and efficiency throughout the development process.

  • :white_check_mark: Full TypeScript Support - Enjoy the benefits of code autocompletion and types for both request and response objects. ⁤⁤Unlike the original Elasticsearch library, this package provides full type definitions in order to provide better development experience and minimize runtime errors. ⁤

  • :hammer_and_wrench: Utility Methods - Say goodbye to repetitive boilerplate code. The package offers set of utility methods for most common Elasticsearch filtering, sorting, pagination and aggregations use cases.

  • :bookmark_tabs: Schema definitions - Schema definitions are integrated into the package, with each schema mapping to an Elasticsearch index to provide a clear data model. These definitions are used to register indexes in the module scope and inject them into a service, similar to the approach in the TypeORM NestJS module, ensuring that only fields available for a given index are used when building request objects.

Installation

You can install package using yarn or npm:

$ yarn add @codemask-labs/nestjs-elasticsearch
$ npm i @codemask-labs/nestjs-elasticsearch

Getting started

Once the package is installed, you can start with importing the ElasticsearchModule into the AppModule.

import { ElasticsearchModule } from '@codemask-labs/nestjs-elasticsearch'

@Module({
    imports: [
        ElasticsearchModule.register({
            node: 'http://localhost:9200'
        })
    ]
})
class AppModule {}

The register() method supports all the configuration properties available in ClientOptions from the @elastic/elasticsearch package.

Registering the index

You can define index schema with @RegisterIndex() decorator.

import { RegisterIndex } from '@codemask-labs/nestjs-elasticsearch'

@RegisterIndex('examples')
export class ExampleDocument {
    readonly id: string
    readonly exampleField: string
    readonly exampleNumericField: number
}

Add index to a module

The ElasticsearchModule provides the forFeature() method to configure the module and define which indexes should be registered in the current scope.

import { ElasticsearchModule } from '@codemask-labs/nestjs-elasticsearch'
import { ExampleDocument } from './example.document'

@Module({
    imports: [ElasticsearchModule.forFeature([ExampleDocument])],
    providers: [ExampleService]
})
export class ExampleModule {}

Inject index in a service

With module configuration in place, we can inject the ExampleDocument into the ExampleService using the @InjectIndex() decorator:

import { Injectable } from '@nestjs/common'
import { Index } from '@codemask-labs/nestjs-elasticsearch'
import { ExampleDocument } from './example.document'

@Injectable()
export class ExampleService {
    @InjectIndex(ExampleDocument)
    private readonly exampleIndex: Index<ExampleDocument>

    getExampleDocuments() {
        return this.exampleIndex.search()
    }
}

Now you can start creating request to Elasticsearch.

Usage

Once you finish the Getting Started guide, you can start building Elasticsearch request objects.

You can put request object directly in the search() method

import { getBoolQuery, getTermQuery, Order } from '@codemask-labs/nestjs-elasticsearch'

getExampleDocuments() {
    return this.exampleIndex.search({
        size: 10,
        query: getBoolQuery({
            must: [
                getTermQuery('exampleField.keyword', 'Some value'),
                getRangeQuery('exampleNumericField', {
                    gte: 1,
                    lte: 10
                })
            ]
        }),
        sort: {
            'exampleField.keyword': {
                order: Order.ASC
            }
        }
    })
}

or use getSearchRequest() method if you want to move request creation to some other place, but still laverage full type support and autocompletion.

import { getBoolQuery, getTermQuery, getSearchRequest, Order } from '@codemask-labs/nestjs-elasticsearch'
import { ExampleDocument } from './example.document'

const searchRequestBody = getSearchRequest(ExampleDocument, {
    size: 10,
    query: getBoolQuery({
        must: [
            getTermQuery('exampleField.keyword', 'Some value'),
            getRangeQuery('exampleNumericField', {
                gte: 1,
                lte: 10
            })
        ]
    }),
    sort: {
        'exampleField.keyword': {
            order: Order.ASC
        }
    }
})

Queries

As for now the package provides utils for the following filter queries:

| Query DSL | Function Name | Documentation | | :------------------------------- | :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------ | | Compound queries | getBoolQuery() | Boolean query | | | getMustQuery() | | | | getMustNotQuery() | | | | getShouldQuery() | | | Full text queries | getMatchQuery() | Match query | | | getMatchPhrasePrefixQuery() | Match phrase prefix query | | Term-level queries | getExistsQuery() | Exists query | | | getRangeQuery() | Range query | | | getTermQuery() | Term query | | | getTermsQuery() | Terms query | | minimum_should_match parameter | getMinimumShouldMatchParameter() | minimum_should_match parameter |

Aggregations

As for now the package provides utils for the following aggregation queries:

| Aggregations | Function Name | Documentation | | :-------------------- | :------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------- | | Bucket Aggregations | getCompositeAggregation() | Composite aggregation | | | getDateHistogramAggregation() | Date histogram aggregation | | | getFilterAggregation() | Filter aggregation | | | getHistogramAggregation() | Histogram aggregation | | | getMissingValueAggregation() | Missing aggregation | | | getRangeAggregation() | Range aggregation | | | getTermsAggregation() | Terms aggregation | | Metrics Aggregations | getAvgAggregation() | Avg aggregation | | | getCardinalityAggregation() | Cardinality aggregation | | | getGeoCentroidAggregation() | Geo-centroid aggregation | | | getMaxAggregation() | Max aggregation | | | getMinAggregation() | Min aggregation | | | getPercentileAggregation() | Percentiles aggregation | | | getSumAggregation() | Sum aggregation | | | getTopHitsAggregation() | Top hits aggregation | | | getValueCountAggregation() | Value count aggregation | | Pipeline Aggregations | getBucketScriptAggregation() | Bucket script aggregation | | | getBucketSelectorAggregation() | Bucket selector aggregation | | | getBucketSortAggregation() | Bucket sort aggregation | | | getStatsBucketAggregation() | Stats bucket aggregation |

License

MIT