elastic-builder

2.30.0

elastic-builder

https://github.com/sudo-suhas/elastic-builder

elastic-builder is a library for easily building elasticsearch request body for search. It implements the builder syntax for building complex queries combining queries and aggregations.

What's Included:

The complete library documentation is present here.

There are two ways to use the classes for constructing queries:

// Import the library
const esb = require('elastic-builder'); // the builder

// Use `new` keyword for constructor instances of class
const requestBody = new esb.RequestBodySearch()
    .query(new esb.MatchQuery('message', 'this is a test'));

// Or use helper methods which construct the object without need for the `new` keyword
const requestBody = esb.requestBodySearch()
    .query(esb.matchQuery('message', 'this is a test'));

// Build the request body
requestBody.toJSON()
{
   "query": {
     "match": {
       "message": "this is a test"
     }
   }
 }

Demo - https://elastic-builder.js.org/

ProTip: The source is transpiled using babel for compatibility with older versions of node and used by default. But this is not required in node env 6 and above. You can directly use the src files:

const esb = require('elastic-builder/src');

This module is heavily influenced by elastic.js(not maintained anymore).

elastic-builder

https://github.com/sudo-suhas/elastic-builder

elastic-builder is a library for easily building elasticsearch request body for search. It implements the builder syntax for building complex queries combining queries and aggregations.

What's Included:

The complete library documentation is present here.

There are two ways to use the classes for constructing queries:

// Import the library
const esb = require('elastic-builder'); // the builder

// Use `new` keyword for constructor instances of class
const requestBody = new esb.RequestBodySearch()
    .query(new esb.MatchQuery('message', 'this is a test'));

// Or use helper methods which construct the object without need for the `new` keyword
const requestBody = esb.requestBodySearch()
    .query(esb.matchQuery('message', 'this is a test'));

// Build the request body
requestBody.toJSON()
{
   "query": {
     "match": {
       "message": "this is a test"
     }
   }
 }

Demo - https://elastic-builder.js.org/

ProTip: The source is transpiled using babel for compatibility with older versions of node and used by default. But this is not required in node env 6 and above. You can directly use the src files:

const esb = require('elastic-builder/src');

This module is heavily influenced by elastic.js(not maintained anymore).

The RequestBodySearch object provides methods generating an elasticsearch search request body. The search request can be executed with a search DSL, which includes the Query DSL, within its body.

Elasticsearch reference

new RequestBodySearch()
Example
const reqBody = esb.requestBodySearch()
    .query(esb.termQuery('user', 'kimchy'))
    .from(0)
    .size(10);

reqBody.toJSON();
{
  "query": { "term": { "user": "kimchy" } },
  "from": 0,
  "size": 10
}
// Query and aggregation
const reqBody = esb.requestBodySearch()
    .query(esb.matchQuery('business_type', 'shop'))
    .agg(
        esb.geoBoundsAggregation('viewport', 'location').wrapLongitude(true)
    );
// Query, aggregation with nested
const reqBody = esb.requestBodySearch()
    .query(esb.matchQuery('crime', 'burglary'))
    .agg(
        esb.termsAggregation('towns', 'town').agg(
            esb.geoCentroidAggregation('centroid', 'location')
        )
    );
Instance Members
query(query)
kNN(knn)
agg(agg)
aggregation(agg)
aggs(aggs)
aggregations(aggs)
suggest(suggest)
suggestText(txt)
timeout(timeout)
from(from)
size(size)
terminateAfter(numberOfDocs)
sort(sort)
sorts(sorts)
trackScores(enable)
trackTotalHits(enableOrLimit)
source(source)
storedFields(fields)
runtimeMapping(runtimeFieldName, runtimeField)
runtimeMappings(runtimeMappings)
scriptField(scriptFieldName, script)
scriptFields(scriptFields)
docvalueFields(fields)
postFilter(filterQuery)
highlight(highlight)
rescore(rescore)
explain(enable)
version(enable)
indexBoost(index, boost)
indicesBoost(index, boost)
minScore(score)
collapse(field, innerHits?, maxConcurrentGroupRequests?)
searchAfter(values)
toJSON()

Queries

These classes allow creation and manipulation of objects which map to elasticsearch DSL for queries.

Queries

These classes allow creation and manipulation of objects which map to elasticsearch DSL for queries.

Base class implementation for all query types.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class should be extended and used, as validation against the class type is present in various places.

new Query(queryType: string)
Parameters
queryType (string)
Instance Members
boost(factor)
name(name)
getDSL()
toJSON()

The most simple query, which matches all documents, giving them all a _score of 1.0.

Elasticsearch reference

new MatchAllQuery()

Extends Query

Example
const qry = esb.matchAllQuery().boost(1.2);

The inverse of the match_all query, which matches no documents.

Elasticsearch reference

new MatchNoneQuery()

Extends Query

Example
const qry = esb.matchNoneQuery();

Full Text Queries

Full Text Queries

The FullTextQueryBase provides support for common options used across various full text query implementations.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new FullTextQueryBase(queryType: string, queryString: string?)

Extends Query

Parameters
queryType (string)
queryString (string?) The query string
Instance Members
analyzer(analyzer)
minimumShouldMatch(minimumShouldMatch)
query(queryString)

The MonoFieldQueryBase provides support for common options used across various full text query implementations with single search field.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new MonoFieldQueryBase(queryType: string, field: string?, queryString: string?)

Extends FullTextQueryBase

Parameters
queryType (string)
field (string?) The document field to query against
queryString (string?) The query string
Instance Members
field(field)
toJSON()

match query accepts text/numerics/dates, analyzes them, and constructs a query.

Elasticsearch reference

new MatchQuery(field: string?, queryString: string?)

Extends MonoFieldQueryBase

Parameters
field (string?) The document field to query against
queryString (string?) The query string
Example
const matchQry = esb.matchQuery('message', 'to be or not to be');
// Providing additional parameters:
const qry = esb.matchQuery('message', 'this is a test').operator('and');
Instance Members
operator(operator)
lenient(enable)
fuzziness(factor)
prefixLength(len)
maxExpansions(limit)
rewrite(method)
fuzzyRewrite(method)
fuzzyTranspositions(enable)
zeroTermsQuery(behavior)
cutoffFrequency(frequency)

The MatchPhraseQueryBase provides support for common options used across various bucket match phrase query implementations.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new MatchPhraseQueryBase(queryType: string, refUrl: string, field: string?, queryString: string?)

Extends MonoFieldQueryBase

Parameters
queryType (string)
refUrl (string)
field (string?) The document field to query against
queryString (string?) The query string
Instance Members
minimumShouldMatch()
slop(slop)

The match_phrase query analyzes the text and creates a phrase query out of the analyzed text.

Elasticsearch reference

new MatchPhraseQuery(field: string?, queryString: string?)

Extends MatchPhraseQueryBase

Parameters
field (string?) The document field to query against
queryString (string?) The query string
Example
const qry = esb.matchPhraseQuery('message', 'to be or not to be');

Elasticsearch reference

new MatchPhrasePrefixQuery(field: string?, queryString: string?)

Extends MatchPhraseQueryBase

Parameters
field (string?) The document field to query against
queryString (string?) The query string
Example
const qry = esb.matchPhrasePrefixQuery('message', 'quick brown f');
Instance Members
maxExpansions(limit)

A MultiMatchQuery query builds further on top of the MultiMatchQuery by allowing multiple fields to be specified. The idea here is to allow to more easily build a concise match type query over multiple fields instead of using a relatively more expressive query by using multiple match queries within a bool query.

Elasticsearch reference

new MultiMatchQuery(fields: (Array<string> | string)?, queryString: string?)

Extends FullTextQueryBase

Parameters
fields ((Array<string> | string)?) The fields to be queried
queryString (string?) The query string
Example
const qry = esb.multiMatchQuery(['subject', 'message'], 'this is a test');
Instance Members
field(field)
fields(fields)
type(type)
tieBreaker(factor)
operator(operator)
lenient(enable)
slop(slop)
fuzziness(factor)
prefixLength(len)
maxExpansions(limit)
rewrite(method)
fuzzyRewrite(method)
zeroTermsQuery(behavior)
cutoffFrequency(frequency)

The common terms query is a modern alternative to stopwords which improves the precision and recall of search results (by taking stopwords into account), without sacrificing performance.

Elasticsearch reference

new CommonTermsQuery(field: string?, queryString: string?)

Extends MonoFieldQueryBase

Parameters
field (string?) The document field to query against
queryString (string?) The query string
Example
const qry = esb.commonTermsQuery('body','this is bonsai cool')
    .cutoffFrequency(0.001);
Instance Members
cutoffFrequency(frequency)
lowFreqOperator(operator)
highFreqOperator(operator)
lowFreq(lowFreqMinMatch)
highFreq(highFreqMinMatch)
disableCoord(enable)

The QueryStringQueryBase provides support for common options used across full text query implementations QueryStringQuery and SimpleQueryStringQuery. A query that uses a query parser in order to parse its content.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

Elasticsearch reference

new QueryStringQueryBase(queryType: string, refUrl: string, queryString: string?)

Extends FullTextQueryBase

Parameters
queryType (string)
refUrl (string)
queryString (string?) The actual query to be parsed.
Instance Members
field(field)
fields(fields)
defaultOperator(operator)
analyzeWildcard(enable)
lenient(enable)
quoteFieldSuffix(suffix)
allFields(enable)

A query that uses a query parser in order to parse its content.

Elasticsearch reference

new QueryStringQuery(queryString: string?)

Extends QueryStringQueryBase

Parameters
queryString (string?) The actual query to be parsed.
Example
const qry = esb.queryStringQuery('this AND that OR thus')
    .defaultField('content');
Instance Members
defaultField(field)
allowLeadingWildcard(enable)
enablePositionIncrements(enable)
fuzzyMaxExpansions(limit)
fuzziness(factor)
fuzzyPrefixLength(len)
rewrite(method)
fuzzyRewrite(method)
phraseSlop(slop)
autoGeneratePhraseQueries(enable)
maxDeterminizedStates(limit)
timeZone(zone)
splitOnWhitespace(enable)
useDisMax(enable)
tieBreaker(factor)
quoteAnalyzer(analyzer)
escape(enable)

A query that uses the SimpleQueryParser to parse its context. Unlike the regular query_string query, the simple_query_string query will never throw an exception, and discards invalid parts of the query.

Elasticsearch reference

new SimpleQueryStringQuery(queryString: string?)

Extends QueryStringQueryBase

Parameters
queryString (string?) The query string
Example
const qry = esb.simpleQueryStringQuery(
    '"fried eggs" +(eggplant | potato) -frittata'
)
    .analyzer('snowball')
    .fields(['body^5', '_all'])
    .defaultOperator('and');
Instance Members
flags(flags)

Term Level Queries

Term Level Queries

The ValueTermQueryBase provides support for common options used across various term level query implementations.

new ValueTermQueryBase(queryType: string, field: string?, value: string?)

Extends Query

Parameters
queryType (string)
field (string?) The document field to query against
value (string?) The query string
Instance Members
field(field)
value(queryVal)
toJSON()
caseInsensitive(value)

The term query finds documents that contain the exact term specified in the inverted index.

Elasticsearch reference

new TermQuery(field: string?, queryVal: (string | number | boolean)?)

Extends ValueTermQueryBase

Parameters
field (string?)
queryVal ((string | number | boolean)?)
Example
const termQry = esb.termQuery('user', 'Kimchy');

Filters documents that have fields that match any of the provided terms (not analyzed).

Elasticsearch reference

new TermsQuery(field: string?, values: (Array | string | number | boolean)?)

Extends Query

Parameters
field (string?)
values ((Array | string | number | boolean)?)
Example
const qry = esb.constantScoreQuery(
    esb.termsQuery('user', ['kimchy', 'elasticsearch'])
);
const qry = esb.termsQuery('user')
    .index('users')
    .type('user')
    .id(2)
    .path('followers');
Instance Members
field(field)
value(value)
values(values)
termsLookup(lookupOpts)
index(idx)
type(type)
id(id)
path(path)
routing(routing)
toJSON()

Returns any documents that match with at least one or more of the provided terms. The terms are not analyzed and thus must match exactly. The number of terms that must match varies per document and is either controlled by a minimum should match field or computed per document in a minimum should match script.

Elasticsearch reference

NOTE: This query was added in elasticsearch v6.1.

new TermsSetQuery(field: string?, terms: (Array<(string | number | boolean)> | string | number)?)

Extends Query

Parameters
field (string?)
terms ((Array<(string | number | boolean)> | string | number)?)
Example
const qry = esb.termsSetQuery('codes', ['abc', 'def', 'ghi'])
    .minimumShouldMatchField('required_matches')
Instance Members
field(field)
term(term)
terms(terms)
minimumShouldMatchField(fieldName)
minimumShouldMatchScript(script)
toJSON()

Interface-like class used to group and identify various implementations of multi term queries:

  • Wildcard Query
  • Fuzzy Query
  • Prefix Query
  • Range Query
  • Regexp Query

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new MultiTermQueryBase()

Extends ValueTermQueryBase

Matches documents with fields that have terms within a certain range.

Elasticsearch reference

new RangeQuery(field: string?)

Extends MultiTermQueryBase

Parameters
field (string?)
Example
const qry = esb.rangeQuery('age')
    .gte(10)
    .lte(20)
    .boost(2.0);
const qry = esb.rangeQuery('date').gte('now-1d/d').lt('now/d');
Instance Members
value()
gte(val)
lte(val)
gt(val)
lt(val)
from(val)
to(val)
includeLower(enable)
includeUpper(enable)
timeZone(zone)
format(fmt)
relation(relation)
toJSON()

Returns documents that have at least one non-null value in the original field

Elasticsearch reference

new ExistsQuery(field: string?)

Extends Query

Parameters
field (string?)
Example
const qry = esb.existsQuery('user');
const qry = esb.boolQuery().mustNot(esb.existsQuery('user'));
Instance Members
field(field)

Matches documents that have fields containing terms with a specified prefix (not analyzed).

Elasticsearch reference

new PrefixQuery(field: string?, value: (string | number)?)

Extends MultiTermQueryBase

Parameters
field (string?)
value ((string | number)?)
Example
const qry = esb.prefixQuery('user', 'ki').boost(2.0);
Instance Members
rewrite(method)

Matches documents that have fields matching a wildcard expression (not analyzed).

Elasticsearch reference

new WildcardQuery(field: string?, value: string?)

Extends MultiTermQueryBase

Parameters
field (string?)
value (string?)
Example
const qry = esb.wildcardQuery('user', 'ki*y').boost(2.0);
Instance Members
caseInsensitive(caseInsensitive)
rewrite(method)

Query for regular expression term queries. Elasticsearch will apply the regexp to the terms produced by the tokenizer for that field, and not to the original text of the field.

Elasticsearch reference

new RegexpQuery(field: string?, value: (string | number)?)

Extends MultiTermQueryBase

Parameters
field (string?)
value ((string | number)?)
Example
const qry = esb.regexpQuery('name.first', 's.*y').boost(1.2);
Instance Members
flags(flags)
caseInsensitive(caseInsensitive)
maxDeterminizedStates(limit)
rewrite(method)

The fuzzy query generates all possible matching terms that are within the maximum edit distance specified in fuzziness and then checks the term dictionary to find out which of those generated terms actually exist in the index.

The fuzzy query uses similarity based on Levenshtein edit distance.

Elasticsearch reference

new FuzzyQuery(field: string?, value: (string | number)?)

Extends MultiTermQueryBase

Parameters
field (string?)
value ((string | number)?)
Example
const qry = esb.fuzzyQuery('user', 'ki');
// More advanced settings
const qry = esb.fuzzyQuery('user', 'ki')
    .fuzziness(2)
    .prefixLength(0)
    .maxExpansions(100)
    .boost(1.0);
Instance Members
fuzziness(factor)
prefixLength(len)
maxExpansions(limit)
transpositions(enable)

Filters documents matching the provided document / mapping type.

Elasticsearch reference

new TypeQuery(type: string?)

Extends Query

Parameters
type (string?) The elasticsearch doc type
Example
const qry = esb.typeQuery('my_type');
Instance Members
value(type)
type(type)

Filters documents that only have the provided ids. Note, this query uses the _uid field.

Elasticsearch reference

new IdsQuery(type: (Array | string)?, ids: Array?)

Extends Query

Parameters
type ((Array | string)?) The elasticsearch doc type
ids (Array?) List of ids to fiter on.
Example
const qry = esb.idsQuery('my_type', ['1', '4', '100']);
Instance Members
type(type)
values(ids)
ids(ids)

Compound Queries

Compound Queries

A query that wraps another query and simply returns a constant score equal to the query boost for every document in the filter. Maps to Lucene ConstantScoreQuery.

Constructs a query where each documents returned by the internal query or filter have a constant score equal to the boost factor.

Elasticsearch reference

new ConstantScoreQuery(filterQuery: Query?)

Extends Query

Parameters
filterQuery (Query?) Query to filter on.
Example
const qry = esb.constantScoreQuery(esb.termQuery('user', 'kimchy')).boost(1.2);
Instance Members
filter(filterQuery)
query(filterQuery)

A query that matches documents matching boolean combinations of other queries. The bool query maps to Lucene BooleanQuery. It is built using one or more boolean clauses, each clause with a typed occurrence.

Elasticsearch reference

new BoolQuery()

Extends Query

Example
const qry = esb.boolQuery()
    .must(esb.termQuery('user', 'kimchy'))
    .filter(esb.termQuery('tag', 'tech'))
    .mustNot(esb.rangeQuery('age').gte(10).lte(20))
    .should([
        esb.termQuery('tag', 'wow'),
        esb.termQuery('tag', 'elasticsearch')
    ])
    .minimumShouldMatch(1)
    .boost(1.0);
Instance Members
must(queries)
filter(queries)
mustNot(queries)
should(queries)
disableCoord(enable)
minimumShouldMatch(minimumShouldMatch)
adjustPureNegative(enable)
toJSON()

A query that generates the union of documents produced by its subqueries, and that scores each document with the maximum score for that document as produced by any subquery, plus a tie breaking increment for any additional matching subqueries.

Elasticsearch reference

new DisMaxQuery()

Extends Query

Example
const qry = esb.disMaxQuery()
    .queries([esb.termQuery('age', 34), esb.termQuery('age', 35)])
    .tieBreaker(0.7)
    .boost(1.2);
const qry = esb.disMaxQuery()
    .queries([
        esb.matchQuery('subject', 'brown fox'),
        esb.matchQuery('message', 'brown fox')
    ])
    .tieBreaker(0.3);
Instance Members
tieBreaker(factor)
queries(queries)

The function_score allows you to modify the score of documents that are retrieved by a query. This can be useful if, for example, a score function is computationally expensive and it is sufficient to compute the score on a filtered set of documents.

Elasticsearch reference

new FunctionScoreQuery()

Extends Query

Example
// `function_score` with only one function
const qry = esb.functionScoreQuery()
    .query(esb.matchAllQuery())
    .function(esb.randomScoreFunction())
    .boostMode('multiply')
    .boost('5');
// Several functions combined
const qry = esb.functionScoreQuery()
    .query(esb.matchAllQuery())
    .functions([
        esb.randomScoreFunction()
            .filter(esb.matchQuery('test', 'bar'))
            .weight(23),
        esb.weightScoreFunction()
            .filter(esb.matchQuery('test', 'cat'))
            .weight(42)
    ])
    .maxBoost(42)
    .scoreMode('max')
    .boostMode('multiply')
    .minScore(42)
    .boost('5');
// Combine decay functions
const qry = esb.functionScoreQuery()
    .functions([
        esb.decayScoreFunction('gauss', 'price').origin('0').scale('20'),
        esb.decayScoreFunction('gauss', 'location')
            .origin('11, 12')
            .scale('2km')
    ])
    .query(esb.matchQuery('properties', 'balcony'))
    .scoreMode('multiply');
Instance Members
query(query)
scoreMode(mode)
boostMode(mode)
maxBoost(limit)
minScore(limit)
function(func)
functions(funcs)

The boosting query can be used to effectively demote results that match a given query. Unlike the "NOT" clause in bool query, this still selects documents that contain undesirable terms, but reduces their overall score.

Elasticsearch reference

new BoostingQuery(positiveQry: Query?, negativeQry: Query?, negativeBoost: number?)

Extends Query

Parameters
positiveQry (Query?) A valid Query object.
negativeQry (Query?) A valid Query object.
negativeBoost (number?) A positive double value where 0 < n < 1 .
Example
const qry = esb.boostingQuery(
    esb.termQuery('field1', 'value1'), // positiveQry
    esb.termQuery('field2', 'value2'), // negativeQry
    0.2 // negativeBoost
);
Instance Members
positive(query)
negative(query)
negativeBoost(factor)

Joining Queries

Joining Queries

The JoiningQueryBase class provides support for common options used across various joining query implementations.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new JoiningQueryBase(queryType: string, refUrl: string, qry: Query?)

Extends Query

Parameters
queryType (string)
refUrl (string)
qry (Query?) A valid Query object
Instance Members
query(qry)
scoreMode(mode)
ignoreUnmapped(enable)
innerHits(innerHits)

Nested query allows to query nested objects. The query is executed against the nested objects / docs as if they were indexed as separate docs (they are, internally) and resulting in the root parent doc (or parent nested mapping).

Elasticsearch reference

new NestedQuery(qry: Query?, path: string?)

Extends JoiningQueryBase

Parameters
qry (Query?) A valid Query object
path (string?) The nested object path.
Example
const qry = esb.nestedQuery()
    .path('obj1')
    .scoreMode('avg')
    .query(
        esb.boolQuery().must([
            esb.matchQuery('obj1.name', 'blue'),
            esb.rangeQuery('obj1.count').gt(5)
        ])
    );
Instance Members
path(path)

The has_child filter accepts a query and the child type to run against, and results in parent documents that have child docs matching the query.

Elasticsearch reference

new HasChildQuery(qry: Query?, type: string?)

Extends JoiningQueryBase

Parameters
qry (Query?) A valid Query object
type (string?) The child type
Example
// Scoring support
const qry = esb.hasChildQuery(
    esb.termQuery('tag', 'something'),
    'blog_tag'
).scoreMode('min');
// Sort by child documents' `click_count` field
const qry = esb.hasChildQuery()
    .query(
        esb.functionScoreQuery().function(
            esb.scriptScoreFunction("_score * doc['click_count'].value")
        )
    )
    .type('blog_tag')
    .scoreMode('max');
Instance Members
type(type)
childType(type)
minChildren(limit)
maxChildren(limit)

The has_parent query accepts a query and a parent type. The query is executed in the parent document space, which is specified by the parent type. This query returns child documents which associated parents have matched.

Elasticsearch reference

new HasParentQuery(qry: Query?, type: string?)

Extends JoiningQueryBase

Parameters
qry (Query?) A valid Query object
type (string?) The parent type
Example
const qry = esb.hasParentQuery(esb.termQuery('tag', 'something'), 'blog');
// Sorting tags by parent documents' `view_count` field
const qry = esb.hasParentQuery()
    .parentType('blog')
    .score(true)
    .query(
        esb.functionScoreQuery().function(
            esb.scriptScoreFunction("_score * doc['view_count'].value")
        )
    );
Instance Members
scoreMode()
type(type)
parentType(type)
score(enable)

The parent_id query can be used to find child documents which belong to a particular parent.

Elasticsearch reference

new ParentIdQuery(type: string?, id: (string | number)?)

Extends Query

Parameters
type (string?) The child type. This must be a type with _parent field.
id ((string | number)?) The required parent id select documents must refer to.
Example
const qry = esb.parentIdQuery('blog_tag', 1);
Instance Members
type(type)
id(id)
ignoreUnmapped(enable)

Geo Queries

Geo Queries

The GeoQueryBase provides support for common options used across various geo query implementations.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new GeoQueryBase(queryType: string, field: string?)

Extends Query

Parameters
queryType (string)
field (string?)
Instance Members
field(field)
validationMethod(method)
toJSON()

Filter documents indexed using the geo_shape type. Requires the geo_shape Mapping.

The geo_shape query uses the same grid square representation as the geo_shape mapping to find documents that have a shape that intersects with the query shape. It will also use the same PrefixTree configuration as defined for the field mapping.

The query supports two ways of defining the query shape, either by providing a whole shape definition, or by referencing the name of a shape pre-indexed in another index.

Elasticsearch reference

new GeoShapeQuery(field: string?)

Extends GeoQueryBase

Parameters
field (string?)
Example
const geoQry = esb.geoShapeQuery('location')
    .shape(esb.geoShape()
        .type('envelope')
        .coordinates([[13.0, 53.0], [14.0, 52.0]]))
    .relation('within');
// Pre-indexed shape
const geoQry = esb.geoShapeQuery()
    .field('location')
    .indexedShape(esb.indexedShape()
        .id('DEU')
        .type('countries')
        .index('shapes')
        .path('location'))
Instance Members
validationMethod()
shape(shape)
indexedShape(shape)
relation(relation)
ignoreUnmapped(enable)

A query allowing to filter hits based on a point location using a bounding box.

Elasticsearch reference

new GeoBoundingBoxQuery(field: string?)

Extends GeoQueryBase

Parameters
field (string?)
Example
// Format of point in Geohash
const qry = esb.geoBoundingBoxQuery('pin.location')
    .topLeft(esb.geoPoint().string('dr5r9ydj2y73'))
    .bottomRight(esb.geoPoint().string('drj7teegpus6'));
// Format of point with lat lon as properties
const qry = esb.geoBoundingBoxQuery()
    .field('pin.location')
    .topLeft(esb.geoPoint()
        .lat(40.73)
        .lon(-74.1))
    .bottomRight(esb.geoPoint()
        .lat(40.10)
        .lon(-71.12));
// Set bounding box values separately
const qry = esb.geoBoundingBoxQuery('pin.location')
    .top(40.73)
    .left(-74.1)
    .bottom(40.01)
    .right(-71.12);
Instance Members
topLeft(point)
bottomRight(point)
topRight(point)
bottomLeft(point)
top(val)
left(val)
bottom(val)
right(val)
type(type)

Filters documents that include only hits that exists within a specific distance from a geo point.

Elasticsearch reference

new GeoDistanceQuery(field: string?, point: GeoPoint?)

Extends GeoQueryBase

Parameters
field (string?)
point (GeoPoint?) Geo point used to measure and filter documents based on distance from it.
Example
const qry = esb.geoDistanceQuery('pin.location', esb.geoPoint().lat(40).lon(-70))
    .distance('12km');

const qry = esb.geoDistanceQuery()
    .field('pin.location')
    .distance('200km')
    .geoPoint(esb.geoPoint().lat(40).lon(-70));
Instance Members
distance(distance)
distanceType(type)
geoPoint(point)

A query allowing to include hits that only fall within a polygon of points.

Elasticsearch reference

new GeoPolygonQuery(field: string?)

Extends GeoQueryBase

Parameters
field (string?)
Example
const geoQry = esb.geoPolygonQuery('person.location')
    .points([
        {"lat" : 40, "lon" : -70},
        {"lat" : 30, "lon" : -80},
        {"lat" : 20, "lon" : -90}
    ]);
Instance Members
points(points)

Specialized Queries

Specialized Queries

The More Like This Query (MLT Query) finds documents that are "like" a given set of documents. In order to do so, MLT selects a set of representative terms of these input documents, forms a query using these terms, executes the query and returns the results. The user controls the input documents, how the terms should be selected and how the query is formed.

Elasticsearch reference

new MoreLikeThisQuery()

Extends Query

Example
// Ask for documents that are similar to a provided piece of text
const qry = esb.moreLikeThisQuery()
    .fields(['title', 'description'])
    .like('Once upon a time')
    .minTermFreq(1)
    .maxQueryTerms(12);
// Mixing texts with documents already existing in the index
const qry = esb.moreLikeThisQuery()
    .fields(['title', 'description'])
    .like({ _index: 'imdb', _type: 'movies', _id: '1' })
    .like({ _index: 'imdb', _type: 'movies', _id: '2' })
    .like('and potentially some more text here as well')
    .minTermFreq(1)
    .maxQueryTerms(12);
// Provide documents not present in the index
const qry = esb.moreLikeThisQuery()
    .fields(['name.first', 'name.last'])
    .like([
        {
            _index: 'marvel',
            _type: 'quotes',
            doc: {
                name: { first: 'Ben', last: 'Grimm' },
                tweet: "You got no idea what I'd... what I'd give to be invisible."
            }
        },
        { _index: 'marvel', _type: 'quotes', _id: '2' }
    ])
    .minTermFreq(1)
    .maxQueryTerms(12);
Instance Members
fields(fields)
like(like)
unlike(unlike)
likeText(txt)
ids(ids)
docs(docs)
maxQueryTerms(termsLimit)
minTermFreq(termFreqLimit)
minDocFreq(docFreqLimit)
maxDocFreq(docFreqLimit)
minWordLength(wordLenLimit)
maxWordLength(wordLenLimit)
stopWords(words)
analyzer(analyzer)
minimumShouldMatch(minimumShouldMatch)
boostTerms(boost)
include(enable)

A query allowing to define scripts as queries. They are typically used in a filter context.

Elasticsearch reference

new ScriptQuery(script: Script?)

Extends Query

Parameters
script (Script?)
Example
const scriptQry = esb.scriptQuery(esb.script()
 .lang('painless')
 .inline("doc['num1'].value > 1"))

// Use in filter context
const qry = esb.boolQuery().must(scriptQry);
Instance Members
script(script)

The percolate query can be used to match queries stored in an index. The percolate query itself contains the document that will be used as query to match with the stored queries.

Elasticsearch reference

new PercolateQuery(field: string?, docType: string?)

Extends Query

Parameters
field (string?) The field of type percolator and that holds the indexed queries.
docType (string?) The type / mapping of the document being percolated.
Example
const percolateQry = esb.percolateQuery('query', 'doctype')
    .document({ message: 'A new bonsai tree in the office' });

const percolateQry = esb.percolateQuery()
    .field('query')
    .documentType('doctype')
    .index('my-index')
    .type('message')
    .id('1')
    .version(1);
Instance Members
field(field)
documentType(docType)
document(doc)
documents(docs)
index(index)
type(type)
id(id)
routing(routing)
preference(preference)
version(version)

Span Queries

Span Queries

Interface-like class used to group and identify various implementations of Span queries.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new SpanQueryBase()

Extends Query

Matches spans containing a term. The span term query maps to Lucene SpanTermQuery.

Elasticsearch reference

new SpanTermQuery(field: string?, value: (string | number)?)

Extends SpanQueryBase

Parameters
field (string?) The document field to query against
value ((string | number)?) The query string
Example
const qry = esb.spanTermQuery('user', 'kimchy');
const qry = esb.spanTermQuery()
    .field('user')
    .value('kimchy')
    .boost(2.0);
Instance Members
field(field)
value(queryVal)
toJSON()

The span_multi query allows you to wrap a multi term query (one of wildcard, fuzzy, prefix, range or regexp query) as a span query, so it can be nested.

Elasticsearch reference

new SpanMultiTermQuery(multiTermQry: MultiTermQueryBase?)

Extends SpanQueryBase

Parameters
multiTermQry (MultiTermQueryBase?) One of wildcard, fuzzy, prefix, range or regexp query
Example
const spanQry = esb.spanMultiTermQuery()
    .match(esb.prefixQuery('user', 'ki').boost(1.08));
Instance Members
match(multiTermQry)

Matches spans near the beginning of a field. The span first query maps to Lucene SpanFirstQuery.

Elasticsearch reference

new SpanFirstQuery(spanQry: SpanQueryBase?)

Extends SpanQueryBase

Parameters
spanQry (SpanQueryBase?) Any other span type query
Example
const spanQry = esb.spanFirstQuery()
    .match(esb.spanTermQuery('user', 'kimchy'))
    .end(3);
Instance Members
match(spanQry)
end(limit)

Matches spans which are near one another. One can specify slop, the maximum number of intervening unmatched positions, as well as whether matches are required to be in-order. The span near query maps to Lucene SpanNearQuery.

Elasticsearch reference

new SpanNearQuery()

Extends SpanQueryBase

Example
const spanQry = esb.spanNearQuery()
    .clauses([
        esb.spanTermQuery('field', 'value1'),
        esb.spanTermQuery('field', 'value2'),
        esb.spanTermQuery('field', 'value3')
    ])
    .slop(12)
    .inOrder(false);
Instance Members
clauses(clauses)
slop(slop)
inOrder(enable)

Matches the union of its span clauses. The span or query maps to Lucene SpanOrQuery.

Elasticsearch reference

new SpanOrQuery()

Extends SpanQueryBase

Example
const spanQry = esb.spanOrQuery()
    .clauses([
        esb.spanTermQuery('field', 'value1'),
        esb.spanTermQuery('field', 'value2'),
        esb.spanTermQuery('field', 'value3')
    ]);
Instance Members
clauses(clauses)

Removes matches which overlap with another span query. The span not query maps to Lucene SpanNotQuery.

Elasticsearch reference

new SpanNotQuery()

Extends SpanQueryBase

Example
const spanQry = esb.spanNotQuery()
    .include(esb.spanTermQuery('field1', 'hoya'))
    .exclude(esb.spanNearQuery()
        .clauses([
            esb.spanTermQuery('field1', 'la'),
            esb.spanTermQuery('field1', 'hoya')
        ])
        .slop(0)
        .inOrder(true));
Instance Members
include(spanQry)
exclude(spanQry)
pre(pre)
post(post)
dist(dist)

Base class for span queries with little, big clauses.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new SpanLittleBigQueryBase()

Extends SpanQueryBase

Instance Members
little(spanQry)
big(spanQry)

Returns matches which enclose another span query. The span containing query maps to Lucene SpanContainingQuery.

Matching spans from big that contain matches from little are returned.

Elasticsearch reference

new SpanContainingQuery()

Extends SpanLittleBigQueryBase

Example
const spanQry = esb.spanContainingQuery()
    .little(esb.spanTermQuery('field1', 'foo'))
    .big(esb.spanNearQuery()
        .clauses([
            esb.spanTermQuery('field1', 'bar'),
            esb.spanTermQuery('field1', 'baz')
        ])
        .slop(5)
        .inOrder(true))

Returns matches which are enclosed inside another span query. The span within query maps to Lucene SpanWithinQuery.

Matching spans from little that are enclosed within big are returned.

Elasticsearch reference

new SpanWithinQuery()

Extends SpanLittleBigQueryBase

Example
const spanQry = esb.spanWithinQuery()
    .little(esb.spanTermQuery('field1', 'foo'))
    .big(esb.spanNearQuery()
        .clauses([
            esb.spanTermQuery('field1', 'bar'),
            esb.spanTermQuery('field1', 'baz')
        ])
        .slop(5)
        .inOrder(true));

Wrapper to allow span queries to participate in composite single-field span queries by lying about their search field. The span field masking query maps to Lucene's SpanFieldMaskingQuery.

This can be used to support queries like span-near or span-or across different fields, which is not ordinarily permitted.

Span field masking query is invaluable in conjunction with multi-fields when same content is indexed with multiple analyzers. For instance we could index a field with the standard analyzer which breaks text up into words, and again with the english analyzer which stems words into their root form.

Elasticsearch reference

new SpanFieldMaskingQuery(field: string?, spanQry: SpanQueryBase?)

Extends SpanQueryBase

Parameters
field (string?)
spanQry (SpanQueryBase?) Any other span type query
Example
const spanQry = esb.spanNearQuery()
    .clauses([
        esb.spanTermQuery('text', 'quick brown'),
        esb.spanFieldMaskingQuery()
            .field('text')
            .query(esb.spanTermQuery('text.stems', 'fox'))
    ])
    .slop(5)
    .inOrder(false);
Instance Members
query(spanQry)
field(field)

Aggregations

These classes can be used to leverage the aggregations framework which helps provide aggregated data based on a search query. They can be composed together with queries and other aggregations in order to build complex summaries of the data.

Aggregations

These classes can be used to leverage the aggregations framework which helps provide aggregated data based on a search query. They can be composed together with queries and other aggregations in order to build complex summaries of the data.

Base class implementation for all aggregation types.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class should be extended and used, as validation against the class type is present in various places.

new Aggregation(name: string, aggType: string)
Parameters
name (string)
aggType (string) Type of aggregation
Throws
  • Error: if name is empty
  • Error: if aggType is empty
Instance Members
name(name)
aggregation(agg)
agg(agg)
aggregations(aggs)
aggs(aggs)
meta(meta)
getDSL()
toJSON()

Metrics Aggregations

Metrics Aggregations

The MetricsAggregationBase provides support for common options used across various metrics Aggregation implementations.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new MetricsAggregationBase(name: string, aggType: string, field: string?)

Extends Aggregation

Parameters
name (string) a valid aggregation name
aggType (string) type of aggregation
field (string?) The field to aggregate on
Instance Members
field(field)
script(script)
missing(value)
format(fmt)

A single-value metrics aggregation that computes the average of numeric values that are extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script.

Elasticsearch reference

Aggregation that computes the average of numeric values that are extracted from the aggregated documents.

new AvgAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
// Compute the average grade over all documents
const agg = esb.avgAggregation('avg_grade', 'grade');
// Compute the average grade based on a script
const agg = esb.avgAggregation('avg_grade').script(
    esb.script('inline', "doc['grade'].value").lang('painless')
);
// Value script, apply grade correction
const agg = esb.avgAggregation('avg_grade', 'grade').script(
    esb.script('inline', '_value * params.correction')
        .lang('painless')
        .params({ correction: 1.2 })
);
// Missing value
const agg = esb.avgAggregation('avg_grade', 'grade').missing(10);

A single-value metrics aggregation that calculates an approximate count of distinct values. Values can be extracted either from specific fields in the document or generated by a script.

Elasticsearch reference

Aggregation that calculates an approximate count of distinct values.

new CardinalityAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.cardinalityAggregation('author_count', 'author');
const agg = esb.cardinalityAggregation('author_count').script(
    esb.script(
        'inline',
        "doc['author.first_name'].value + ' ' + doc['author.last_name'].value"
    ).lang('painless')
);
Instance Members
format()
precisionThreshold(threshold)

A multi-value metrics aggregation that computes stats over numeric values extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script.

Elasticsearch reference

Aggregation that computes extra stats over numeric values extracted from the aggregated documents.

new ExtendedStatsAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.extendedStatsAggregation('grades_stats', 'grade');
// Compute the grade stats based on a script
const agg = esb.extendedStatsAggregation('grades_stats').script(
    esb.script('inline', "doc['grade'].value").lang('painless')
);
// Value script, apply grade correction
const agg = esb.extendedStatsAggregation('grades_stats', 'grade').script(
    esb.script('inline', '_value * params.correction')
        .lang('painless')
        .params({ correction: 1.2 })
);
// Missing value
const agg = esb.extendedStatsAggregation('grades_stats', 'grade').missing(0);
Instance Members
sigma(sigma)

A metric aggregation that computes the bounding box containing all geo_point values for a field.

Elasticsearch reference

new GeoBoundsAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.geoBoundsAggregation('viewport', 'location').wrapLongitude(true);
Instance Members
format()
script()
wrapLongitude(allowOverlap)

A metric aggregation that computes the weighted centroid from all coordinate values for a Geo-point datatype field.

Elasticsearchreference

new GeoCentroidAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on. field must be a Geo-point datatype type
Example
const agg = esb.geoCentroidAggregation('centroid', 'location');
// Combined as a sub-aggregation to other bucket aggregations
const reqBody = esb.requestBodySearch()
    .query(esb.matchQuery('crime', 'burglary'))
    .agg(
        esb.termsAggregation('towns', 'town').agg(
            esb.geoCentroidAggregation('centroid', 'location')
        )
    );
Instance Members
format()

A single-value metrics aggregation that keeps track and returns the maximum value among the numeric values extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script.

Elasticsearch reference

Aggregation that keeps track and returns the maximum value among the numeric values extracted from the aggregated documents.

new MaxAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.maxAggregation('max_price', 'price');
// Use a file script
const agg = esb.maxAggregation('max_price').script(
    esb.script('file', 'my_script').params({ field: 'price' })
);
// Value script to apply the conversion rate to every value
// before it is aggregated
const agg = esb.maxAggregation('max_price').script(
    esb.script('inline', '_value * params.conversion_rate').params({
        conversion_rate: 1.2
    })
);

A single-value metrics aggregation that keeps track and returns the minimum value among the numeric values extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script.

Elasticsearch reference

Aggregation that keeps track and returns the minimum value among numeric values extracted from the aggregated documents.

new MinAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.minAggregation('min_price', 'price');
// Use a file script
const agg = esb.minAggregation('min_price').script(
    esb.script('file', 'my_script').params({ field: 'price' })
);
// Value script to apply the conversion rate to every value
// before it is aggregated
const agg = esb.minAggregation('min_price').script(
    esb.script('inline', '_value * params.conversion_rate').params({
        conversion_rate: 1.2
    })
);

A multi-value metrics aggregation that calculates one or more percentiles over numeric values extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script.

Elasticsearch reference

Aggregation that calculates one or more percentiles over numeric values extracted from the aggregated documents.

new PercentilesAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.percentilesAggregation('load_time_outlier', 'load_time');
// Convert load time from mills to seconds on-the-fly using script
const agg = esb.percentilesAggregation('load_time_outlier').script(
    esb.script('inline', "doc['load_time'].value / params.timeUnit")
        .lang('painless')
        .params({ timeUnit: 1000 })
);
Instance Members
keyed(keyed)
percents(percents)
tdigest(compression)
compression(compression)
hdr(numberOfSigDigits)

A multi-value metrics aggregation that calculates one or more percentile ranks over numeric values extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script.

Elasticsearch reference

Aggregation that calculates one or more percentiles ranks over numeric values extracted from the aggregated documents.

new PercentileRanksAggregation(name: string, field: string?, values: Array?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on. It must be a numeric field
values (Array?) Values to compute percentiles from.
Throws
  • TypeError: If values is not an instance of Array
Example
const agg = esb.percentileRanksAggregation(
    'load_time_outlier',
    'load_time',
    [15, 30]
);
// Convert load time from mills to seconds on-the-fly using script
const agg = esb.percentileRanksAggregation('load_time_outlier')
    .values([3, 5])
    .script(
        esb.script('inline', "doc['load_time'].value / params.timeUnit")
            .lang('painless')
            .params({ timeUnit: 1000 })
    );
Instance Members
format()
keyed(keyed)
values(values)
tdigest(compression)
compression(compression)
hdr(numberOfSigDigits)

A metric aggregation that executes using scripts to provide a metric output.

Elasticsearch reference

Aggregation that keeps track and returns the minimum value among numeric values extracted from the aggregated documents.

new ScriptedMetricAggregation(name: string)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
Example
const agg = esb.scriptedMetricAggregation('profit')
    .initScript('params._agg.transactions = []')
    .mapScript(
        "params._agg.transactions.add(doc.type.value == 'sale' ? doc.amount.value : -1 * doc.amount.value)"
    )
    .combineScript(
        'double profit = 0; for (t in params._agg.transactions) { profit += t } return profit'
    )
    .reduceScript(
        'double profit = 0; for (a in params._aggs) { profit += a } return profit'
    );
// Specify using file scripts
const agg = esb.scriptedMetricAggregation('profit')
    .initScript(esb.script('file', 'my_init_script'))
    .mapScript(esb.script('file', 'my_map_script'))
    .combineScript(esb.script('file', 'my_combine_script'))
    // script parameters for `init`, `map` and `combine` scripts must be
    // specified in a global params object so that
    // it can be shared between the scripts
    .params({ field: 'amount', _agg: {} })
    .reduceScript(esb.script('file', 'my_reduce_script'));
Instance Members
field()
script()
missing()
initScript(initScript)
mapScript(mapScript)
combineScript(combineScript)
reduceScript(reduceScript)
params(params)

A multi-value metrics aggregation that computes stats over numeric values extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script.

The stats that are returned consist of: min, max, sum, count and avg.

Elasticsearch reference

Aggregation that computes stats over numeric values extracted from the aggregated documents.

new StatsAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.statsAggregation('grades_stats', 'grade');
// Use a file script
const agg = esb.statsAggregation('grades_stats').script(
    esb.script('file', 'my_script').params({ field: 'price' })
);
// Value script to apply the conversion rate to every value
// before it is aggregated
const agg = esb.statsAggregation('grades_stats').script(
    esb.script('inline', '_value * params.conversion_rate').params({
        conversion_rate: 1.2
    })
);

A single-value metrics aggregation that sums up numeric values that are extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents, or be generated by a provided script.

Elasticsearch reference

Aggregation that sums up numeric values that are extracted from the aggregated documents.

new SumAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const reqBody = esb.requestBodySearch()
    .query(esb.constantScoreQuery(esb.matchQuery('type', 'hat')))
    .agg(esb.sumAggregation('hat_prices', 'price'));
// Script to fetch the sales price
const reqBody = esb.requestBodySearch()
    .query(esb.constantScoreQuery(esb.matchQuery('type', 'hat')))
    .agg(
        esb.sumAggregation('hat_prices').script(
            esb.script('inline', 'doc.price.value')
        )
    );
// Access the field value from the script using `_value`
const reqBody = esb.requestBodySearch()
    .query(esb.constantScoreQuery(esb.matchQuery('type', 'hat')))
    .agg(
        esb.sumAggregation('square_hats', 'price').script(
            esb.script('inline', '_value * _value')
        )
    );
// Treat documents missing price as if they had a value
const reqBody = esb.requestBodySearch()
    .query(esb.constantScoreQuery(esb.matchQuery('type', 'hat')))
    .agg(esb.sumAggregation('hat_prices', 'price').missing(100));

A top_hits metric aggregator keeps track of the most relevant document being aggregated. This aggregator is intended to be used as a sub aggregator, so that the top matching documents can be aggregated per bucket.

Elasticsearch reference

top_hits metric aggregator keeps track of the most relevant document being aggregated.

new TopHitsAggregation(name: string)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.termsAggregation('top_tags', 'type')
            .size(3)
            .agg(
                esb.topHitsAggregation('top_sales_hits')
                    .sort(esb.sort('date', 'desc'))
                    .source({ includes: ['date', 'price'] })
                    .size(1)
            )
    )
    .size(0);
// Field collapsing(logically groups a result set into
// groups and per group returns top documents)
const reqBody = esb.requestBodySearch()
    .query(esb.matchQuery('body', 'elections'))
    .agg(
        esb.termsAggregation('top-sites', 'domain')
            .order('top_hit', 'desc')
            .agg(esb.topHitsAggregation('top_tags_hits'))
            .agg(
                esb.maxAggregation('top_hit').script(
                    esb.script('inline', '_score')
                )
            )
    );
Instance Members
field()
script()
missing()
format()
from(from)
size(size)
sort(sort)
sorts(sorts)
trackScores(trackScores)
version(version)
explain(explain)
highlight(highlight)
source(source)
storedFields(fields)
scriptField(scriptFieldName, script)
scriptFields(scriptFields)
docvalueFields(fields)

A single-value metrics aggregation that counts the number of values that are extracted from the aggregated documents. These values can be extracted either from specific fields in the documents, or be generated by a provided script. Typically, this aggregator will be used in conjunction with other single-value aggregations.

Elasticsearch reference

Aggregation that counts the number of values that are extracted from the aggregated documents.

new ValueCountAggregation(name: string, field: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.valueCountAggregation('types_count', 'type');
const agg = esb.valueCountAggregation('types_count').script(
    esb.script('inline', "doc['type'].value")
);
Instance Members
format()

Bucket Aggregations

Bucket Aggregations

The BucketAggregationBase provides support for common options used across various bucket Aggregation implementations.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new BucketAggregationBase(name: string, aggType: string, field: string?)

Extends Aggregation

Parameters
name (string) a valid aggregation name
aggType (string) type of aggregation
field (string?) The field to aggregate on
Instance Members
field(field)
script(script)

A bucket aggregation returning a form of adjacency matrix. The request provides a collection of named filter expressions, similar to the filters aggregation request. Each bucket in the response represents a non-empty cell in the matrix of intersecting filters.

Elasticsearch reference

new AdjacencyMatrixAggregation(name: string)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
Example
const agg = esb.adjacencyMatrixAggregation('interactions').filters({
    grpA: esb.termsQuery('accounts', ['hillary', 'sidney']),
    grpB: esb.termsQuery('accounts', ['donald', 'mitt']),
    grpC: esb.termsQuery('accounts', ['vladimir', 'nigel'])
});
Instance Members
field()
script()
filter(filterName, filterQuery)
filters(filterQueries)
separator(sep)

A multi-bucket aggregation similar to the Date histogram aggregation except instead of providing an interval to use as the width of each bucket, a target number of buckets is provided indicating the number of buckets needed and the interval of the buckets is automatically chosen to best achieve that target. The number of buckets returned will always be less than or equal to this target number.

Elasticsearch reference

new AutoDateHistogramAggregation(name: string, field: string, buckets: number)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string) The field to aggregate on
buckets (number) Bucket count to generate histogram over.
Example
const agg = esb.autoDateHistogramAggregation('sales_over_time', 'date', 15);
Instance Members
buckets(buckets)
minimumInterval(interval)
format(fmt)
missing(value)
timeZone(tz)

A special single bucket aggregation that enables aggregating from buckets on parent document types to buckets on child documents.

This aggregation relies on the _parent field in the mapping.

Elasticsearch reference

new ChildrenAggregation(name: string)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.termsAggregation('top-tags', 'tags.keyword')
            .size(10)
            .agg(
                esb.childrenAggregation('to-answers')
                    .type('answer')
                    .agg(
                        esb.termsAggregation(
                            'top-names',
                            'owner.display_name.keyword'
                        ).size(10)
                    )
            )
    )
    .size(0);
Instance Members
field()
script()
type(type)

CompositeAggregation is a multi-bucket values source based aggregation that can be used to calculate unique composite values from source documents.

Unlike the other multi-bucket aggregation the composite aggregation can be used to paginate all buckets from a multi-level aggregation efficiently. This aggregation provides a way to stream all buckets of a specific aggregation similarly to what scroll does for documents.

Elasticsearch reference

new CompositeAggregation(name: string)

Extends Aggregation

Parameters
name (string) a valid aggregation name
Example
const reqBody = esb.requestBodySearch()
  .agg(
    esb.compositeAggregation('my_buckets')
      .sources(
        esb.CompositeAggregation.termsValuesSource('product', 'product')
      )
  )

NOTE: This query was added in elasticsearch v6.1.
Instance Members
sources(sources)
size(size)
after(afterKey)

Values Source

The sources parameter controls the sources that should be used to build the composite buckets. There are three different types of values source:

Values Source

The sources parameter controls the sources that should be used to build the composite buckets. There are three different types of values source:

Base class implementation for all Composite Aggregation values sources.

NOTE: Instantiating this directly should not be required.

new ValuesSourceBase(valueSrcType: string, refUrl: string, name: string, field: string?)
Parameters
valueSrcType (string) Type of value source
refUrl (string) Elasticsearch reference URL
name (string)
field (string?) The field to aggregate on
Throws
  • Error: if name is empty
  • Error: if valueSrcType is empty
Instance Members
field(field)
script(script)
valueType(valueType)
order(order)
missing(value)
missingBucket(value)
toJSON()

TermsValuesSource is a source for the CompositeAggregation that handles terms. It works very similar to a terms aggregation with a slightly different syntax.

Elasticsearch reference

new TermsValuesSource(name: string, field: string?)

Extends ValuesSourceBase

Parameters
name (string)
field (string?) The field to aggregate on
Example
const valueSrc = esb.CompositeAggregation.termsValuesSource('product').script({
  source: "doc['product'].value",
  lang: 'painless'
});

HistogramValuesSource is a source for the CompositeAggregation that handles histograms. It works very similar to a histogram aggregation with a slightly different syntax.

Elasticsearch reference

new HistogramValuesSource(name: string, field: string?, interval: number?)

Extends ValuesSourceBase

Parameters
name (string)
field (string?) The field to aggregate on
interval (number?) Interval to generate histogram over.
Example
const valueSrc = esb.CompositeAggregation.histogramValuesSource(
  'histo', // name
  'price', // field
  5 // interval
);
Instance Members
interval(interval)

DateHistogramValuesSource is a source for the CompositeAggregation that handles date histograms. It works very similar to a histogram aggregation with a slightly different syntax.

Elasticsearch reference

new DateHistogramValuesSource(name: string, field: string?, interval: (string | number)?)

Extends ValuesSourceBase

Parameters
name (string)
field (string?) The field to aggregate on
interval ((string | number)?) Interval to generate histogram over.
Example
const valueSrc = esb.CompositeAggregation.dateHistogramValuesSource(
  'date', // name
  'timestamp', // field
  '1d' // interval
);
Instance Members
interval(interval)
calendarInterval(interval)
fixedInterval(interval)
timeZone(tz)
format(fmt)

The HistogramAggregationBase provides support for common options used across various histogram Aggregation implementations like Histogram Aggregation, Date Histogram aggregation.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new HistogramAggregationBase(name: string, aggType: string, field: string?, interval: (string | number)?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
aggType (string) Type of aggregation
field (string?) The field to aggregate on
interval ((string | number)?) Interval to generate histogram over.
Instance Members
interval(interval)
format(fmt)
offset(offset)
order(key, direction)
minDocCount(minDocCnt)
extendedBounds(min, max)
hardBounds(min, max)
missing(value)
keyed(keyed)

A multi-bucket aggregation similar to the histogram except it can only be applied on date values. The interval can be specified by date/time expressions.

Elasticsearch reference

new DateHistogramAggregation(name: string, field: string?, interval: string?)

Extends HistogramAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
interval (string?) Interval to generate histogram over. Available expressions for interval: year, quarter, month, week, day, hour, minute, second
Example
const agg = esb.dateHistogramAggregation('sales_over_time', 'date', 'month');
const agg = esb.dateHistogramAggregation(
    'sales_over_time',
    'date',
    '1M'
).format('yyyy-MM-dd');
Instance Members
timeZone(tz)
calendarInterval(interval)
fixedInterval(interval)

The RangeAggregationBase provides support for common options used across various range Aggregation implementations like Range Aggregation and Date Range aggregation.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new RangeAggregationBase(name: string, aggType: string, field: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
aggType (string) Type of aggregation
field (string?) The field to aggregate on
Instance Members
format(fmt)
range(range)
ranges(ranges)
missing(value)
keyed(keyed)
toJSON()

A range aggregation that is dedicated for date values. The main difference between this aggregation and the normal range aggregation is that the from and to values can be expressed in Date Math expressions, and it is also possible to specify a date format by which the from and to response fields will be returned.

Elasticsearch reference

new DateRangeAggregation(name: string, field: string?)

Extends RangeAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.dateRangeAggregation('range', 'date')
    .format('MM-yyy')
    .ranges([{ to: 'now-10M/M' }, { from: 'now-10M/M' }]);
Instance Members
timeZone(tz)

A filtering aggregation used to limit any sub aggregations' processing to a sample of the top-scoring documents. Diversity settings are used to limit the number of matches that share a common value such as an "author".

Elasticsearch reference

new DiversifiedSamplerAggregation(name: string, field: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const reqBody = esb.requestBodySearch()
    .query(esb.queryStringQuery('tags:elasticsearch'))
    .agg(
        esb.diversifiedSamplerAggregation('my_unbiased_sample', 'author')
            .shardSize(200)
            .agg(
                esb.significantTermsAggregation(
                    'keywords',
                    'tags'
                ).exclude(['elasticsearch'])
            )
    );
// Use a script to produce a hash of the multiple values in a tags field
// to ensure we don't have a sample that consists of the same repeated
// combinations of tags
const reqBody = esb.requestBodySearch()
    .query(esb.queryStringQuery('tags:kibana'))
    .agg(
        esb.diversifiedSamplerAggregation('my_unbiased_sample')
            .shardSize(200)
            .maxDocsPerValue(3)
            .script(esb.script('inline', "doc['tags'].values.hashCode()"))
            .agg(
                esb.significantTermsAggregation(
                    'keywords',
                    'tags'
                ).exclude(['kibana'])
            )
    );
Instance Members
shardSize(size)
maxDocsPerValue(maxDocsPerValue)
executionHint(hint)

Defines a single bucket of all the documents in the current document set context that match a specified filter. Often this will be used to narrow down the current aggregation context to a specific set of documents.

Elasticsearch reference

new FilterAggregation(name: string, filterQuery: Query?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
filterQuery (Query?) Query to filter on. Example - term query.
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.filterAggregation(
            't_shirts',
            esb.termQuery('type', 't-shirt')
        ).agg(esb.avgAggregation('avg_price', 'price'))
    )
    .size(0);
Instance Members
field()
script()
filter(filterQuery)

Defines a single bucket of all the documents in the current document set context that match a specified filter. Often this will be used to narrow down the current aggregation context to a specific set of documents.

Elasticsearch reference

new FiltersAggregation(name: string)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
Example
const agg = esb.filtersAggregation('messages')
    .filter('errors', esb.matchQuery('body', 'error'))
    .filter('warnings', esb.matchQuery('body', 'warning'));
const agg = esb.filtersAggregation('messages')
    .anonymousFilters([
        esb.matchQuery('body', 'error'),
        esb.matchQuery('body', 'warning')
    ])
Instance Members
field()
script()
filter(bucketName, filterQuery)
filters(filterQueries)
anonymousFilter(filterQuery)
anonymousFilters(filterQueries)
otherBucket(enable, otherBucketKey?)
otherBucketKey(otherBucketKey)

A multi-bucket aggregation that works on geo_point fields and conceptually works very similar to the range aggregation. The user can define a point of origin and a set of distance range buckets. The aggregation evaluate the distance of each document value from the origin point and determines the buckets it belongs to based on the ranges (a document belongs to a bucket if the distance between the document and the origin falls within the distance range of the bucket).

Elasticsearch reference

new GeoDistanceAggregation(name: string, field: string?)

Extends RangeAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.geoDistanceAggregation('rings_around_amsterdam', 'location')
    .origin(esb.geoPoint().string('52.3760, 4.894'))
    .ranges([{ to: 100000 }, { from: 100000, to: 300000 }, { from: 300000 }]);
Instance Members
format()
script()
origin(point)
unit(unit)
distanceType(type)

A multi-bucket aggregation that works on geo_point fields and groups points into buckets that represent cells in a grid. The resulting grid can be sparse and only contains cells that have matching data. Each cell is labeled using a geohash which is of user-definable precision.

Elasticsearch reference

new GeoHashGridAggregation(name: string, field: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.geoHashGridAggregation('large-grid', 'location').precision(3);
Instance Members
format()
script()
precision(precision)
size(size)
shardSize(shardSize)

Defines a single bucket of all the documents within the search execution context. This context is defined by the indices and the document types you’re searching on, but is not influenced by the search query itself.

Elasticsearch reference

new GlobalAggregation(name: string)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
Example
const reqBody = esb.requestBodySearch()
    .query(esb.matchQuery('type', 't-shirt'))
    .agg(
        esb.globalAggregation('all_products').agg(
            esb.avgAggregation('avg_price', 'price')
        )
    )
    .agg(esb.avgAggregation('t_shirts', 'price'));
Instance Members
field()
script()

A multi-bucket values source based aggregation that can be applied on numeric values extracted from the documents. It dynamically builds fixed size (a.k.a. interval) buckets over the values.

Elasticsearch reference

new HistogramAggregation(name: string, field: string?, interval: number?)

Extends HistogramAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
interval (number?) Interval to generate histogram over.
Example
const agg = esb.histogramAggregation('prices', 'price', 50);
const agg = esb.histogramAggregation('prices', 'price', 50).minDocCount(1);
const agg = esb.histogramAggregation('prices', 'price', 50)
    .extendedBounds(0, 500);
const agg = esb.histogramAggregation('quantity', 'quantity', 10).missing(0);

Dedicated range aggregation for IP typed fields.

Elasticsearch reference

new IpRangeAggregation(name: string, field: string?)

Extends RangeAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.ipRangeAggregation('ip_ranges', 'ip').ranges([
    { to: '10.0.0.5' },
    { from: '10.0.0.5' }
]);
const agg = esb.ipRangeAggregation('ip_ranges', 'ip').ranges([
    { mask: '10.0.0.0/25' },
    { mask: '10.0.0.127/25' }
]);
Instance Members
format()

A field data based single bucket aggregation, that creates a bucket of all documents in the current document set context that are missing a field value (effectively, missing a field or having the configured NULL value set).

Elasticsearch reference

new MissingAggregation(name: string, field: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.missingAggregation('products_without_a_price', 'price');
Instance Members
script()

A special single bucket aggregation that enables aggregating nested documents.

Elasticsearch reference

new NestedAggregation(name: string, path: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
path (string?) path of the nested document
Example
const reqBody = esb.requestBodySearch()
    .query(esb.matchQuery('name', 'led tv'))
    .agg(
        esb.nestedAggregation('resellers', 'resellers').agg(
            esb.minAggregation('min_price', 'resellers.price')
        )
    );
Instance Members
field()
script()
path(path)

A special single bucket aggregation that enables aggregating from buckets on child document types to buckets on parent documents.

This aggregation relies on the _parent field in the mapping.

Elasticsearch reference

new ParentAggregation(name: string, type: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
type (string?) The type of the child document.
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.termsAggregation('top-names', 'owner.display_name.keyword')
            .size(10)
            .agg(
                esb.parentAggregation('to-questions')
                    .type('answer')
                    .agg(
                        esb.termsAggregation(
                            'top-tags',
                            'tags.keyword'
                        ).size(10)
                    )
            )
    )
    .size(0);
Instance Members
field()
script()
type(type)

A multi-bucket value source based aggregation that enables the user to define a set of ranges - each representing a bucket. During the aggregation process, the values extracted from each document will be checked against each bucket range and "bucket" the relevant/matching document.

Note that this aggregration includes the from value and excludes the to value for each range.

Elasticsearch reference

new RangeAggregation(name: string, field: string?)

Extends RangeAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.rangeAggregation('price_ranges', 'price').ranges([
    { to: 50 },
    { from: 50, to: 100 },
    { from: 100 }
]);
const agg = esb.rangeAggregation('price_ranges')
    .script(esb.script('inline', "doc['price'].value").lang('painless'))
    .ranges([{ to: 50 }, { from: 50, to: 100 }, { from: 100 }]);
// Value script for on-the-fly conversion before aggregation
const agg = esb.rangeAggregation('price_ranges', 'price')
    .script(
        esb.script('inline', '_value * params.conversion_rate')
            .lang('painless')
            .params({ conversion_rate: 0.8 })
    )
    .ranges([{ to: 50 }, { from: 50, to: 100 }, { from: 100 }]);
// Compute statistics over the prices in each price range
const agg = esb.rangeAggregation('price_ranges', 'price')
    .ranges([{ to: 50 }, { from: 50, to: 100 }, { from: 100 }])
    // Passing price to Stats Aggregation is optional(same value source)
    .agg(esb.statsAggregation('price_stats', 'price'));

A multi-bucket value source based aggregation which finds "rare" terms — terms that are at the long-tail of the distribution and are not frequent. Conceptually, this is like a terms aggregation that is sorted by _count ascending. As noted in the terms aggregation docs, actually ordering a terms agg by count ascending has unbounded error. Instead, you should use the rare_terms aggregation

Elasticsearch reference

NOTE: Only available in Elasticsearch 7.3.0+.

new RareTermsAggregation(name: string, field: string)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string) The field we wish to find rare terms in
Example
const agg = esb.rareTermsAggregation('genres', 'genre');
Instance Members
maxDocCount(maxDocCnt)
precision(precision)
include(include)
exclude(exclude)
missing(value)
script()

A special single bucket aggregation that enables aggregating on parent docs from nested documents. Effectively this aggregation can break out of the nested block structure and link to other nested structures or the root document, which allows nesting other aggregations that aren’t part of the nested object in a nested aggregation.

The reverse_nested aggregation must be defined inside a nested aggregation.

Elasticsearch reference

new ReverseNestedAggregation(name: string, path: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
path (string?) Defines to what nested object field should be joined back. The default is empty, which means that it joins back to the root / main document level.
Example
const reqBody = esb.requestBodySearch()
    .query(esb.matchQuery('name', 'led tv'))
    .agg(
        esb.nestedAggregation('comments', 'comments').agg(
            esb.termsAggregation('top_usernames', 'comments.username').agg(
                esb.reverseNestedAggregation('comment_to_issue').agg(
                    esb.termsAggregation('top_tags_per_comment', 'tags')
                )
            )
        )
    );
Instance Members
field()
script()
path(path)

A filtering aggregation used to limit any sub aggregations' processing to a sample of the top-scoring documents.

Elasticsearch reference

new SamplerAggregation(name: string, field: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const reqBody = esb.requestBodySearch()
    .query(esb.queryStringQuery('tags:kibana OR tags:javascript'))
    .agg(
        esb.samplerAggregation('sample')
            .shardSize(200)
            .agg(
                esb.significantTermsAggregation(
                    'keywords',
                    'tags'
                ).exclude(['kibana', 'javascript'])
            )
    );
Instance Members
field()
script()
shardSize(size)

The TermsAggregationBase provides support for common options used across various terms Aggregation implementations like Significant terms and Terms aggregation.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new TermsAggregationBase(name: string, aggType: string, refUrl: string, field: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
aggType (string) Type of aggregation
refUrl (string) Elasticsearch reference URL.
field (string?) The field to aggregate on
Instance Members
format(fmt)
minDocCount(minDocCnt)
shardMinDocCount(minDocCnt)
size(size)
shardSize(size)
missing(value)
include(clause)
exclude(clause)
executionHint(hint)

The SignificantAggregationBase provides support for common options used in SignificantTermsAggregation and SignificantTextAggregation.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new SignificantAggregationBase()

Extends TermsAggregationBase

Instance Members
jlh()
mutualInformation(includeNegatives = true, backgroundIsSuperset = true)
chiSquare(includeNegatives, backgroundIsSuperset)
gnd(backgroundIsSuperset)
percentage()
scriptHeuristic(script)
backgroundFilter(filterQuery)
script()

An aggregation that returns interesting or unusual occurrences of terms in a set.

Elasticsearch reference

new SignificantTermsAggregation(name: string, field: string?)

Extends SignificantAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const reqBody = esb.requestBodySearch()
    .query(esb.termsQuery('force', 'British Transport Police'))
    .agg(
        esb.significantTermsAggregation(
            'significantCrimeTypes',
            'crime_type'
        )
    );
// Use parent aggregation for segregated data analysis
const agg = esb.termsAggregation('forces', 'force').agg(
    esb.significantTermsAggregation('significantCrimeTypes', 'crime_type')
);

An aggregation that returns interesting or unusual occurrences of free-text terms in a set. It is like the SignificantTermsAggregation but differs in that:

  • It is specifically designed for use on type text fields
  • It does not require field data or doc-values
  • It re-analyzes text content on-the-fly meaning it can also filter duplicate sections of noisy text that otherwise tend to skew statistics.

Elasticsearch reference

NOTE: This query was added in elasticsearch v6.0.

new SignificantTextAggregation(name: string, field: string?)

Extends SignificantAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const reqBody = esb.requestBodySearch()
  .query(esb.matchQuery('content', 'Bird flu'))
  .agg(
    esb.samplerAggregation('my_sample')
      .shardSize(100)
      .agg(esb.significantTextAggregation('keywords', 'content'))
  );
Instance Members
filterDuplicateText(enable)
sourceFields(srcFields)
missing()
executionHint()

A multi-bucket value source based aggregation where buckets are dynamically built - one per unique value.

Elasticsearch reference

new TermsAggregation(name: string, field: string?)

Extends TermsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.termsAggregation('genres', 'genre');
Instance Members
showTermDocCountError(enable)
includePartition(partition, numPartitions)
collectMode(mode)
order(key, direction)

Pipeline Aggregations

Pipeline Aggregations

The PipelineAggregationBase provides support for common options used across various pipeline Aggregation implementations.

Pipeline aggregations cannot have sub-aggregations but depending on the type it can reference another pipeline in the buckets_path allowing pipeline aggregations to be chained. For example, you can chain together two derivatives to calculate the second derivative (i.e. a derivative of a derivative).

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new PipelineAggregationBase(name: string, aggType: string, refUrl: string, bucketsPath: (string | Object)?)

Extends Aggregation

Parameters
name (string) a valid aggregation name
aggType (string) type of aggregation
refUrl (string) Elasticsearch reference URL
bucketsPath ((string | Object)?) The relative path of metric to aggregate over
Instance Members
bucketsPath(path)
gapPolicy(policy)
format(fmt)

A sibling pipeline aggregation which calculates the (mean) average value of a specified metric in a sibling aggregation. The specified metric must be numeric and the sibling aggregation must be a multi-bucket aggregation.

Elasticsearch reference

new AvgBucketAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date')
            .interval('month')
            .agg(esb.sumAggregation('sales', 'price'))
    )
    .agg(
        esb.avgBucketAggregation(
            'avg_monthly_sales',
            'sales_per_month>sales'
        )
    )
    .size(0);

A parent pipeline aggregation which calculates the derivative of a specified metric in a parent histogram (or date_histogram) aggregation. The specified metric must be numeric and the enclosing histogram must have min_doc_count set to 0 (default for histogram aggregations).

Elasticsearch reference

new DerivativeAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date')
            .interval('month')
            .agg(esb.sumAggregation('sales', 'price'))
            .agg(esb.derivativeAggregation('sales_deriv', 'sales'))
    )
    .size(0);
// First and second order derivative of the monthly sales
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date')
            .interval('month')
            .agg(esb.sumAggregation('sales', 'price'))
            .agg(esb.derivativeAggregation('sales_deriv', 'sales'))
            .agg(esb.derivativeAggregation('sales_2nd_deriv', 'sales_deriv'))
    )
    .size(0);
Instance Members
unit(unit)

A sibling pipeline aggregation which identifies the bucket(s) with the maximum value of a specified metric in a sibling aggregation and outputs both the value and the key(s) of the bucket(s). The specified metric must be numeric and the sibling aggregation must be a multi-bucket aggregation.

Elasticsearch reference

new MaxBucketAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date')
            .interval('month')
            .agg(esb.sumAggregation('sales', 'price'))
    )
    .agg(
        // Metric embedded in sibling aggregation
        // Get the maximum value of `sales` aggregation in
        // `sales_per_month` histogram
        esb.maxBucketAggregation(
            'max_monthly_sales',
            'sales_per_month>sales'
        )
    )
    .size(0);

A sibling pipeline aggregation which identifies the bucket(s) with the minimum value of a specified metric in a sibling aggregation and outputs both the value and the key(s) of the bucket(s). The specified metric must be numeric and the sibling aggregation must be a multi-bucket aggregation.

Elasticsearch reference

new MinBucketAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date')
            .interval('month')
            .agg(esb.sumAggregation('sales', 'price'))
    )
    .agg(
        // Metric embedded in sibling aggregation
        // Get the minimum value of `sales` aggregation in
        // `sales_per_month` histogram
        esb.minBucketAggregation(
            'min_monthly_sales',
            'sales_per_month>sales'
        )
    )
    .size(0);

A sibling pipeline aggregation which calculates the sum across all bucket of a specified metric in a sibling aggregation. The specified metric must be numeric and the sibling aggregation must be a multi-bucket aggregation.

Elasticsearch reference

new SumBucketAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date')
            .interval('month')
            .agg(esb.sumAggregation('sales', 'price'))
    )
    .agg(
        // Get the sum of all the total monthly `sales` buckets
        esb.sumBucketAggregation(
            'sum_monthly_sales',
            'sales_per_month>sales'
        )
    )
    .size(0);

A sibling pipeline aggregation which calculates a variety of stats across all bucket of a specified metric in a sibling aggregation. The specified metric must be numeric and the sibling aggregation must be a multi-bucket aggregation.

Elasticsearch reference

new StatsBucketAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date')
            .interval('month')
            .agg(esb.sumAggregation('sales', 'price'))
    )
    .agg(
        // Calculates stats for monthly sales
        esb.statsBucketAggregation(
            'stats_monthly_sales',
            'sales_per_month>sales'
        )
    )
    .size(0);

A sibling pipeline aggregation which calculates a variety of stats across all bucket of a specified metric in a sibling aggregation. The specified metric must be numeric and the sibling aggregation must be a multi-bucket aggregation.

Elasticsearch reference

new ExtendedStatsBucketAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date')
            .interval('month')
            .agg(esb.sumAggregation('sales', 'price'))
    )
    .agg(
        // Calculates extended stats for monthly sales
        esb.extendedStatsBucketAggregation(
            'stats_monthly_sales',
            'sales_per_month>sales'
        )
    )
    .size(0);
Instance Members
sigma(sigma)

A sibling pipeline aggregation which calculates percentiles across all bucket of a specified metric in a sibling aggregation. The specified metric must be numeric and the sibling aggregation must be a multi-bucket aggregation.

Elasticsearch reference

new PercentilesBucketAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date')
            .interval('month')
            .agg(esb.sumAggregation('sales', 'price'))
    )
    .agg(
        // Calculates stats for monthly sales
        esb.percentilesBucketAggregation(
            'percentiles_monthly_sales',
            'sales_per_month>sales'
        ).percents([25.0, 50.0, 75.0])
    )
    .size(0);
Instance Members
percents(percents)

Given an ordered series of data, the Moving Average aggregation will slide a window across the data and emit the average value of that window.

moving_avg aggregations must be embedded inside of a histogram or date_histogram aggregation.

Elasticsearch reference

new MovingAverageAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const agg = esb.movingAverageAggregation('the_movavg', 'the_sum')
    .model('holt')
    .window(5)
    .gapPolicy('insert_zeros')
    .settings({ alpha: 0.8 });
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('my_date_histo', 'timestamp')
            .interval('day')
            .agg(esb.sumAggregation('the_sum', 'lemmings'))
            // Relative path to sibling metric `the_sum`
            .agg(esb.movingAverageAggregation('the_movavg', 'the_sum'))
    )
    .size(0);
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('my_date_histo', 'timestamp')
            .interval('day')
            // Use the document count as it's input
            .agg(esb.movingAverageAggregation('the_movavg', '_count'))
    )
    .size(0);
Instance Members
format()
model(model)
window(window)
minimize(enable)
settings(settings)
predict(predict)

Given an ordered series of data, the Moving Function aggregation will slide a window across the data and allow the user to specify a custom script that is executed on each window of data. For convenience, a number of common functions are predefined such as min/max, moving averages, etc.

moving_fn aggregations must be embedded inside of a histogram or date_histogram aggregation.

Elasticsearch reference

NOTE: Only available in Elasticsearch 6.4.0+.

new MovingFunctionAggregation(name: string, bucketsPath: string?, window: string?, script: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over.
window (string?) The size of window to "slide" across the histogram.
script (string?) The script that should be executed on each window of data.
Example
const agg = esb.movingFunctionAggregation('the_movfn', 'the_sum')
    .model('holt')
    .window(5)
    .gapPolicy('insert_zeros')
    .settings({ alpha: 0.8 });
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('my_date_histo', 'timestamp')
            .interval('day')
            .agg(esb.sumAggregation('the_sum', 'lemmings'))
            // Relative path to sibling metric `the_sum`
            .agg(esb.movingFunctionAggregation('the_movfn', 'the_sum'))
    )
    .size(0);
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('my_date_histo', 'timestamp')
            .interval('day')
            // Use the document count as it's input
            .agg(esb.movingFunctionAggregation('the_movfn', '_count'))
    )
    .size(0);
Instance Members
window(window)
shift(shift)
script(script)

A parent pipeline aggregation which calculates the cumulative sum of a specified metric in a parent histogram (or date_histogram) aggregation. The specified metric must be numeric and the enclosing histogram must have min_doc_count set to 0 (default for histogram aggregations).

Elasticsearch reference

new CumulativeSumAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date', 'month')
            .agg(esb.sumAggregation('sales', 'price'))
            .agg(esb.cumulativeSumAggregation('cumulative_sales', 'sales'))
    )
    .size(0);
Instance Members
gapPolicy()

A parent pipeline aggregation which executes a script which can perform per bucket computations on specified metrics in the parent multi-bucket aggregation. The specified metric must be numeric and the script must return a numeric value.

Elasticsearch reference

new BucketScriptAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date', 'month')
            .agg(esb.sumAggregation('total_sales', 'price'))
            .agg(
                esb.filterAggregation('t-shirts')
                    .filter(esb.termQuery('type', 't-shirt'))
                    .agg(esb.sumAggregation('sales', 'price'))
            )
            .agg(
                esb.bucketScriptAggregation('t-shirt-percentage')
                    .bucketsPath({
                        tShirtSales: 't-shirts>sales',
                        totalSales: 'total_sales'
                    })
                    .script('params.tShirtSales / params.totalSales * 100')
            )
    )
    .size(0);
Instance Members
script(script)

A parent pipeline aggregation which executes a script which determines whether the current bucket will be retained in the parent multi-bucket aggregation. The specified metric must be numeric and the script must return a boolean value. If the script language is expression then a numeric return value is permitted. In this case 0.0 will be evaluated as false and all other values will evaluate to true.

Elasticsearch reference

new BucketSelectorAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('histo', 'date')
            .interval('day')
            .agg(esb.termsAggregation('categories', 'category'))
            .agg(
                esb.bucketSelectorAggregation('min_bucket_selector')
                    .bucketsPath({ count: 'categories._bucket_count' })
                    .script(esb.script('inline', 'params.count != 0'))
            )
    )
    .size(0);
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('sales_per_month', 'date')
            .interval('month')
            .agg(esb.sumAggregation('sales', 'price'))
            .agg(
                esb.bucketSelectorAggregation('sales_bucket_filter')
                    .bucketsPath({ totalSales: 'total_sales' })
                    .script('params.totalSales > 200')
            )
    )
    .size(0);
Instance Members
format()
script(script)

Serial differencing is a technique where values in a time series are subtracted from itself at different time lags or periods.

Serial differences are built by first specifying a histogram or date_histogram over a field.

Elasticsearch reference

new SerialDifferencingAggregation(name: string, bucketsPath: string?)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
bucketsPath (string?) The relative path of metric to aggregate over
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.dateHistogramAggregation('my_date_histo', 'timestamp')
            .interval('day')
            .agg(esb.sumAggregation('the_sum', 'lemmings'))
            .agg(
                esb.serialDifferencingAggregation(
                    'thirtieth_difference',
                    'the_sum'
                ).lag(30)
            )
    )
    .size(0);
Instance Members
lag(lag)

A parent pipeline aggregation which sorts the buckets of its parent multi-bucket aggregation. Zero or more sort fields may be specified together with the corresponding sort order. Each bucket may be sorted based on its _key, _count or its sub-aggregations. In addition, parameters from and size may be set in order to truncate the result buckets.

Elasticsearch reference

new BucketSortAggregation(name: string)

Extends PipelineAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
Example
const reqBody = esb.requestBodySearch()
    .agg(
        esb.bucketSortAggregation('sort')
            .sort([
                 esb.sort('user', 'desc')
             ])
             .from(5)
             .size(10)
        )
    );
Instance Members
sort(sort)
from(from)
size(size)

Matrix Aggregations

Matrix Aggregations

The matrix_stats aggregation is a numeric aggregation that computes statistics over a set of document fields

Elasticsearch reference

new MatrixStatsAggregation(name: string, fields: Array?)

Extends Aggregation

Parameters
name (string) A valid aggregation name
fields (Array?) Array of fields
Example
const agg = esb.matrixStatsAggregation('matrixstats', ['poverty', 'income']);
Instance Members
fields(fields)
mode(mode)
missing(missing)

Score Functions

Score Functions

ScoreFunction provides support for common options used across various ScoreFunction implementations.

Elasticsearch reference

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new ScoreFunction(name: string)
Parameters
name (string)
Instance Members
filter(filterQry)
weight(weight)
toJSON()

The script_score function allows you to wrap another query and customize the scoring of it optionally with a computation derived from other numeric field values in the doc using a script expression.

Elasticsearch reference

new ScriptScoreFunction(script: (Script | string))

Extends ScoreFunction

Parameters
script ((Script | string))
Example
const scoreFunc = esb.scriptScoreFunction(
    esb.script('inline', "_score * doc['my_numeric_field'].value")
        .lang('painless')
);
// Script with parameters
const scoreFunc = esb.scriptScoreFunction(
    esb.script(
        'inline',
        "_score * doc['my_numeric_field'].value / Math.pow(params.param1, params.param2)"
    )
        .lang('painless')
        .params({ param1: 'value1', param2: 'value2' })
);
Instance Members
script(script)

The weight score allows you to multiply the score by the provided weight. This can sometimes be desired since boost value set on specific queries gets normalized, while for this score function it does not. The number value is of type float.

Elasticsearch reference

new WeightScoreFunction(weight: number?)

Extends ScoreFunction

Parameters
weight (number?) The weight of this score function.
Example
const scoreFunc = esb.weightScoreFunction(42);
Instance Members
toJSON()

The random_score generates scores using a hash of the _uid field, with a seed for variation. If seed is not specified, the current time is used.

Elasticsearch reference

new RandomScoreFunction()

Extends ScoreFunction

Example
const scoreFunc = esb.randomScoreFunction().seed(299792458);
Instance Members
seed(seed)

The field_value_factor function allows you to use a field from a document to influence the score. It's similar to using the script_score function, however, it avoids the overhead of scripting. If used on a multi-valued field, only the first value of the field is used in calculations.

Elasticsearch reference

new FieldValueFactorFunction(field: string?)

Extends ScoreFunction

Parameters
field (string?) the field to be extracted from the document.
Example
// Scoring formula - sqrt(1.2 * doc['popularity'].value)
const scoreFunc = esb.fieldValueFactorFunction('popularity')
    .factor(1.2)
    .modifier('sqrt')
    .missing(1);
Instance Members
field(field)
factor(factor)
modifier(mod)
missing(val)

Decay functions score a document with a function that decays depending on the distance of a numeric field value of the document from a user given origin. This is similar to a range query, but with smooth edges instead of boxes.

Supported decay functions are: linear, exp, and gauss.

Elasticsearch reference

If no mode is supplied, gauss will be used.

new DecayScoreFunction(mode: string?, field: string?)

Extends ScoreFunction

Parameters
mode (string? = 'gauss') Can be one of linear , exp , and gauss . Defaults to gauss .
field (string?) the document field to run decay function against.
Example
// Defaults to decay function `gauss`
const decayFunc = esb.decayScoreFunction()
    .field('location') // field is a geo_point
    .origin('11, 12') // geo format
    .scale('2km')
    .offset('0km')
    .decay(0.33);
const decayFunc = esb.decayScoreFunction('gauss', 'date')
    .origin('2013-09-17')
    .scale('10d')
    .offset('5d')
    .decay(0.5);
Instance Members
mode(mode)
linear()
exp()
gauss()
field(field)
origin(origin)
scale(scale)
offset(offset)
decay(decay)
toJSON()

Suggesters

Suggesters

Base class implementation for all suggester types.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class should be extended and used, as validation against the class type is present in various places.

new Suggester(suggesterType: string, name: string, field: string?)
Parameters
suggesterType (string) The type of suggester. Can be one of term , phrase , completion
name (string) The name of the Suggester, an arbitrary identifier
field (string?) The field to fetch the candidate suggestions from.
Throws
  • Error: if name is empty
  • Error: if suggesterType is empty
Instance Members
field(field)
size(size)
toJSON()

The AnalyzedSuggesterBase provides support for common options used in TermSuggester and PhraseSuggester.

NOTE: Instantiating this directly should not be required. However, if you wish to add a custom implementation for whatever reason, this class could be extended.

new AnalyzedSuggesterBase(suggesterType: string, name: string, field: string?, txt: string?)

Extends Suggester

Parameters
suggesterType (string) The type of suggester. Can be one of term , phrase
name (string) The name of the Suggester, an arbitrary identifier
field (string?) The field to fetch the candidate suggestions from.
txt (string?) A string to get suggestions for.
Throws
  • Error: if name is empty
  • Error: if suggesterType is empty
Instance Members
text(txt)
analyzer(analyzer)
shardSize(size)

The term suggester suggests terms based on edit distance. The provided suggest text is analyzed before terms are suggested. The suggested terms are provided per analyzed suggest text token. The term suggester doesn’t take the query into account that is part of request.

Elasticsearch reference

new TermSuggester(name: string, field: string?, txt: string?)

Extends AnalyzedSuggesterBase

Parameters
name (string) The name of the Suggester, an arbitrary identifier
field (string?) The field to fetch the candidate suggestions from.
txt (string?) A string to get suggestions for.
Throws
  • Error: if name is empty
Example
const suggest = esb.termSuggester(
    'my-suggestion',
    'message',
    'tring out Elasticsearch'
);
Instance Members
sort(sort)
suggestMode(mode)
maxEdits(maxEdits)
prefixLength(len)
minWordLength(len)
maxInspections(maxInspections)
minDocFreq(limit)
maxTermFreq(limit)
stringDistance(implMethod)

The phrase suggester uses candidate generators to produce a list of possible terms per term in the given text. A single candidate generator is similar to a term suggester called for each individual term in the text. The output of the generators is subsequently scored in combination with the candidates from the other terms to for suggestion candidates.

The Phrase suggest API accepts a list of generators under the key direct_generator each of the generators in the list are called per term in the original text.

Elasticsearch reference

new DirectGenerator(field: string?)
Parameters
field (string?) The field to fetch the candidate suggestions from.
Instance Members
field(field)
size(size)
suggestMode(mode)
maxEdits(maxEdits)
prefixLength(len)
minWordLength(len)
maxInspections(maxInspections)
minDocFreq(limit)
maxTermFreq(limit)
preFilter(filter)
postFilter(filter)
toJSON()

The phrase suggester adds additional logic on top of the term suggester to select entire corrected phrases instead of individual tokens weighted based on ngram-language models. In practice this suggester will be able to make better decisions about which tokens to pick based on co-occurrence and frequencies.

Elasticsearch reference

new PhraseSuggester(name: string, field: string?, txt: string?)

Extends AnalyzedSuggesterBase

Parameters
name (string) The name of the Suggester, an arbitrary identifier
field (string?) The field to fetch the candidate suggestions from.
txt (string?) A string to get suggestions for.
Throws
  • Error: if name is empty
Example
const suggest = esb.phraseSuggester(
    'simple_phrase',
    'title.trigram',
    'noble prize'
)
    .size(1)
    .gramSize(3)
    .directGenerator(esb.directGenerator('title.trigram').suggestMode('always'))
    .highlight('<em>', '</em>');
Instance Members
gramSize(size)
realWordErrorLikelihood(factor)
confidence(level)
maxErrors(limit)
separator(sep)
highlight(preTag, postTag)
collate(opts)
smoothing(model)
directGenerator(dirGen)
toJSON()

The completion suggester provides auto-complete/search-as-you-type functionality. This is a navigational feature to guide users to relevant results as they are typing, improving search precision. It is not meant for spell correction or did-you-mean functionality like the term or phrase suggesters.

Ideally, auto-complete functionality should be as fast as a user types to provide instant feedback relevant to what a user has already typed in. Hence, completion suggester is optimized for speed. The suggester uses data structures that enable fast lookups, but are costly to build and are stored in-memory.

Elasticsearch reference

new CompletionSuggester(name: string, field: string?)

Extends Suggester

Parameters
name (string) The name of the Suggester, an arbitrary identifier
field (string?) The field to fetch the candidate suggestions from.
Throws
  • Error: if name is empty
Example
const suggest = esb.completionSuggester('song-suggest', 'suggest').prefix('nir');
const suggest = new esb.CompletionSuggester('place_suggestion', 'suggest')
    .prefix('tim')
    .size(10)
    .contexts('place_type', ['cafe', 'restaurants']);
Instance Members
prefix(prefix)
skipDuplicates(skip)
fuzzy(fuzzy = true)
fuzziness(factor)
transpositions(enable)
minLength(len)
prefixLength(len)
unicodeAware(enable)
regex(expr)
flags(flags)
maxDeterminizedStates(limit)
contexts(name, ctx)

Miscellaneous

Miscellaneous

Allows to highlight search results on one or more fields. In order to perform highlighting, the actual content of the field is required. If the field in question is stored (has store set to yes in the mapping), it will be used, otherwise, the actual _source will be loaded and the relevant field will be extracted from it.

If no term_vector information is provided (by setting it to with_positions_offsets in the mapping), then the plain highlighter will be used. If it is provided, then the fast vector highlighter will be used. When term vectors are available, highlighting will be performed faster at the cost of bigger index size.

Elasticsearch reference

new Highlight(fields: (string | Array)?)
Parameters
fields ((string | Array)?) An optional field or array of fields to highlight.
Example
const reqBody = esb.requestBodySearch()
    .query(esb.matchAllQuery())
    .highlight(esb.highlight('content'));
const highlight = esb.highlight()
    .numberOfFragments(3)
    .fragmentSize(150)
    .fields(['_all', 'bio.title', 'bio.author', 'bio.content'])
    .preTags('<em>', '_all')
    .postTags('</em>', '_all')
    .numberOfFragments(0, 'bio.title')
    .numberOfFragments(0, 'bio.author')
    .numberOfFragments(5, 'bio.content')
    .scoreOrder('bio.content');

highlight.toJSON()
{
    "number_of_fragments" : 3,
    "fragment_size" : 150,
    "fields" : {
        "_all" : { "pre_tags" : ["<em>"], "post_tags" : ["</em>"] },
        "bio.title" : { "number_of_fragments" : 0 },
        "bio.author" : { "number_of_fragments" : 0 },
        "bio.content" : { "number_of_fragments" : 5, "order" : "score" }
    }
 }
Instance Members
field(field)
fields(fields)
preTags(tags, field?)
postTags(tags, field?)
styledTagsSchema()
scoreOrder(field?)
fragmentSize(size, field?)
numberOfFragments(count, field?)
noMatchSize(size, field)
highlightQuery(query, field?)
matchedFields(fields, field)
phraseLimit(limit)
encoder(encoder)
requireFieldMatch(requireFieldMatch, field?)
boundaryMaxScan(count, field?)
boundaryChars(charStr, field?)
type(type, field?)
forceSource(forceSource, field?)
fragmenter(fragmenter, field?)
toJSON()

Class supporting the Elasticsearch scripting API.

Elasticsearch reference

Note: inline script type was deprecated in elasticsearch v5.0. source should be used instead. And similarly for stored scripts, type id must be used instead. file scripts were removed as part of the breaking changes in elasticsearch v6.0

new Script(type: string?, source: string?)
Parameters
type (string?) One of inline , stored , file , source , id .
source (string?) Source of the script. This needs to be specified if optional argument type is passed.
Example
const script = esb.script('inline', "doc['my_field'] * multiplier")
    .lang('expression')
    .params({ multiplier: 2 });

// cat "log(_score * 2) + my_modifier" > config/scripts/calculate-score.groovy
const script = esb.script()
    .lang('groovy')
    .file('calculate-score')
    .params({ my_modifier: 2 });
Instance Members
inline(scriptCode)
source(scriptCode)
stored(scriptId)
id(scriptId)
file(fileName)
lang(lang)
params(params)
toJSON()

A GeoPoint object that can be used in queries and filters that take a GeoPoint. GeoPoint supports various input formats.

Elasticsearch reference

new GeoPoint()
Instance Members
lat(lat)
lon(lon)
object(point)
array(point)
string(point)
toJSON()

Shape object that can be used in queries and filters that take a Shape. Shape uses the GeoJSON format.

Elasticsearch reference

new GeoShape(type: string?, coords: Array?)
Parameters
type (string?) A valid shape type. Can be one of point , linestring , polygon , multipoint , multilinestring , multipolygon , geometrycollection , envelope and circle
coords (Array?) A valid coordinat definition for the given shape.
Example
// Pass options using method
const shape = esb.geoShape()
    .type('linestring')
    .coordinates([[-77.03653, 38.897676], [-77.009051, 38.889939]]);
// Pass parameters using contructor
const shape = esb.geoShape('multipoint', [[102.0, 2.0], [103.0, 2.0]])
Instance Members
type(type)
coordinates(coords)
radius(radius)
toJSON()

A shape which has already been indexed in another index and/or index type. This is particularly useful for when you have a pre-defined list of shapes which are useful to your application and you want to reference this using a logical name (for example 'New Zealand') rather than having to provide their coordinates each time.

new IndexedShape(id: string?, type: string?)
Parameters
id (string?) The document id of the shape.
type (string?) The name of the type where the shape is indexed.
Example
const shape = esb.indexedShape('DEU', 'countries')
    .index('shapes')
    .path('location');

const shape = esb.indexedShape()
    .id('DEU')
    .type('countries')
    .index('shapes')
    .path('location');
Instance Members
id(id)
type(type)
index(index)
path(path)
toJSON()

Allows creating and configuring sort on specified field.

Elasticsearch reference

new Sort(field: string?, order: string?)
Parameters
field (string?) The field to sort on. If a script is used to specify the sort order, field should be omitted.
order (string?) The order option can have the following values. asc , desc to sort in ascending, descending order respectively.
Example
const reqBody = esb.requestBodySearch()
    .query(esb.termQuery('user', 'kimchy'))
    .sort(esb.sort('post_date', 'asc'))
Instance Members
order(order)
mode(mode)
nestedPath(path)
nestedFilter(filterQuery)
nested(nested)
missing(value)
unmappedType(type)
geoDistance(geoPoint)
distanceType(type)
unit(unit)
script(script)
type(type)
format(fmt)
reverse(reverse)
toJSON()

A rescore request can help to improve precision by reordering just the top (eg 100 - 500) documents returned by the query and post_filter phases, using a secondary (usually more costly) algorithm, instead of applying the costly algorithm to all documents in the index.

The rescore phase is not executed when sort is used.

Elasticsearch reference

new Rescore(windowSize: number?, rescoreQuery: Query?)
Parameters
windowSize (number?)
rescoreQuery (Query?)
Example
const reqBody = esb.requestBodySearch()
    .query(esb.matchQuery('message', 'the quick brown').operator('or'))
    .rescore(
        esb.rescore(
            50,
            esb.matchPhraseQuery('message', 'the quick brown').slop(2)
        )
            .queryWeight(0.7)
            .rescoreQueryWeight(1.2)
    );
const rescore = esb.rescore(
    10,
    esb.functionScoreQuery().function(
        esb.scriptScoreFunction(
            esb.script('inline', 'Math.log10(doc.likes.value + 2)')
        )
    )
).scoreMode('multiply');
Instance Members
windowSize(windowSize)
rescoreQuery(rescoreQuery)
queryWeight(weight)
rescoreQueryWeight(weight)
scoreMode(mode)
toJSON()

Inner hits returns per search hit in the search response additional nested hits that caused a search hit to match in a different scope. Inner hits can be used by defining an inner_hits definition on a nested, has_child or has_parent query and filter.

Elasticsearch reference

new InnerHits(name: string?)
Parameters
name (string?) The name to be used for the particular inner hit definition in the response. Useful when multiple inner hits have been defined in a single search request. The default depends in which query the inner hit is defined.
Example
const reqBody = esb.requestBodySearch().query(
    esb.nestedQuery(
        esb.matchQuery('comments.message', '[actual query]')
    ).innerHits(
        esb.innerHits().source(false).storedFields(['comments.text'])
    )
);
Instance Members
name(name)
from(from)
size(size)
sort(sort)
sorts(sorts)
highlight(highlight)
explain(enable)
source(source)
storedFields(fields)
scriptField(scriptFieldName, script)
scriptFields(scriptFields)
docvalueFields(fields)
version(enable)
toJSON()

Class supporting the Elasticsearch search template API.

The /_search/template endpoint allows to use the mustache language to pre render search requests, before they are executed and fill existing templates with template parameters.

Elasticsearch reference

new SearchTemplate(type: string?, source: (string | Object)?)
Parameters
type (string?) One of inline , id , file . id is also aliased as indexed
source ((string | Object)?) Source of the search template. This needs to be specified if optional argument type is passed.
Example
const templ = esb.searchTemplate('inline', {
    query: esb.matchQuery('{{my_field}}', '{{my_value}}'),
    size: '{{my_size}}'
}).params({
    my_field: 'message',
    my_value: 'some message',
    my_size: 5
});
const templ = new esb.SearchTemplate(
    'inline',
    '{ "query": { "terms": {{#toJson}}statuses{{/toJson}} }}'
).params({
    statuses: {
        status: ['pending', 'published']
    }
});
const templ = new esb.SearchTemplate(
    'inline',
    '{ "query": { "bool": { "must": {{#toJson}}clauses{{/toJson}} } } }'
).params({
    clauses: [
        esb.termQuery('user', 'boo'),
        esb.termQuery('user', 'bar'),
        esb.termQuery('user', 'baz')
    ]
});
Instance Members
inline(templ)
id(templId)
indexed(templId)
file(fileName)
params(params)
toJSON()

Helper recipes for common query use cases.

If you have any recipes, please do share or better yet, create a pull request.

Recipes:

These can be accessed under the recipes namespace or using the cook[Recipe Name] alias for ease of use.

recipes
Example
// `recipes` namespace
const qry = esb.recipes.missingQuery('user');
// `cookMissingQuery` alias
const qry = esb.cookMissingQuery('user');

Class representing a k-Nearest Neighbors (k-NN) query. This class extends the Query class to support the specifics of k-NN search, including setting up the field, query vector, number of neighbors (k), and number of candidates.

new KNN(field: any, k: any, numCandidates: any)
Parameters
field (any)
k (any)
numCandidates (any)
Example
const qry = esb.kNN('my_field', 100, 1000).vector([1,2,3]);
const qry = esb.kNN('my_field', 100, 1000).queryVectorBuilder('model_123', 'Sample model text');

NOTE: kNN search was added to Elasticsearch in v8.0

[Elasticsearch reference](https://www.elastic.co/guide/en/elasticsearch/reference/current/knn-search.html)
Instance Members
queryVector(vector)
queryVectorBuilder(modelId, modelText)
filter(queries)
boost(boost)
similarity(similarity)
toJSON()

Echos the value of a value. Trys to print the value out in the best way possible given the different types.

inspect(obj: Object, opts: Object): string
Parameters
obj (Object) The object to print out.
opts (Object) Optional options object that alters the output.
Returns
string:

Class supporting the Elasticsearch runtime field.

Elasticsearch reference

Added in Elasticsearch v7.11.0 Release note

new RuntimeField(type: string?, script: string?)
Parameters
type (string?) One of boolean , composite , date , double , geo_point , ip , keyword , long , lookup .
script (string?) Source of the script.
Example
const field = esb.runtimeField('keyword', `emit(doc['sessionId'].value + '::' + doc['name'].value)`);
Instance Members
script(script)
type(type)
lang(lang)
params(params)
toJSON()

Elasticsearch reference

new CombinedFieldsQuery(fields: (Array<string> | string)?, queryString: string?)

Extends FullTextQueryBase

Parameters
fields ((Array<string> | string)?) The fields to be queried
queryString (string?) The query string
Example
const qry = esb.combinedFieldsQuery(['subject', 'message'], 'this is a test');

NOTE: This query was added in elasticsearch v7.13.
Instance Members
field(field)
fields(fields)
autoGenerateSynonymsPhraseQuery(enable)
operator(operator)
zeroTermsQuery(behavior)

A query that uses a script to provide a custom score for returned documents.

Elasticsearch reference

NOTE: This query was added in elasticsearch v7.0.

new ScriptScoreQuery()

Extends Query

Example
const qry = esb.scriptScoreQuery()
  .query(esb.matchQuery("message", "elasticsearch"))
  .script(esb.script().source("doc['my-int'].value / 10"))
Instance Members
query(query)
script(script)
minScore(limit)

The distance_feature query can be used to filter documents that are inside a timeframe or radius given an origin point. For dates the difference can be minutes, hours, etc and for coordinates it can be meters, kilometers..

Elasticsearch reference

NOTE: Only available in Elasticsearch 7.1.0+.

new DistanceFeatureQuery(field: string)

Extends Query

Parameters
field (string) The field inside the document to be used in the query
Example
const query = new DistanceFeatureQuery('time');
  query
      .origin('now')
      .pivot('1h')
      .toJSON();
Instance Members
field(fieldName)
origin(originPoint)
pivot(pivotDistance)

The rank_feature query boosts the relevance score on the numeric value of document with a rank_feature/rank_features field.

Elasticsearch reference

NOTE: This query was added in elasticsearch v7.0.

new RankFeatureQuery(field: string)

Extends Query

Parameters
field (string) The field inside the document to be used in the query
Example
const query = new RankFeatureQuery('rank_feature_field');
  query
      .linear()
      .toJSON();
Instance Members
field(fieldName)
linear()
saturation()
saturationPivot(pivot)
log(scalingFactor, scaling_factor)
sigmoid(pivot, exponent)

A single-value metrics aggregation that computes the weighted average of numeric values that are extracted from the aggregated documents. These values can be extracted either from specific numeric fields in the documents.

Elasticsearch reference

Added in Elasticsearch v6.4.0 Release notes

As a formula, a weighted average is ∑(value * weight) / ∑(weight)

new WeightedAverageAggregation(name: string, value: string?, weight: string?)

Extends MetricsAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
value (string?) The field or script to be used as the value.
weight (string?) The field or script to be used as the weighting.
Example
// Compute the average grade over all documents, weighing by teacher score.
const agg = esb.weightedAverageAggregation('avg_grade', 'grade', 'teacher_score');
// Compute the average grade where the weight is calculated by a script.
// Filling in missing values as '10'.
const agg = esb.weightedAverageAggregation('avg_grade', 'grade')
     .weight(esb.script('inline', "doc['teacher_score'].value").lang('painless'), 10)
);
// Compute the average grade, weighted by teacher score, filling in missing values.
const agg = esb.weightedAverageAggregation('avg_grade').value('grade', 5).weight('teacher_score', 10));
// Compute the average grade over all documents, weighing by teacher score.
const agg = esb.weightedAverageAggregation('avg_grade').value('grade').weight('teacher_score');
Instance Members
value(value, missing?)
weight(weight, missing?)
script()
missing()
field()

This is a multi-bucket aggregation similar to Histogram. However, the width of each bucket is not specified. Rather, a target number of buckets is provided and bucket intervals are dynamically determined based on the document distribution. This is done using a simple one-pass document clustering algorithm that aims to obtain low distances between bucket centroids. Unlike other multi-bucket aggregations, the intervals will not necessarily have a uniform width.

Elasticsearch reference

NOTE: Only available in Elasticsearch v7.9.0+

new VariableWidthHistogramAggregation(name: string, field: string?, buckets: number?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
buckets (number?) Bucket count to generate histogram over.
Example
const agg = esb.variableWidthHistogramAggregation('price', 'lowestPrice', 10)
Instance Members
buckets(buckets)

A multi-bucket aggregation that groups geo_point and geo_shape values into buckets that represent a grid. The resulting grid can be sparse and only contains cells that have matching data. Each cell corresponds to a H3 cell index and is labeled using the H3Index representation.

Elasticsearch reference

NOTE: This aggregation was added in elasticsearch v8.1.0.

new GeoHexGridAggregation(name: string, field: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.geoHexGridAggregation('hex-grid', 'location').precision(3);
Instance Members
format()
script()
precision(precision)
size(size)
shardSize(shardSize)

A multi-bucket aggregation that works on geo_point fields and groups points into buckets that represent cells in a grid. The resulting grid can be sparse and only contains cells that have matching data. Each cell corresponds to a map tile as used by many online map sites. Each cell is labeled using a "{zoom}/{x}/{y}" format, where zoom is equal to the user-specified precision.

Elasticsearch reference

NOTE: This query was added in elasticsearch v7.0.

new GeoTileGridAggregation(name: string, field: string?)

Extends BucketAggregationBase

Parameters
name (string) The name which will be used to refer to this aggregation.
field (string?) The field to aggregate on
Example
const agg = esb.geoTileGridAggregation('large-grid', 'location').precision(8);
Instance Members
format()
script()
precision(precision)
size(size)
shardSize(shardSize)
topLeft(point)
bottomRight(point)
topRight(point)
bottomLeft(point)
top(val)
left(val)
bottom(val)
right(val)

missingQuery

src/recipes.js

Recipe for the now removed missing query.

Can be accessed using esb.recipes.missingQuery OR esb.cookMissingQuery.

Elasticsearch refererence

missingQuery(field: string): BoolQuery
Parameters
field (string) The field which should be missing the value.
Returns
BoolQuery: A boolean query with a must_not exists clause is returned.
Example
const qry = esb.cookMissingQuery('user');

qry.toJSON();
{
  "bool": {
    "must_not": {
      "exists": {
        "field": "user"
      }
    }
  }
}

randomSortQuery

src/recipes.js

Recipe for random sort query. Takes a query and returns the same wrapped in a random scoring query.

Can be accessed using esb.recipes.randomSortQuery OR esb.cookRandomSortQuery.

Elasticsearch reference

randomSortQuery(query: Query?, seed: number?): FunctionScoreQuery
Parameters
query (Query? = new MatchAllQuery()) The query to fetch documents for. Defaults to match_all query.
seed (number?) A seed value for the random score function.
Returns
FunctionScoreQuery: A function_score query with random sort applied
Throws
  • TypeError: If query is not an instance of Query .
Example
const reqBody = esb.requestBodySearch()
    .query(esb.cookRandomSortQuery(esb.rangeQuery('age').gte(10)))
    .size(100);

reqBody.toJSON();
{
  "query": {
    "function_score": {
      "query": {
        "range": { "age": { "gte": 10 } }
      },
      "random_score": {}
    }
  },
  "size": 100
}

filterQuery

src/recipes.js

Recipe for constructing a filter query using bool query. Optionally, scoring can be enabled.

Can be accessed using esb.recipes.filterQuery OR esb.cookFilterQuery.

Elasticsearch reference

filterQuery(query: Query, scoring: boolean?): BoolQuery
Parameters
query (Query) The query to fetch documents for.
scoring (boolean? = false) Optional flag for enabling/disabling scoring. Disabled by default. If enabled, a score of 1.0 will be assigned to all documents.
Returns
BoolQuery: A bool query with a filter clause is returned.
Throws
  • TypeError: If query is not an instance of Query .
Example
const boolQry = esb.cookFilterQuery(esb.termQuery('status', 'active'), true);
boolQry.toJSON();
{
  "bool": {
    "must": { "match_all": {} },
    "filter": {
      "term": { "status": "active" }
    }
  }
}