elastic-builder

2.7.1

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)
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)
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()

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
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)
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()