bodybuilder

http://bodybuilder.js.org

https://github.com/danpaz/bodybuilder

Bodybuilder is a small library that makes elasticsearch queries easier to write, read, and maintain 💪. The whole public api is documented here, but how about a simple example to get started:

bodybuilder()
  .query('match', 'message', 'this is a test')
  .build()

// results in:
{
  query: {
    match: {
      message: 'this is a test'
    }
  }
}

You can chain multiple methods together to build up a more complex query.

bodybuilder()
  .query('match', 'message', 'this is a test')
  .filter('term', 'user', 'kimchy')
  .notFilter('term', 'user', 'cassie')
  .aggregation('terms', 'user')
  .build()

For nested sub-queries or sub-aggregations, pass a function as the last argument and build the nested clause in the body of that function. Note that you must return the builder object in the nested function. For example:

bodybuilder()
  .query('nested', 'path', 'obj1', (q) => {
    return q.query('match', 'obj1.color', 'blue')
  })
  .build()

The entire elasticsearch query DSL is available using the bodybuilder api. There are many more examples in the docs as well as in the tests.

bodybuilder(newBody: Object, newQueries: Object, newFilters: Object, newAggregations: Object, newSuggestions: Object): bodybuilder
Parameters
newBody (Object) Body to initialise with
newQueries (Object) Queries to initialise with
newFilters (Object) Filters to initialise with
newAggregations (Object) Aggregations to initialise with
newSuggestions (Object) Suggestions to initialise with
Returns
bodybuilder: Builder.

sort

Set a sort direction on a given field.

bodybuilder()
  .sort('timestamp', 'desc')
  .build()

You can sort multiple fields at once

bodybuilder()
 .sort([
   {"categories": "desc"},
   {"content": "asc"}
 ])
  .build()

Geo Distance sorting is also supported & it's the only sort type that allows for duplicates

bodyBuilder().sort([
    {
      _geo_distance: {
        'a.pin.location': [-70, 40],
        order: 'asc',
        unit: 'km',
        mode: 'min',
        distance_type: 'sloppy_arc'
      }
    },
    {
      _geo_distance: {
        'b.pin.location': [-140, 80],
        order: 'asc',
        unit: 'km',
        mode: 'min',
        distance_type: 'sloppy_arc'
      }
    }
  ])
  .sort([
    { timestamp: 'desc' },
    { content: 'desc' },
    { content: 'asc' },
   {"price" : {"order" : "asc", "mode" : "avg"}}
  ])
.build()
sort(field: String, direction: String): bodybuilder
Parameters
field (String) Field name.
direction (String = 'asc') A valid direction: 'asc' or 'desc'.
Returns
bodybuilder: Builder.

from

Set a from offset value, for paginating a query.

from(quantity: Number): bodybuilder
Parameters
quantity (Number) The offset from the first result you want to fetch.
Returns
bodybuilder: Builder.

size

Set a size value for maximum results to return.

size(quantity: Number): bodybuilder
Parameters
quantity (Number) Maximum number of results to return.
Returns
bodybuilder: Builder.

rawOption

Set any key-value on the elasticsearch body.

rawOption(k: String, v: any): bodybuilder
Parameters
k (String) Key.
v (any) Value.
Returns
bodybuilder: Builder.

build

Collect all queries, filters, and aggregations and build the entire elasticsearch query.

build(version: string?): Object
Parameters
version (string?) (optional) Pass 'v1' to build for the elasticsearch 1.x query dsl.
Returns
Object: Elasticsearch query body.

clone

Returns a cloned instance of bodybuilder

const bodyA = bodybuilder().size(3);
const bodyB = bodyA.clone().from(2); // Doesn't affect bodyA
// bodyA: { size: 3 }
// bodyB: { size: 3, from: 2 }
clone(): bodybuilder
Returns
bodybuilder: Newly cloned bodybuilder instance

query

Add a query clause to the query body.

query(args: ...any, type: string, field: (string | Object), value: (string | Object), options: Object, nest: Function?): bodybuilder
Parameters
args (...any)
type (string) Query type.
field ((string | Object)) Field to query or complete query clause.
value ((string | Object)) Query term or inner clause.
options (Object) (optional) Additional options for the query clause.
nest (Function?) (optional) A function used to define sub-filters as children. This must be the last argument.
Returns
bodybuilder: Builder.
Example
bodybuilder()
  .query('match_all')
  .build()

bodybuilder()
  .query('match_all', { boost: 1.2 })
  .build()

bodybuilder()
  .query('match', 'message', 'this is a test')
  .build()

bodybuilder()
  .query('terms', 'user', ['kimchy', 'elastic'])
  .build()

bodybuilder()
  .query('nested', { path: 'obj1', score_mode: 'avg' }, (q) => {
    return q
      .query('match', 'obj1.name', 'blue')
      .query('range', 'obj1.count', {gt: 5})
  })
  .build()

andQuery

Alias for query.

andQuery(args: ...any): bodybuilder
Parameters
args (...any)
Returns
bodybuilder: Builder.

addQuery

Alias for query.

addQuery(args: ...any): bodybuilder
Parameters
args (...any)
Returns
bodybuilder: Builder.

orQuery

Add a "should" query to the query body.

Same arguments as query.

orQuery(args: ...any): bodybuilder
Parameters
args (...any)
Returns
bodybuilder: Builder.

notQuery

Add a "must_not" query to the query body.

Same arguments as query.

notQuery(args: ...any): bodybuilder
Parameters
args (...any)
Returns
bodybuilder: Builder.

queryMinimumShouldMatch

Set the minimum_should_match property on a bool query with more than one should clause.

queryMinimumShouldMatch(param: any, override: boolean): bodybuilder
Parameters
param (any) minimum_should_match parameter. For possible values see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-minimum-should-match.html
override (boolean) allows minimum_should_match to be overridden, ignoring internal constraints
Returns
bodybuilder: Builder.

filter

Add a filter clause to the query body.

filter(args: ...any, type: string, field: (string | Object), value: (string | Object), options: Object, nest: Function?): bodybuilder
Parameters
args (...any)
type (string) Filter type.
field ((string | Object)) Field to filter or complete filter clause.
value ((string | Object)) Filter term or inner clause.
options (Object) (optional) Additional options for the filter clause.
nest (Function?) (optional) A function used to define sub-filters as children. This must be the last argument.
Returns
bodybuilder: Builder.
Example
bodybuilder()
  .filter('term', 'user', 'kimchy')
  .build()

andFilter

Alias for filter.

andFilter(args: ...any): bodybuilder
Parameters
args (...any)
Returns
bodybuilder: Builder.

addFilter

Alias for filter.

addFilter(args: ...any): bodybuilder
Parameters
args (...any)
Returns
bodybuilder: Builder.

orFilter

Add a "should" filter to the query body.

Same arguments as filter.

orFilter(args: ...any): bodybuilder
Parameters
args (...any)
Returns
bodybuilder: Builder.

notFilter

Add a "must_not" filter to the query body.

Same arguments as filter.

notFilter(args: ...any): bodybuilder
Parameters
args (...any)
Returns
bodybuilder: Builder.

filterMinimumShouldMatch

Set the minimum_should_match property on a bool filter with more than one should clause.

filterMinimumShouldMatch(param: any, override: boolean): bodybuilder
Parameters
param (any) minimum_should_match parameter. For possible values see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-minimum-should-match.html
override (boolean) allows minimum_should_match to be overridden, ignoring internal constraints
Returns
bodybuilder: Builder.

aggregation

Add an aggregation clause to the query body.

aggregation(args: ...any, type: (string | Object), field: string, options: Object?, name: string?, nest: Function?): bodybuilder
Parameters
args (...any)
type ((string | Object)) Name of the aggregation type, such as 'sum' or 'terms' .
field (string) Name of the field to aggregate over.
options (Object?) (optional) Additional options to include in the aggregation. [options._meta] associate a piece of metadata with individual aggregations [options._name ] another way to pass a custom name to the aggregation.
name (string?) (optional) A custom name for the aggregation, defaults to agg_<type>_<field> .
nest (Function?) (optional) A function used to define sub-aggregations as children. This must be the last argument.
Returns
bodybuilder: Builder.
Example
bodybuilder()
  .aggregation('max', 'price')
  .build()

bodybuilder()
  .aggregation('percentiles', 'load_time', {
    percents: [95, 99, 99.9]
  })
  .build()

bodybuilder()
  .aggregation('date_range', 'date', {
    format: 'MM-yyy',
    ranges: [{ to: 'now-10M/M' }, { from: 'now-10M/M' }]
  })
  .build()

bodybuilder()
  .aggregation('diversified_sampler', 'user.id', { shard_size: 200 }, (a) => {
    return a.aggregation('significant_terms', 'text', 'keywords')
  })
  .build()

bodybuilder()
  .aggregation('terms', 'title', {
     _meta: { color: 'blue' }
   }, 'titles')
  .build()

agg

Alias for aggregation.

agg(args: ...any): bodybuilder
Parameters
args (...any)
Returns
bodybuilder: Builder.

suggest

Add a suggestion clause to the query body.

suggest(args: ...any, field: string, options: Object?): bodybuilder
Parameters
args (...any)
field (string) Name of the field to suggest on.
options (Object?) (optional) Additional options to include in the suggestion clause. [options.text ] text query to run on suggest [options.name ] pass a custom name to the function [options.analyzer ] name of predefined analyzer to use on suggest
Returns
bodybuilder: Builder.
Example
bodybuilder()
  .suggest('term', price', { text: 'test' })
  .build()

bodybuilder()
  .suggest('phrase', 'price', { text: 'test', name: 'custom name' })
  .build()