Elasticsearch Query DSL Builder

4.1.0 · active · verified Wed Apr 22

Elastic-builder is a JavaScript library designed to construct Elasticsearch Query DSL (Domain Specific Language) bodies using a fluent builder pattern, making complex queries easier to write and maintain. Currently in stable version 4.1.0, the package sees a consistent release cadence, with updates typically occurring every 1-2 months to introduce new features and maintain compatibility with modern Node.js versions. Its key differentiators include comprehensive TypeScript definitions for an enhanced development experience, compatibility with the official Elasticsearch JavaScript client, and a focus on replicating Elasticsearch 5.x DSL (while largely usable with newer versions). It provides both class-based and functional builder utilities (e.g., `new esb.MatchQuery()` vs. `esb.matchQuery()`) and recently removed `lodash` as a dependency in v4.1.0, reducing its footprint.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates building a complex Elasticsearch query body using a boolean query, range filter, terms aggregation, and sorting, then outputs the JSON representation.

import * as esb from 'elastic-builder';

// Build a complex search request with a query, aggregation, and sorting.
const requestBody = esb.requestBodySearch()
  .query(
    esb.boolQuery()
      .must(esb.matchQuery('message', 'this is a test'))
      .filter(esb.rangeQuery('timestamp').gte('now-1d/d'))
  )
  .agg(
    esb.termsAggregation('top_tags', 'tags.keyword')
      .size(10)
      .order('_count', 'desc')
  )
  .sort(esb.sort('timestamp', 'desc'));

// Convert the builder object to its JSON representation
const queryJson = requestBody.toJSON();

console.log('Generated Elasticsearch Query Body:');
console.log(JSON.stringify(queryJson, null, 2));

view raw JSON →