2.30.0
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).
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.
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')
)
);
Define query on the search request body using the Query DSL.
(Query)
RequestBodySearch
:
returns
this
so that calls can be chained.
Sets knn on the search request body.
((Knn | Array<Knn>))
RequestBodySearch
:
returns
this
so that calls can be chained.
Sets aggregation on the request body.
Alias for method aggregation
RequestBodySearch
:
returns
this
so that calls can be chained.
agg
is not an instance of
Aggregation
Sets aggregation on the request body.
RequestBodySearch
:
returns
this
so that calls can be chained.
agg
is not an instance of
Aggregation
Sets multiple nested aggregation items.
Alias for method aggregations
Aggregation
:
returns
this
so that calls can be chained.
Sets multiple nested aggregation items. This method accepts an array to set multiple nested aggregations in one call.
Aggregation
:
returns
this
so that calls can be chained.
Sets suggester on the request body.
RequestBodySearch
:
returns
this
so that calls can be chained.
suggest
is not an instance of
Suggester
const req = esb.requestBodySearch()
.query(esb.matchQuery('message', 'trying out elasticsearch'))
.suggest(
esb.termSuggester(
'my-suggestion',
'message',
'tring out Elasticsearch'
)
);
Sets the global suggest text to avoid repetition for multiple suggestions.
(string)
Global suggest text
RequestBodySearch
:
returns
this
so that calls can be chained.
const req = esb.requestBodySearch()
.suggestText('tring out elasticsearch')
.suggest(esb.termSuggester('my-suggest-1', 'message'))
.suggest(esb.termSuggester('my-suggest-2', 'user'));
Sets a search timeout, bounding the search request to be executed within the specified time value and bail with the hits accumulated up to that point when expired.
RequestBodySearch
:
returns
this
so that calls can be chained.
To retrieve hits from a certain offset.
(number)
Defaults to 0.
RequestBodySearch
:
returns
this
so that calls can be chained.
The number of hits to return. If you do not care about getting some hits back but only about the number of matches and/or aggregations, setting the value to 0 will help performance.
(number)
Defaults to 10.
RequestBodySearch
:
returns
this
so that calls can be chained.
The maximum number of documents to collect for each shard, upon reaching which
the query execution will terminate early. If set, the response will have a
boolean field terminated_early
to indicate whether the query execution has
actually terminated early.
(number)
Maximum number of documents to collect for each shard.
Defaults to no limit.
RequestBodySearch
:
returns
this
so that calls can be chained.
Allows to add sort on specific field. The sort can be reversed as well.
The sort is defined on a per field level, with special field name for _score
to
sort by score, and _doc
to sort by index order.
(Sort)
RequestBodySearch
:
returns
this
so that calls can be chained.
sort
is not an instance of
Sort
.
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.sort(esb.sort('post_date', 'asc'))
.sort(esb.sort('user'))
.sorts([
esb.sort('name', 'desc'),
esb.sort('age', 'desc'),
esb.sort('_score')
]);
Allows to add multiple sort on specific fields. Each sort can be reversed as well. The sort is defined on a per field level, with special field name for _score to sort by score, and _doc to sort by index order.
RequestBodySearch
:
returns
this
so that calls can be chained.
sorts
is not an instance of
Sort
.
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.sort(esb.sort('post_date', 'asc'))
.sort(esb.sort('user'))
.sorts([
esb.sort('name', 'desc'),
esb.sort('age', 'desc'),
esb.sort('_score')
]);
When sorting on a field, scores are not computed. By setting track_scores
to true,
scores will still be computed and tracked.
(boolean)
RequestBodySearch
:
returns
this
so that calls can be chained
const reqBody = esb.requestBodySearch()
.trackScores(true)
.sorts([
esb.sort('post_date', 'desc'),
esb.sort('name', 'desc'),
esb.sort('age', 'desc')
])
.query(esb.termQuery('user', 'kimchy'));
The track_total_hits
parameter allows you to control how the total number of hits
should be tracked. Passing false
can increase performance in some situations.
(Added in elasticsearch@7)
Pass true
, false
, or the upper limit (default: 10000
) of hits you want tracked.
RequestBodySearch
:
returns
this
so that calls can be chained
Allows to control how the _source
field is returned with every hit.
You can turn off _source
retrieval by passing false
.
It also accepts one(string) or more wildcard(array) patterns to control
what parts of the _source
should be returned
An object can also be used to specify the wildcard patterns for includes
and excludes
.
RequestBodySearch
:
returns
this
so that calls can be chained
// To disable `_source` retrieval set to `false`:
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.source(false);
// The `_source` also accepts one or more wildcard patterns to control what
// parts of the `_source` should be returned:
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.source('obj.*');
// OR
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.source([ 'obj1.*', 'obj2.*' ]);
// For complete control, you can specify both `includes` and `excludes` patterns:
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.source({
'includes': [ 'obj1.*', 'obj2.*' ],
'excludes': [ '*.description' ]
});
The stored_fields
parameter is about fields that are explicitly marked as stored in the mapping.
Selectively load specific stored fields for each document represented by a search hit
using array of stored fields.
An empty array will cause only the _id
and _type
for each hit to be returned.
To disable the stored fields (and metadata fields) entirely use: _none_
RequestBodySearch
:
returns
this
so that calls can be chained
// Selectively load specific stored fields for each document
// represented by a search hit
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.storedFields(['user', 'postDate']);
// Return only the `_id` and `_type` to be returned:
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.storedFields([]);
// Disable the stored fields (and metadata fields) entirely
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.storedFields('_none_');
Computes a document property dynamically based on the supplied runtimeField
.
Added in Elasticsearch v7.11.0 Release note
(string)
Name for the computed runtime mapping field.
(RuntimeField)
Instance of RuntimeField
RequestBodySearch
:
returns
this
so that calls can be chained
const reqBody = esb.requestBodySearch()
.query(esb.matchAllQuery())
.runtimeMapping(
'sessionId-name',
esb.runtimeField(
'keyword',
`emit(doc['session_id'].value + '::' + doc['name'].value)`
)
)
// runtime fields can also be used in query aggregation
const reqBody = esb.requestBodySearch()
.query(esb.matchAllQuery())
.runtimeMapping(
'sessionId-eventName',
esb.runtimeField(
'keyword',
`emit(doc['session_id'].value + '::' + doc['eventName'].value)`,
)
)
.agg(esb.cardinalityAggregation('uniqueCount', `sessionId-eventName`)),;
Computes one or more document properties dynamically based on supplied RuntimeField
s.
Added in Elasticsearch v7.11.0 Release note
(Object)
Object with
runtimeFieldName
as key and instance of
RuntimeField
as the value.
RequestBodySearch
:
returns
this
so that calls can be chained
const fieldA = esb.runtimeField(
'keyword',
`emit(doc['session_id'].value + '::' + doc['name'].value)`
);
const reqBody = esb.requestBodySearch()
.query(esb.matchAllQuery())
.runtimeMappings({
'sessionId-name': fieldA,
})
Computes a document property dynamically based on the supplied Script
.
RequestBodySearch
:
returns
this
so that calls can be chained
const reqBody = esb.requestBodySearch()
.query(esb.matchAllQuery())
.scriptField(
'test1',
esb.script('inline', "doc['my_field_name'].value * 2").lang('painless')
)
.scriptField(
'test2',
esb.script('inline', "doc['my_field_name'].value * factor")
.lang('painless')
.params({ factor: 2.0 })
);
// Script fields can also access the actual `_source` document and extract
// specific elements to be returned from it by using `params['_source']`.
const reqBody = esb.requestBodySearch()
.query(esb.matchAllQuery())
.scriptField('test1', "params['_source']['message']");
Sets given dynamic document properties to be computed using supplied Script
s.
Object should have scriptFieldName
as key and script
as the value.
TopHitsAggregation
:
returns
this
so that calls can be chained
const reqBody = esb.requestBodySearch()
.query(esb.matchAllQuery())
.scriptFields({
test1: esb
.script('inline', "doc['my_field_name'].value * 2")
.lang('painless'),
test2: esb
.script('inline', "doc['my_field_name'].value * factor")
.lang('painless')
.params({ factor: 2.0 })
});
// Script fields can also access the actual `_source` document and extract
// specific elements to be returned from it by using `params['_source']`.
const reqBody = esb.requestBodySearch()
.query(esb.matchAllQuery())
.scriptFields({ test1: "params['_source']['message']" });
Allows to return the doc value representation of a field for each hit. Doc value fields can work on fields that are not stored.
RequestBodySearch
:
returns
this
so that calls can be chained
const reqBody = esb.requestBodySearch()
.query(esb.matchAllQuery())
.docvalueFields(['test1', 'test2']);
The post_filter
is applied to the search hits at the very end of a search request,
after aggregations have already been calculated.
(Query)
The filter to be applied after aggregation.
RequestBodySearch
:
returns
this
so that calls can be chained
const reqBody = esb.requestBodySearch()
.query(esb.boolQuery().filter(esb.termQuery('brand', 'gucci')))
.agg(esb.termsAggregation('colors', 'color'))
.agg(
esb.filterAggregation(
'color_red',
esb.termQuery('color', 'red')
).agg(esb.termsAggregation('models', 'model'))
)
.postFilter(esb.termQuery('color', 'red'));
Allows to highlight search results on one or more fields. The implementation
uses either the lucene plain
highlighter, the fast vector highlighter (fvh
)
or postings
highlighter.
Note: The postings
highlighter has been removed in elasticsearch 6.0.
The unified
highlighter outputs the same highlighting when
index_options
is set to offsets
.
(Highlight)
RequestBodySearch
:
returns
this
so that calls can be chained
const reqBody = esb.requestBodySearch()
.query(esb.matchAllQuery())
.highlight(esb.highlight('content'));
const reqBody = esb.requestBodySearch()
.query(
esb.percolateQuery('query', 'doctype').document({
message: 'The quick brown fox jumps over the lazy dog'
})
)
.highlight(esb.highlight('message'));
Rescoring 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.
(Rescore)
RequestBodySearch
:
returns
this
so that calls can be chained
query
is not an instance of
Rescore
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 reqBody = esb.requestBodySearch()
.query(esb.matchQuery('message', 'the quick brown').operator('or'))
.rescore(
esb.rescore(
100,
esb.matchPhraseQuery('message', 'the quick brown').slop(2)
)
.queryWeight(0.7)
.rescoreQueryWeight(1.2)
)
.rescore(
esb.rescore(
10,
esb.functionScoreQuery().function(
esb.scriptScoreFunction(
esb.script('inline', 'Math.log10(doc.likes.value + 2)')
)
)
).scoreMode('multiply')
);
Enables explanation for each hit on how its score was computed.
(boolean)
RequestBodySearch
:
returns
this
so that calls can be chained
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.explain(true);
Returns a version for each search hit.
(boolean)
RequestBodySearch
:
returns
this
so that calls can be chained.
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.version(true);
Allows to configure different boost level per index when searching across more than one indices. This is very handy when hits coming from one index matter more than hits coming from another index.
Alias for method indicesBoost
.
RequestBodySearch
:
returns
this
so that calls can be chained.
const reqBody = esb.requestBodySearch()
.indexBoost('alias1', 1.4)
.indexBoost('index*', 1.3);
Allows to configure different boost level per index when searching across more than one indices. This is very handy when hits coming from one index matter more than hits coming from another index.
RequestBodySearch
:
returns
this
so that calls can be chained.
const reqBody = esb.requestBodySearch()
.indicesBoost('alias1', 1.4)
.indicesBoost('index*', 1.3);
Exclude documents which have a _score
less than the minimum specified in min_score
.
(number)
RequestBodySearch
:
returns
this
so that calls can be chained.
const reqBody = esb.requestBodySearch()
.query(esb.termQuery('user', 'kimchy'))
.minScore(0.5);
Allows to collapse search results based on field values. The collapsing is done by selecting only the top sorted document per collapse key.
The field used for collapsing must be a single valued keyword
or numeric
field with doc_values
activated
(string)
(InnerHits?)
Allows to expand each collapsed top hits.
(number?)
The number of concurrent
requests allowed to retrieve the inner_hits' per group
RequestBodySearch
:
returns
this
so that calls can be chained.
innerHits
is not an instance of
InnerHits
const reqBody = esb.requestBodySearch()
.query(esb.matchQuery('message', 'elasticsearch'))
.collapse('user')
.sort(esb.sort('likes'))
.from(10);
// Expand each collapsed top hits with the `inner_hits` option:
const reqBody = esb.requestBodySearch()
.query(esb.matchQuery('message', 'elasticsearch'))
.collapse(
'user',
esb.innerHits('last_tweets')
.size(5)
.sort(esb.sort('date', 'asc')),
4
)
.sort(esb.sort('likes'))
.from(10);
Allows to use the results from the previous page to help the retrieval
of the next page. The search_after
parameter provides a live cursor.
The parameter from
must be set to 0
(or -1
) when search_after
is used.
RequestBodySearch
:
returns
this
so that calls can be chained.
const reqBody = esb.requestBodySearch()
.size(10)
.query(esb.matchQuery('message', 'elasticsearch'))
.searchAfter(1463538857, 'tweet#654323')
.sorts([esb.sort('date', 'asc'), esb.sort('_uid', 'desc')]);
These classes allow creation and manipulation of objects which map to elasticsearch DSL for 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.
(string)
Sets the query name.
(string)
Query
:
returns
this
so that calls can be chained.
const boolQry = esb.boolQuery()
.should([
esb.matchQuery('name.first', 'shay').name('first'),
esb.matchQuery('name.last', 'banon').name('last')
])
.filter(esb.termsQuery('name.last', ['banon', 'kimchy']).name('test'));
The most simple query, which matches all documents, giving them all a _score
of 1.0
.
Extends Query
const qry = esb.matchAllQuery().boost(1.2);
The inverse of the match_all
query, which matches no documents.
Extends Query
const qry = esb.matchNoneQuery();
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.
Extends Query
Set the analyzer to control which analyzer will perform the analysis process on the text
(string)
FullTextQueryBase
:
returns
this
so that calls can be chained.
const qry = esb.matchPhraseQuery('message', 'this is a test')
.analyzer('my_analyzer');
const qry = esb.multiMatchQuery(['first', 'last', '*.edge'], 'Jon')
.type('cross_fields')
.analyzer('standard');
Sets the value controlling how many "should" clauses in the resulting boolean
query should match. It can be an absolute value (2), a percentage (30%)
or a combination of both. For Common Terms Query when specifying different
minimum_should_match
for low and high frequency terms, an object with the
keys low_freq
and high_freq
can be used.
FullTextQueryBase
:
returns
this
so that calls can be chained.
const qry = esb.commonTermsQuery('body', 'nelly the elephant as a cartoon')
.minimumShouldMatch(2)
.cutoffFrequency(0.001);
Sets the query string.
(string)
FullTextQueryBase
:
returns
this
so that calls can be chained.
const qry = esb.queryStringQuery()
.query('city.\\*:(this AND that OR thus)')
.useDisMax(true);
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.
Extends FullTextQueryBase
(string)
(string?)
The document field to query against
(string?)
The query string
Sets the field to search on.
(string)
MonoFieldQueryBase
:
returns
this
so that calls can be chained.
match
query accepts text/numerics/dates, analyzes them, and constructs a query.
Extends MonoFieldQueryBase
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');
The operator to be used in the boolean query which is constructed
by analyzing the text provided. The operator
flag can be set to or
or
and
to control the boolean clauses (defaults to or
).
MatchQuery
:
returns
this
so that calls can be chained.
Sets the lenient
parameter which allows to ignore exceptions caused
by data-type mismatches such as trying to query a numeric field with a
text query string when set to true
.
MatchQuery
:
returns
this
so that calls can be chained.
Sets the fuzziness
parameter which is interpreted as a Levenshtein Edit Distance —
the number of one character changes that need to be made to one string to make it
the same as another string.
MatchQuery
:
returns
this
so that calls can be chained.
Sets the prefix length for a fuzzy prefix MatchQuery
(number)
MatchQuery
:
returns
this
so that calls can be chained.
Sets the max expansions for a fuzzy prefix MatchQuery
(number)
MatchQuery
:
returns
this
so that calls can be chained.
Sets the rewrite method. Valid values are:
constant_score
- tries to pick the best constant-score rewrite
method based on term and document counts from the query.
Synonyms - constant_score_auto
, constant_score_filter
scoring_boolean
- translates each term into boolean should and
keeps the scores as computed by the query
constant_score_boolean
- same as scoring_boolean
, expect no scores
are computed.
constant_score_filter
- first creates a private Filter, by visiting
each term in sequence and marking all docs for that term
top_terms_boost_N
- first translates each term into boolean should
and scores are only computed as the boost using the top N
scoring terms. Replace N with an integer value.
top_terms_N
- first translates each term into boolean should
and keeps the scores as computed by the query. Only the top N
scoring terms are used. Replace N with an integer value.
Default is constant_score
.
Note: The deprecated multi term rewrite parameters constant_score_auto
,
constant_score_filter
(synonyms for constant_score
) have been removed
in elasticsearch 6.0.
This is an advanced option, use with care.
(string)
The rewrite method as a string.
MatchQuery
:
returns
this
so that calls can be chained.
rewrite
method is not valid.
Sets the fuzzy rewrite method. Valid values are:
constant_score
- tries to pick the best constant-score rewrite
method based on term and document counts from the query.
Synonyms - constant_score_auto
, constant_score_filter
scoring_boolean
- translates each term into boolean should and
keeps the scores as computed by the query
constant_score_boolean
- same as scoring_boolean
, expect no scores
are computed.
constant_score_filter
- first creates a private Filter, by visiting
each term in sequence and marking all docs for that term
top_terms_boost_N
- first translates each term into boolean should
and scores are only computed as the boost using the top N
scoring terms. Replace N with an integer value.
top_terms_N
- first translates each term into boolean should
and keeps the scores as computed by the query. Only the top N
scoring terms are used. Replace N with an integer value.
Default is constant_score
.
This is an advanced option, use with care.
Note: The deprecated multi term rewrite parameters constant_score_auto
,
constant_score_filter
(synonyms for constant_score
) have been removed
in elasticsearch 6.0.
(string)
The rewrite method as a string.
MatchQuery
:
returns
this
so that calls can be chained.
fuzzy_rewrite
method is not valid.
Fuzzy transpositions (ab
→ ba
) are allowed by default but can be disabled
by setting fuzzy_transpositions
to false.
(boolean)
MatchQuery
:
returns
this
so that calls can be chained.
If the analyzer used removes all tokens in a query like a stop
filter does,
the default behavior is to match no documents at all. In order to change that
the zero_terms_query
option can be used, which accepts none
(default) and all
which corresponds to a match_all
query.
MatchQuery
:
returns
this
so that calls can be chained.
const qry = esb.matchQuery('message', 'to be or not to be')
.operator('and')
.zeroTermsQuery('all');
Allows specifying an absolute or relative document frequency where high frequency
terms are moved into an optional subquery and are only scored if one of the
low frequency (below the cutoff) terms in the case of an or
operator or
all of the low frequency terms in the case of an and
operator match.
(number)
It can either be relative to the total number of documents
if in the range
[0..1)
or absolute if greater or equal to
1.0
.
MatchQuery
:
returns
this
so that calls can be chained.
const qry = esb.matchQuery('message', 'to be or not to be')
.cutoffFrequency(0.001);
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.
Extends MonoFieldQueryBase
(string)
(string)
(string?)
The document field to query against
(string?)
The query string
MatchPhraseQueryBase
Configures the slop
(default is 0) for matching terms in any order.
Transposed terms have a slop of 2.
(number)
A positive integer value, defaults is 0.
MatchPhraseQueryBase
:
returns
this
so that calls can be chained.
The match_phrase
query analyzes the text and creates a phrase
query out of
the analyzed text.
Extends MatchPhraseQueryBase
const qry = esb.matchPhraseQuery('message', 'to be or not to be');
Extends MatchPhraseQueryBase
const qry = esb.matchPhrasePrefixQuery('message', 'quick brown f');
Control to how many prefixes the last term will be expanded.
(number)
Defaults to 50.
MatchPhrasePrefixQuery
:
returns
this
so that calls can be chained.
const qry = esb.matchPhrasePrefixQuery('message', 'quick brown f')
.maxExpansions(10);
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.
Extends FullTextQueryBase
const qry = esb.multiMatchQuery(['subject', 'message'], 'this is a test');
Appends given field to the list of fields to search against.
Fields can be specified with wildcards.
Individual fields can be boosted with the caret (^) notation.
Example - "subject^3"
(string)
One of the fields to be queried
MultiMatchQuery
:
returns
this
so that calls can be chained.
Appends given fields to the list of fields to search against. Fields can be specified with wildcards. Individual fields can be boosted with the caret (^) notation.
MultiMatchQuery
:
returns
this
so that calls can be chained.
// Boost individual fields with caret `^` notation
const qry = esb.multiMatchQuery(['subject^3', 'message'], 'this is a test');
// Specify fields with wildcards
const qry = esb.multiMatchQuery(['title', '*_name'], 'Will Smith');
Sets the type of multi match query. Valid values are:
best_fields
- (default) Finds documents which match any field,
but uses the _score
from the best field.
most_fields
- Finds documents which match any field and combines
the _score
from each field.
cross_fields
- Treats fields with the same analyzer
as though
they were one big field. Looks for each word in any field
phrase
- Runs a match_phrase
query on each field and combines
the _score
from each field.
phrase_prefix
- Runs a match_phrase_prefix
query on each field
and combines the _score
from each field.
bool_prefix
- (added in v7.2) Creates a match_bool_prefix query on each field and
combines the _score from each field.
(string)
Can be one of
best_fields
,
most_fields
,
cross_fields
,
phrase
,
phrase_prefix
and
bool_prefix
. Default is
best_fields
.
MultiMatchQuery
:
returns
this
so that calls can be chained.
// Find the single best matching field
const qry = esb.multiMatchQuery(['subject', 'message'], 'brown fox')
.type('best_fields')
.tieBreaker(0.3);
// Query multiple fields analyzed differently for the same text
const qry = esb.multiMatchQuery(
['title', 'title.original', 'title.shingles'],
'quick brown fox'
).type('most_fields');
// Run a `match_phrase_prefix` query on multiple fields
const qry = esb.multiMatchQuery(
['subject', 'message'],
'quick brown f'
).type('phrase_prefix');
// All terms must be present in at least one field for document to match
const qry = esb.multiMatchQuery(['first_name', 'last_name'], 'Will Smith')
.type('cross_fields')
.operator('and');
The tie breaker value. The tie breaker capability allows results
that include the same term in multiple fields to be judged better than
results that include this term in only the best of those multiple
fields, without confusing this with the better case of two different
terms in the multiple fields. Default: 0.0
.
(number)
MultiMatchQuery
:
returns
this
so that calls can be chained.
The operator to be used in the boolean query which is constructed
by analyzing the text provided. The operator
flag can be set to or
or
and
to control the boolean clauses (defaults to or
).
MultiMatchQuery
:
returns
this
so that calls can be chained.
Sets the lenient
parameter which allows to ignore exceptions caused
by data-type mismatches such as trying to query a numeric field with a
text query string when set to true
.
MultiMatchQuery
:
returns
this
so that calls can be chained.
Configures the slop
(default is 0) for matching terms in any order.
Transposed terms have a slop of 2.
(number)
A positive integer value, defaults is 0.
MultiMatchQuery
:
returns
this
so that calls can be chained.
Sets the fuzziness
parameter which is interpreted as a Levenshtein Edit Distance —
the number of one character changes that need to be made to one string to make it
the same as another string.
The fuzziness
parameter cannot be used with the phrase
, phrase_prefix
or cross_fields
type.
MultiMatchQuery
:
returns
this
so that calls can be chained.
Sets the prefix length for a fuzzy prefix MultiMatchQuery
(number)
MultiMatchQuery
:
returns
this
so that calls can be chained.
Sets the max expansions for a fuzzy prefix MultiMatchQuery
(number)
MultiMatchQuery
:
returns
this
so that calls can be chained.
Sets the rewrite method. Valid values are:
constant_score
- tries to pick the best constant-score rewrite
method based on term and document counts from the query.
Synonyms - constant_score_auto
, constant_score_filter
scoring_boolean
- translates each term into boolean should and
keeps the scores as computed by the query
constant_score_boolean
- same as scoring_boolean
, expect no scores
are computed.
constant_score_filter
- first creates a private Filter, by visiting
each term in sequence and marking all docs for that term
top_terms_boost_N
- first translates each term into boolean should
and scores are only computed as the boost using the top N
scoring terms. Replace N with an integer value.
top_terms_N
- first translates each term into boolean should
and keeps the scores as computed by the query. Only the top N
scoring terms are used. Replace N with an integer value.
Default is constant_score
.
This is an advanced option, use with care.
Note: The deprecated multi term rewrite parameters constant_score_auto
,
constant_score_filter
(synonyms for constant_score
) have been removed
in elasticsearch 6.0.
(string)
The rewrite method as a string.
MultiMatchQuery
:
returns
this
so that calls can be chained.
rewrite
method is not valid.
Sets the fuzzy rewrite method. Valid values are:
constant_score
- tries to pick the best constant-score rewrite
method based on term and document counts from the query.
Synonyms - constant_score_auto
, constant_score_filter
scoring_boolean
- translates each term into boolean should and
keeps the scores as computed by the query
constant_score_boolean
- same as scoring_boolean
, expect no scores
are computed.
constant_score_filter
- first creates a private Filter, by visiting
each term in sequence and marking all docs for that term
top_terms_boost_N
- first translates each term into boolean should
and scores are only computed as the boost using the top N
scoring terms. Replace N with an integer value.
top_terms_N
- first translates each term into boolean should
and keeps the scores as computed by the query. Only the top N
scoring terms are used. Replace N with an integer value.
Default is constant_score
.
This is an advanced option, use with care.
Note: The deprecated multi term rewrite parameters constant_score_auto
,
constant_score_filter
(synonyms for constant_score
) have been removed
in elasticsearch 6.0.
(string)
The rewrite method as a string.
MultiMatchQuery
:
returns
this
so that calls can be chained.
fuzzy_rewrite
method is not valid.
If the analyzer used removes all tokens in a query like a stop
filter does,
the default behavior is to match no documents at all. In order to change that
the zero_terms_query
option can be used, which accepts none
(default) and all
which corresponds to a match_all
query.
MultiMatchQuery
:
returns
this
so that calls can be chained.
Allows specifying an absolute or relative document frequency where high frequency
terms are moved into an optional subquery and are only scored if one of the
low frequency (below the cutoff) terms in the case of an or
operator or
all of the low frequency terms in the case of an and
operator match.
(number)
It can either be relative to the total number of documents
if in the range
[0..1)
or absolute if greater or equal to
1.0
.
MultiMatchQuery
:
returns
this
so that calls can be chained.
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.
Extends MonoFieldQueryBase
const qry = esb.commonTermsQuery('body','this is bonsai cool')
.cutoffFrequency(0.001);
Allows specifying an absolute or relative document frequency where high frequency
terms are moved into an optional subquery and are only scored if one of the
low frequency (below the cutoff) terms in the case of an or
operator or
all of the low frequency terms in the case of an and
operator match.
(number)
It can either be relative to the total number of documents
if in the range
[0..1)
or absolute if greater or equal to
1.0
.
CommonTermsQuery
:
returns
this
so that calls can be chained.
The operator to be used on low frequency terms in the boolean query
which is constructed by analyzing the text provided. The operator
flag
can be set to or
or and
to control the boolean clauses (defaults to or
).
CommonTermsQuery
:
returns
this
so that calls can be chained.
const qry = esb.commonTermsQuery('body', 'nelly the elephant as a cartoon')
.lowFreqOperator('and')
.cutoffFrequency(0.001);
The operator to be used on high frequency terms in the boolean query
which is constructed by analyzing the text provided. The operator
flag
can be set to or
or and
to control the boolean clauses (defaults to or
).
CommonTermsQuery
:
returns
this
so that calls can be chained.
Sets the value controlling how many "should" clauses in the resulting boolean query should match for low frequency terms. It can be an absolute value (2), a percentage (30%) or a combination of both.
CommonTermsQuery
:
returns
this
so that calls can be chained.
const qry = esb.commonTermsQuery('body', 'nelly the elephant as a cartoon')
.lowFreq(2)
.highFreq(3)
.cutoffFrequency(0.001);
Sets the value controlling how many "should" clauses in the resulting boolean query should match for high frequency terms. It can be an absolute value (2), a percentage (30%) or a combination of both.
CommonTermsQuery
:
returns
this
so that calls can be chained.
const qry = esb.commonTermsQuery('body', 'nelly the elephant as a cartoon')
.lowFreq(2)
.highFreq(3)
.cutoffFrequency(0.001);
Enables or disables similarity coordinate scoring of documents
commoning the CommonTermsQuery
. Default: false
.
NOTE: This has been removed in elasticsearch 6.0. If provided, it will be ignored and a deprecation warning will be issued.
(boolean)
CommonTermsQuery
:
returns
this
so that calls can be chained.
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.
Extends FullTextQueryBase
Appends given field to the list of fields to search against. Fields can be specified with wildcards.
Individual fields can be boosted with the caret (^) notation.
Example - "subject^3"
(string)
One of the fields to be queried
QueryStringQueryBase
:
returns
this
so that calls can be chained.
const qry = esb.queryStringQuery('this AND that OR thus')
.field('city.*')
.useDisMax(true);
const qry = esb.simpleQueryStringQuery('foo bar -baz').field('content');
Appends given fields to the list of fields to search against. Fields can be specified with wildcards.
Individual fields can be boosted with the caret (^) notation.
Example - [ "subject^3", "message" ]
QueryStringQueryBase
:
returns
this
so that calls can be chained.
const qry = esb.queryStringQuery('this AND that')
.fields(['content', 'name'])
const qry = esb.simpleQueryStringQuery('foo bar baz')
.fields(['content', 'name.*^5']);
The default operator used if no explicit operator is specified.
For example, with a default operator of OR
, the query capital of Hungary
is translated to capital OR of OR Hungary
, and with default operator of AND,
the same query is translated to capital AND of AND Hungary
.
The default value is OR.
QueryStringQueryBase
:
returns
this
so that calls can be chained.
By default, wildcards terms in a query string are not analyzed.
By setting this value to true
, a best effort will be made to analyze those as well.
(boolean)
QueryStringQueryBase
:
returns
this
so that calls can be chained.
Sets the lenient
parameter which allows to ignore exceptions caused
by data-type mismatches such as trying to query a numeric field with a
text query string when set to true
.
QueryStringQueryBase
:
returns
this
so that calls can be chained.
A suffix to append to fields for quoted parts of the query string. This allows to use a field that has a different analysis chain for exact matching.
(string)
QueryStringQueryBase
:
returns
this
so that calls can be chained.
Perform the query on all fields detected in the mapping that can be queried.
Will be used by default when the _all
field is disabled and
no default_field
is specified (either in the index settings or
in the request body) and no fields
are specified.
(boolean)
QueryStringQueryBase
:
returns
this
so that calls can be chained.
A query that uses a query parser in order to parse its content.
Extends QueryStringQueryBase
(string?)
The actual query to be parsed.
const qry = esb.queryStringQuery('this AND that OR thus')
.defaultField('content');
The default field for query terms if no prefix field is specified.
Defaults to the index.query.default_field
index settings, which
in turn defaults to _all
.
(string)
QueryStringQuery
:
returns
this
so that calls can be chained.
When set, *
or ?
are allowed as the first character. Defaults to true
.
(boolean)
QueryStringQuery
:
returns
this
so that calls can be chained.
Set to true to enable position increments in result queries. Defaults to true.
(boolean)
QueryStringQuery
:
returns
this
so that calls can be chained.
Controls the number of terms fuzzy queries will expand to. Defaults to 50
.
(number)
QueryStringQuery
:
returns
this
so that calls can be chained.
Sets the fuzziness
parameter which is interpreted as a Levenshtein Edit Distance —
the number of one character changes that need to be made to one string to make it
the same as another string. Defaults to AUTO
.
QueryStringQuery
:
returns
this
so that calls can be chained.
Set the prefix length for fuzzy queries. Default is 0
.
(number)
QueryStringQuery
:
returns
this
so that calls can be chained.
Sets the rewrite method. Valid values are:
constant_score
- tries to pick the best constant-score rewrite
method based on term and document counts from the query.
Synonyms - constant_score_auto
, constant_score_filter
scoring_boolean
- translates each term into boolean should and
keeps the scores as computed by the query
constant_score_boolean
- same as scoring_boolean
, expect no scores
are computed.
constant_score_filter
- first creates a private Filter, by visiting
each term in sequence and marking all docs for that term
top_terms_boost_N
- first translates each term into boolean should
and scores are only computed as the boost using the top N
scoring terms. Replace N with an integer value.
top_terms_N
- first translates each term into boolean should
and keeps the scores as computed by the query. Only the top N
scoring terms are used. Replace N with an integer value.
Default is constant_score
.
This is an advanced option, use with care.
Note: The deprecated multi term rewrite parameters constant_score_auto
,
constant_score_filter
(synonyms for constant_score
) have been removed
in elasticsearch 6.0.
(string)
The rewrite method as a string.
QueryStringQuery
:
returns
this
so that calls can be chained.
rewrite
method is not valid.
Sets the fuzzy rewrite method. Valid values are:
constant_score
- tries to pick the best constant-score rewrite
method based on term and document counts from the query.
Synonyms - constant_score_auto
, constant_score_filter
scoring_boolean
- translates each term into boolean should and
keeps the scores as computed by the query
constant_score_boolean
- same as scoring_boolean
, expect no scores
are computed.
constant_score_filter
- first creates a private Filter, by visiting
each term in sequence and marking all docs for that term
top_terms_boost_N
- first translates each term into boolean should
and scores are only computed as the boost using the top N
scoring terms. Replace N with an integer value.
top_terms_N
- first translates each term into boolean should
and keeps the scores as computed by the query. Only the top N
scoring terms are used. Replace N with an integer value.
Default is constant_score
.
This is an advanced option, use with care.
Note: The deprecated multi term rewrite parameters constant_score_auto
,
constant_score_filter
(synonyms for constant_score
) have been removed
in elasticsearch 6.0.
(string)
The rewrite method as a string.
QueryStringQuery
:
returns
this
so that calls can be chained.
fuzzy_rewrite
method is not valid.
Sets the default slop for phrases. If zero, then exact phrase matches are required. Default value is 0.
(number)
A positive integer value, defaults is 0.
QueryStringQuery
:
returns
this
so that calls can be chained.
Auto generate phrase queries. Defaults to false
.
Note: This parameter has been removed in elasticsearch 6.0. If provided, it will be ignored and issue a deprecation warning.
(boolean)
QueryStringQuery
:
returns
this
so that calls can be chained.
Limit on how many automaton states regexp queries are allowed to create. This protects against too-difficult (e.g. exponentially hard) regexps. Defaults to 10000.
(number)
QueryStringQuery
:
returns
this
so that calls can be chained.
Time Zone to be applied to any range query related to dates.
(string)
QueryStringQuery
:
returns
this
so that calls can be chained.
Whether query text should be split on whitespace prior to analysis.
Instead the queryparser would parse around only real operators.
Default is false
. It is not allowed to set this option to false
if auto_generate_phrase_queries
is already set to true
.
Note: This parameter has been removed in elasticsearch 6.0. If provided,
it will be ignored and issue a deprecation warning. The query_string
query now splits on operator only.
(string)
QueryStringQuery
:
returns
this
so that calls can be chained.
Should the queries be combined using dis_max
(set it to true
),
or a bool query (set it to false
). Defaults to true
.
Note: This parameter has been removed in elasticsearch 6.0. If provided,
it will be ignored and issue a deprecation warning. The tie_breaker
parameter must be used instead.
(boolean)
QueryStringQuery
:
returns
this
so that calls can be chained.
const qry = esb.queryStringQuery('this AND that OR thus')
.fields(['content', 'name^5'])
.useDisMax(true);
When using dis_max
, the disjunction max tie breaker. Defaults to 0
.
(number)
QueryStringQuery
:
returns
this
so that calls can be chained.
Sets the quote analyzer name used to analyze the query
when in quoted text.
(string)
A valid analyzer name.
QueryStringQuery
:
returns
this
so that calls can be chained.
If they query string should be escaped or not.
(boolean)
QueryStringQuery
:
returns
this
so that calls can be chained.
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.
Extends QueryStringQueryBase
(string?)
The query string
const qry = esb.simpleQueryStringQuery(
'"fried eggs" +(eggplant | potato) -frittata'
)
.analyzer('snowball')
.fields(['body^5', '_all'])
.defaultOperator('and');
simple_query_string
support multiple flags to specify which parsing features
should be enabled. It is specified as a |
-delimited string.
(string)
|
delimited string. The available flags are:
ALL
,
NONE
,
AND
,
OR
,
NOT
,
PREFIX
,
PHRASE
,
PRECEDENCE
,
ESCAPE
,
WHITESPACE
,
FUZZY
,
NEAR
, and
SLOP
.
SimpleQueryStringQuery
:
returns
this
so that calls can be chained.
const qry = esb.simpleQueryStringQuery('foo | bar + baz*')
.flags('OR|AND|PREFIX');
The ValueTermQueryBase
provides support for common options used across
various term level query implementations.
Extends Query
(string)
(string?)
The document field to query against
(string?)
The query string
Sets the field to search on.
(string)
ValueTermQueryBase
:
returns
this
so that calls can be chained.
Sets the query string.
ValueTermQueryBase
:
returns
this
so that calls can be chained.
Allows ASCII case insensitive matching of the value with the indexed field values when set to true.
NOTE: Only available in Elasticsearch v7.10.0+
(boolean
= true
)
ValueTermQueryBase
:
returns
this
so that calls can be chained.
The term
query finds documents that contain the exact term specified
in the inverted index.
Extends ValueTermQueryBase
const termQry = esb.termQuery('user', 'Kimchy');
Filters documents that have fields that match any of the provided terms (not analyzed).
Extends Query
const qry = esb.constantScoreQuery(
esb.termsQuery('user', ['kimchy', 'elasticsearch'])
);
const qry = esb.termsQuery('user')
.index('users')
.type('user')
.id(2)
.path('followers');
Sets the field to search on.
(string)
TermsQuery
:
returns
this
so that calls can be chained.
Append given value to list of values to run Terms Query with.
TermsQuery
:
returns
this
so that calls can be chained
Specifies the values to run query for.
TermsQuery
:
returns
this
so that calls can be chained
values
is not an instance of Array
Convenience method for setting term lookup options.
Valid options are index
, type
, id
, path
and routing
TermsQuery
:
returns
this
so that calls can be chained
The index to fetch the term values from. Defaults to the current index.
Note: The index
parameter in the terms filter, used to look up terms in
a dedicated index is mandatory in elasticsearch 6.0. Previously, the
index defaulted to the index the query was executed on. In 6.0, this
index must be explicitly set in the request.
(string)
The index to fetch the term values from.
Defaults to the current index.
TermsQuery
:
returns
this
so that calls can be chained
The type to fetch the term values from.
(string)
TermsQuery
:
returns
this
so that calls can be chained
The id of the document to fetch the term values from.
(string)
TermsQuery
:
returns
this
so that calls can be chained
The field specified as path to fetch the actual values for the terms
filter.
(string)
TermsQuery
:
returns
this
so that calls can be chained
A custom routing value to be used when retrieving the external terms doc.
(string)
TermsQuery
:
returns
this
so that calls can be chained
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.
NOTE: This query was added in elasticsearch v6.1.
Extends Query
const qry = esb.termsSetQuery('codes', ['abc', 'def', 'ghi'])
.minimumShouldMatchField('required_matches')
Sets the field to search on.
(string)
TermsSetQuery
:
returns
this
so that calls can be chained.
Append given term to set of terms to run Terms Set Query with.
TermsSetQuery
:
returns
this
so that calls can be chained
Specifies the terms to run query for.
TermsSetQuery
:
returns
this
so that calls can be chained
terms
is not an instance of Array
Controls the number of terms that must match per document.
(string)
TermsSetQuery
:
returns
this
so that calls can be chained
Sets the script
for query. It controls how many terms are required to
match in a more dynamic way.
The params.num_terms
parameter is available in the script to indicate
the number of terms that have been specified.
ScriptQuery
:
returns
this
so that calls can be chained.
const qry = esb.termsSetQuery('codes', ['abc', 'def', 'ghi'])
.minimumShouldMatchScript({
source: "Math.min(params.num_terms, doc['required_matches'].value)"
})
Interface-like class used to group and identify various implementations of multi term 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.
Extends ValueTermQueryBase
Matches documents with fields that have terms within a certain range.
Extends MultiTermQueryBase
(string?)
const qry = esb.rangeQuery('age')
.gte(10)
.lte(20)
.boost(2.0);
const qry = esb.rangeQuery('date').gte('now-1d/d').lt('now/d');
Greater-than or equal to
RangeQuery
:
returns
this
so that calls can be chained.
Less-than or equal to
RangeQuery
:
returns
this
so that calls can be chained.
Greater-than
RangeQuery
:
returns
this
so that calls can be chained.
Less-than
RangeQuery
:
returns
this
so that calls can be chained.
The lower bound. Defaults to start from the first.
RangeQuery
:
returns
this
so that calls can be chained.
The upper bound. Defaults to unbounded.
RangeQuery
:
returns
this
so that calls can be chained.
Should the first from (if set) be inclusive or not. Defaults to true
RangeQuery
:
returns
this
so that calls can be chained.
Should the last to (if set) be inclusive or not. Defaults to true
.
RangeQuery
:
returns
this
so that calls can be chained.
Time Zone to be applied to any range query related to dates.
(string)
RangeQuery
:
returns
this
so that calls can be chained.
Sets the format expression for parsing the upper and lower bounds. If no format is specified, then it will use the first format specified in the field mapping.
(string)
Format for parsing upper and lower bounds.
RangeQuery
:
returns
this
so that calls can be chained
const qry = esb.rangeQuery('born')
.gte('01/01/2012')
.lte('2013')
.format('dd/MM/yyyy||yyyy');
Sets the relationship between Query and indexed data that will be used to determine if a Document should be matched or not.
RangeQuery
:
returns
this
so that calls can be chained
Returns documents that have at least one non-null
value in the original field
Extends Query
(string?)
const qry = esb.existsQuery('user');
const qry = esb.boolQuery().mustNot(esb.existsQuery('user'));
Sets the field to search on.
(string)
ExistsQuery
:
returns
this
so that calls can be chained.
Matches documents that have fields containing terms with a specified prefix (not analyzed).
Extends MultiTermQueryBase
const qry = esb.prefixQuery('user', 'ki').boost(2.0);
Sets the rewrite method. Valid values are:
constant_score
- tries to pick the best constant-score rewrite
method based on term and document counts from the query.
Synonyms - constant_score_auto
, constant_score_filter
scoring_boolean
- translates each term into boolean should and
keeps the scores as computed by the query
constant_score_boolean
- same as scoring_boolean
, expect no scores
are computed.
constant_score_filter
- first creates a private Filter, by visiting
each term in sequence and marking all docs for that term
top_terms_boost_N
- first translates each term into boolean should
and scores are only computed as the boost using the top N
scoring terms. Replace N with an integer value.
top_terms_N
- first translates each term into boolean should
and keeps the scores as computed by the query. Only the top N
scoring terms are used. Replace N with an integer value.
Default is constant_score
.
This is an advanced option, use with care.
Note: The deprecated multi term rewrite parameters constant_score_auto
,
constant_score_filter
(synonyms for constant_score
) have been removed
in elasticsearch 6.0.
(string)
The rewrite method as a string.
PrefixQuery
:
returns
this
so that calls can be chained.
rewrite
method is not valid.
Matches documents that have fields matching a wildcard expression (not analyzed).
Extends MultiTermQueryBase
const qry = esb.wildcardQuery('user', 'ki*y').boost(2.0);
Allow case insensitive matching or not (added in 7.10.0). Defaults to false.
(boolean)
RegexpQuery
:
returns
this
so that calls can be chained.
const qry = esb.wildcardQuery('user', 'ki*y')
.caseInsensitive(true);
Sets the rewrite method. Valid values are:
constant_score
- tries to pick the best constant-score rewrite
method based on term and document counts from the query.
Synonyms - constant_score_auto
, constant_score_filter
scoring_boolean
- translates each term into boolean should and
keeps the scores as computed by the query
constant_score_boolean
- same as scoring_boolean
, expect no scores
are computed.
constant_score_filter
- first creates a private Filter, by visiting
each term in sequence and marking all docs for that term
top_terms_boost_N
- first translates each term into boolean should
and scores are only computed as the boost using the top N
scoring terms. Replace N with an integer value.
top_terms_N
- first translates each term into boolean should
and keeps the scores as computed by the query. Only the top N
scoring terms are used. Replace N with an integer value.
Default is constant_score
.
This is an advanced option, use with care.
Note: The deprecated multi term rewrite parameters constant_score_auto
,
constant_score_filter
(synonyms for constant_score
) have been removed
in elasticsearch 6.0.
(string)
The rewrite method as a string.
WildcardQuery
:
returns
this
so that calls can be chained.
rewrite
method is not valid.
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.
Extends MultiTermQueryBase
const qry = esb.regexpQuery('name.first', 's.*y').boost(1.2);
Set special flags. Possible flags are ALL
(default),
ANYSTRING
, COMPLEMENT
, EMPTY
, INTERSECTION
, INTERVAL
, or NONE
.
(string)
|
separated flags. Possible flags are
ALL
(default),
ANYSTRING
,
COMPLEMENT
,
EMPTY
,
INTERSECTION
,
INTERVAL
, or
NONE
.
RegexpQuery
:
returns
this
so that calls can be chained.
const qry = esb.regexpQuery('name.first', 's.*y')
.flags('INTERSECTION|COMPLEMENT|EMPTY');
Allow case insensitive matching or not (added in 7.10.0). Defaults to false.
(boolean)
RegexpQuery
:
returns
this
so that calls can be chained.
const qry = esb.regexpQuery('name.first', 's.*y')
.caseInsensitive(true);
Limit on how many automaton states regexp queries are allowed to create. This protects against too-difficult (e.g. exponentially hard) regexps. Defaults to 10000.
(number)
RegexpQuery
:
returns
this
so that calls can be chained.
const qry = esb.regexpQuery('name.first', 's.*y')
.flags('INTERSECTION|COMPLEMENT|EMPTY')
.maxDeterminizedStates(20000);
Sets the rewrite method. Valid values are:
constant_score
- tries to pick the best constant-score rewrite
method based on term and document counts from the query.
Synonyms - constant_score_auto
, constant_score_filter
scoring_boolean
- translates each term into boolean should and
keeps the scores as computed by the query
constant_score_boolean
- same as scoring_boolean
, expect no scores
are computed.
constant_score_filter
- first creates a private Filter, by visiting
each term in sequence and marking all docs for that term
top_terms_boost_N
- first translates each term into boolean should
and scores are only computed as the boost using the top N
scoring terms. Replace N with an integer value.
top_terms_N
- first translates each term into boolean should
and keeps the scores as computed by the query. Only the top N
scoring terms are used. Replace N with an integer value.
Default is constant_score
.
This is an advanced option, use with care.
Note: The deprecated multi term rewrite parameters constant_score_auto
,
constant_score_filter
(synonyms for constant_score
) have been removed
in elasticsearch 6.0.
(string)
The rewrite method as a string.
RegexpQuery
:
returns
this
so that calls can be chained.
rewrite
method is not valid.
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.
Extends MultiTermQueryBase
const qry = esb.fuzzyQuery('user', 'ki');
// More advanced settings
const qry = esb.fuzzyQuery('user', 'ki')
.fuzziness(2)
.prefixLength(0)
.maxExpansions(100)
.boost(1.0);
Sets the fuzziness
parameter which is interpreted as a Levenshtein Edit Distance —
the number of one character changes that need to be made to one string to make it
the same as another string.
FuzzyQuery
:
returns
this
so that calls can be chained.
The number of initial characters which will not be “fuzzified”.
This helps to reduce the number of terms which must be examined. Defaults to 0
.
FuzzyQuery
:
returns
this
so that calls can be chained.
The maximum number of terms that the fuzzy query will expand to. Defaults to 50
.
FuzzyQuery
:
returns
this
so that calls can be chained.
Transpositions (ab
→ ba
) are allowed by default but can be disabled
by setting transpositions
to false.
(boolean)
FuzzyQuery
:
returns
this
so that calls can be chained.
Filters documents matching the provided document / mapping type.
Extends Query
(string?)
The elasticsearch doc type
const qry = esb.typeQuery('my_type');
Filters documents that only have the provided ids. Note, this query uses the _uid field.
Extends Query
const qry = esb.idsQuery('my_type', ['1', '4', '100']);
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.
Extends Query
(Query?)
Query to filter on.
const qry = esb.constantScoreQuery(esb.termQuery('user', 'kimchy')).boost(1.2);
Adds the query to apply a constant score to.
(Query)
Query to filter on.
ConstantScoreQuery
:
returns
this
so that calls can be chained.
Adds the query to apply a constant score to.
Alias for method filter
.
Note: This parameter has been removed in elasticsearch 6.0. Use filter
instead.
(Query)
Query to filter on.
ConstantScoreQuery
:
returns
this
so that calls can be chained.
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.
Extends Query
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);
Adds filter
query to boolean container.
The clause (query) must appear in matching documents. However unlike must
the score
of the query will be ignored. Filter clauses are executed in filter context, meaning that
scoring is ignored and clauses are considered for caching.
BoolQuery
:
returns
this
so that calls can be chained.
Query
// Assign score of `0` to all documents
const qry = esb.boolQuery().filter(esb.termQuery('status', 'active'));
// Assign a score of `1.0` to all documents
const qry = esb.boolQuery()
.must(esb.matchAllQuery())
.filter(esb.termQuery('status', 'active'));
Adds must_not
query to boolean container.
The clause (query) must not appear in the matching documents.
Clauses are executed in filter context meaning that scoring is ignored
and clauses are considered for caching. Because scoring is ignored,
a score of 0 for all documents is returned.
BoolQuery
:
returns
this
so that calls can be chained.
Query
Adds should
query to boolean container.
The clause (query) should appear in the matching document. In a boolean query with
no must or filter clauses, one or more should clauses must match a document.
The minimum number of should clauses to match can be set using the
minimum_should_match
parameter.
BoolQuery
:
returns
this
so that calls can be chained.
Query
Enables or disables similarity coordinate scoring of documents
commoning the CommonTermsQuery
. Default: false
.
NOTE: This has been removed in elasticsearch 6.0. If provided, it will be ignored and a deprecation warning will be issued.
(boolean)
BoolQuery
:
returns
this
so that calls can be chained.
Sets the value controlling how many should
clauses in the boolean
query should match. It can be an absolute value (2), a percentage (30%)
or a combination of both. By default no optional clauses are necessary for a match.
However, if the bool query is used in a filter context and it has should
clauses then,
at least one should
clause is required to match.
BoolQuery
:
returns
this
so that calls can be chained.
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.
Extends Query
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);
The tie breaker value. The tie breaker capability allows results
that include the same term in multiple fields to be judged better than
results that include this term in only the best of those multiple
fields, without confusing this with the better case of two different
terms in the multiple fields. Default: 0.0
.
(number)
DisMaxQuery
:
returns
this
so that calls can be chained.
Add given query array or query to list of queries
DisMaxQuery
:
returns
this
so that calls can be chained.
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.
Extends Query
// `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');
Sets the source query.
FunctionScoreQuery
:
returns
this
so that calls can be chained.
Controls the way the scores are combined.
FunctionScoreQuery
:
returns
this
so that calls can be chained.
Controls the way the query and function scores are combined.
FunctionScoreQuery
:
returns
this
so that calls can be chained.
Restricts new score to not exceed given limit. The default for max_boost
is FLT_MAX
.
(number)
FunctionScoreQuery
:
returns
this
so that calls can be chained.
Sets the minimum score limit for documents to be included in search result.
(number)
Minimum score threshold
FunctionScoreQuery
:
returns
this
so that calls can be chained.
Add a single score function to the list of existing functions.
FunctionScoreQuery
:
returns
this
so that calls can be chained.
Adds array of score functions to the list of existing functions.
FunctionScoreQuery
:
returns
this
so that calls can be chained.
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.
Extends Query
const qry = esb.boostingQuery(
esb.termQuery('field1', 'value1'), // positiveQry
esb.termQuery('field2', 'value2'), // negativeQry
0.2 // negativeBoost
);
Sets the "master" query that determines which results are returned.
BoostingQuery
:
returns
this
so that calls can be chained.
Sets the query used to match documents in the positive
query that will be negatively boosted.
BoostingQuery
:
returns
this
so that calls can be chained.
Sets the negative boost value.
BoostingQuery
:
returns
this
so that calls can be chained.
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.
Extends Query
Sets the nested query to be executed.
JoiningQueryBase
:
returns
this
so that calls can be chained.
Sets the scoring method.
Valid values are:
none
- no scoringmax
- the highest score of all matched child documents is usedmin
- the lowest score of all matched child documents is usedsum
- the sum the all the matched child documents is usedavg
- the default, the average of all matched child documents is used(string)
Can be one of
none
,
sum
,
min
,
max
,
avg
.
Defaults to
avg
for
NestedQuery
,
none
for
HasChildQuery
.
JoiningQueryBase
:
returns
this
so that calls can be chained.
const qry = esb.hasChildQuery(
esb.termQuery('tag', 'something'),
'blog_tag'
).scoreMode('min');
When set to true
will ignore an unmapped path
and will not match any
documents for this query. When set to false
(the default value) the query
will throw an exception if the path is not mapped.
JoiningQueryBase
:
returns
this
so that calls can be chained.
Sets the inner hits options
JoiningQueryBase
:
returns
this
so that calls can be chained.
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).
Extends JoiningQueryBase
const qry = esb.nestedQuery()
.path('obj1')
.scoreMode('avg')
.query(
esb.boolQuery().must([
esb.matchQuery('obj1.name', 'blue'),
esb.rangeQuery('obj1.count').gt(5)
])
);
Sets the root context for the nested query.
(string)
NestedQuery
:
returns
this
so that calls can be chained.
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.
Extends JoiningQueryBase
// 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');
Sets the child document type to search against.
Alias for method childType
.
(string)
A valid doc type name
HasChildQuery
:
returns
this
so that calls can be chained.
Sets the child document type to search against
(string)
A valid doc type name
HasChildQuery
:
returns
this
so that calls can be chained.
Specify the minimum number of children are required to match for the parent doc to be considered a match
HasChildQuery
:
returns
this
so that calls can be chained.
const qry = esb.hasChildQuery(esb.termQuery('tag', 'something'), 'blog_tag')
.minChildren(2)
.maxChildren(10)
.scoreMode('min');
Specify the maximum number of children are required to match for the parent doc to be considered a match
HasChildQuery
:
returns
this
so that calls can be chained.
const qry = esb.hasChildQuery(esb.termQuery('tag', 'something'), 'blog_tag')
.minChildren(2)
.maxChildren(10)
.scoreMode('min');
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.
Extends JoiningQueryBase
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")
)
);
Sets the child document type to search against
Alias for method parentType
(string)
A valid doc type name
HasParentQuery
:
returns
this
so that calls can be chained.
Sets the child document type to search against
(string)
A valid doc type name
HasParentQuery
:
returns
this
so that calls can be chained.
By default, scoring is false
which ignores the score from the parent document.
The score is in this case equal to the boost on the has_parent
query (Defaults to 1).
If the score is set to true
, then the score of the matching parent document is
aggregated into the child documents belonging to the matching parent document.
HasParentQuery
:
returns
this
so that calls can be chained.
const qry = esb.hasParentQuery(
esb.termQuery('tag', 'something'),
'blog'
).score(true);
The parent_id
query can be used to find child documents which belong to a particular parent.
Extends Query
const qry = esb.parentIdQuery('blog_tag', 1);
Sets the child type.
ParentIdQuery
:
returns
this
so that calls can be chained.
Sets the id.
ParentIdQuery
:
returns
this
so that calls can be chained.
When set to true
will ignore an unmapped path
and will not match any
documents for this query. When set to false
(the default value) the query
will throw an exception if the path is not mapped.
ParentIdQuery
:
returns
this
so that calls can be chained.
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.
Extends Query
Sets the field to run the geo query on.
(string)
GeoQueryBase
:
returns
this
so that calls can be chained.
Sets the validation_method
parameter. Can be set to IGNORE_MALFORMED
to accept
geo points with invalid latitude or longitude, COERCE
to try and infer correct latitude
or longitude, or STRICT
(default is STRICT
).
Note: The ignore_malformed
and coerce
parameters have been removed
from geo_bounding_box
, geo_polygon
, and geo_distance
queries in
elasticsearch 6.0.
GeoQueryBase
:
returns
this
so that calls can be chained.
method
parameter is not one of
IGNORE_MALFORMED
,
COERCE
or
STRICT
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.
Extends GeoQueryBase
(string?)
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'))
Sets the shape definition for the geo query.
(GeoShape)
GeoShapeQuery
:
returns
this
so that calls can be chained.
shape
is not an instance of
GeoShape
Sets the reference name of a shape pre-indexed in another index.
(IndexedShape)
GeoShapeQuery
:
returns
this
so that calls can be chained.
shape
is not an instance of
IndexedShape
Sets the relationship between Query and indexed data that will be used to determine if a Document should be matched or not.
GeoShapeQuery
:
returns
this
so that calls can be chained
When set to true
will ignore an unmapped path
and will not match any
documents for this query. When set to false
(the default value) the query
will throw an exception if the path is not mapped.
GeoShapeQuery
:
returns
this
so that calls can be chained.
A query allowing to filter hits based on a point location using a bounding box.
Extends GeoQueryBase
(string?)
// 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);
Sets the top left coordinate for the Geo bounding box filter for querying documents
GeoBoundingBoxQuery
:
returns
this
so that calls can be chained.
Sets the bottom right coordinate for the Geo bounding box filter for querying documents
GeoBoundingBoxQuery
:
returns
this
so that calls can be chained.
Sets the top right coordinate for the Geo bounding box filter for querying documents
GeoBoundingBoxQuery
:
returns
this
so that calls can be chained.
Sets the bottom left coordinate for the Geo bounding box filter for querying documents
GeoBoundingBoxQuery
:
returns
this
so that calls can be chained.
Sets value for top of the bounding box.
(number)
GeoBoundingBoxQuery
:
returns
this
so that calls can be chained.
Sets value for left of the bounding box.
(number)
GeoBoundingBoxQuery
:
returns
this
so that calls can be chained.
Sets value for bottom of the bounding box.
(number)
GeoBoundingBoxQuery
:
returns
this
so that calls can be chained.
Sets value for right of the bounding box.
(number)
GeoBoundingBoxQuery
:
returns
this
so that calls can be chained.
Sets the type of execution for the bounding box query. The type of the bounding box execution by default is set to memory, which means in memory checks if the doc falls within the bounding box range. In some cases, an indexed option will perform faster (but note that the geo_point type must have lat and lon indexed in this case)
GeoBoundingBoxQuery
:
returns
this
so that calls can be chained.
const geoQry = esb.geoBoundingBoxQuery()
.field('pin.location')
.topLeft(esb.geoPoint()
.lat(40.73)
.lon(-74.1))
.bottomRight(esb.geoPoint()
.lat(40.10)
.lon(-71.12))
.type('indexed');
Filters documents that include only hits that exists within a specific distance from a geo point.
Extends GeoQueryBase
(string?)
(GeoPoint?)
Geo point used to measure and filter documents based on distance from it.
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));
Sets the radius of the circle centred on the specified location. Points which fall into this circle are considered to be matches. The distance can be specified in various units.
GeoDistanceQuery
:
returns
this
so that calls can be chained.
Sets the distance calculation mode, arc
or plane
.
The arc
calculation is the more accurate.
The plane
is the faster but least accurate.
(string)
GeoDistanceQuery
:
returns
this
so that calls can be chained
type
is neither
plane
nor
arc
.
Sets the point to filter documents based on the distance from it.
(GeoPoint)
Geo point used to measure and filter documents based on distance from it.
GeoDistanceQuery
:
returns
this
so that calls can be chained
point
is not an instance of
GeoPoint
A query allowing to include hits that only fall within a polygon of points.
Extends GeoQueryBase
(string?)
const geoQry = esb.geoPolygonQuery('person.location')
.points([
{"lat" : 40, "lon" : -70},
{"lat" : 30, "lon" : -80},
{"lat" : 20, "lon" : -90}
]);
Sets the points which form the polygon.
Points can be instances of GeoPoint
, Object with lat
, lon
keys,
GeoJSON
array representation or string(geohash
/lat, lon
)
(Array<any>)
GeoPolygonQuery
:
returns
this
so that calls can be chained
points
parameter is not an instance of
Array
.
// Format in `[lon, lat]`
const qry = esb.geoPolygonQuery('person.location').points([
[-70, 40],
[-80, 30],
[-90, 20]
]);
// Format in lat,lon
const qry = esb.geoPolygonQuery('person.location').points([
'40, -70',
'30, -80',
'20, -90'
]);
// Geohash
const qry = esb.geoPolygonQuery('person.location').points([
'drn5x1g8cu2y',
'30, -80',
'20, -90'
]);
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.
Extends Query
// 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);
Sets the list of fields to fetch and analyze the text from. Defaults to
the _all
field for free text and to all possible fields for document inputs.
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the search clause for the query. It is the only required parameter of the MLT query
and follows a versatile syntax, in which the user can specify free form text and/or
a single or multiple documents (see examples above). The syntax to specify documents
is similar to the one used by the Multi GET API.
When specifying documents, the text is fetched from fields unless overridden
in each document request. The text is analyzed by the analyzer at the field,
but could also be overridden. The syntax to override the analyzer at the
field follows a similar syntax to the per_field_analyzer
parameter of the
Term Vectors API.
Additionally, to provide documents not necessarily present in the index,
artificial documents
are also supported.
If string or object is passed, it is appended to the list. If an array is passed, it replaces the existing list.
MoreLikeThisQuery
:
returns
this
so that calls can be chained
The unlike
parameter is used in conjunction with like
in order not to
select terms found in a chosen set of documents. In other words, we could ask
for documents like
: "Apple", but unlike
: "cake crumble tree".
The syntax is the same as like.
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the text to find documents like it.
Note: This parameter has been removed in elasticsearch 6.0. Use like
instead.
(string)
The text to find documents like it.
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the list of ids
for the documents with syntax similar to
the Multi GET API.
Note: This parameter has been removed in elasticsearch 6.0. Use like
instead.
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the list of docs
for the documents with syntax similar to
the Multi GET API.
Note: This parameter has been removed in elasticsearch 6.0. Use like
instead.
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the maximum number of query terms that will be selected.
Increasing this value gives greater accuracy at the expense of query execution speed.
Defaults to 25
.
(number)
The maximum number of query terms that will be selected.
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the minimum term frequency below which the terms will be ignored from the input document Defaults to 2.
(number)
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the minimum document frequency below which the terms will be ignored
from the input document. Defaults to 5
.
(number)
The minimum document frequency
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the maximum document frequency above which the terms will be ignored
from the input document. Defaults to unbounded (0
).
(number)
The minimum document frequency
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the minimum word length below which the terms will be ignored.
Defaults to 0
.
(number)
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the maximum word length above which the terms will be ignored.
Defaults to unbounded (0
).
(number)
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Sets the array of stop words. Any word in this set is considered "uninteresting" and ignored.
MoreLikeThisQuery
:
returns
this
so that calls can be chained
Set the analyzer to control which analyzer will perform the analysis process on the text.
Defaults to the analyzer associated with the first field in fields
.
(string)
A valid text analyzer.
MoreLikeThisQuery
:
returns
this
so that calls can be chained.
Sets the value controlling how many should
clauses in the boolean
query should match. It can be an absolute value (2), a percentage (30%)
or a combination of both. (Defaults to "30%"
).
MoreLikeThisQuery
:
returns
this
so that calls can be chained.
Sets the boost factor to use when boosting terms.
Defaults to deactivated (0
).
(number)
A positive value to boost terms.
MoreLikeThisQuery
:
returns
this
so that calls can be chained.
Specifies whether the input documents should also be included in the
search results returned. Defaults to false
.
(boolean)
MoreLikeThisQuery
:
returns
this
so that calls can be chained.
A query allowing to define scripts as queries. They are typically used in a filter context.
Extends Query
(Script?)
const scriptQry = esb.scriptQuery(esb.script()
.lang('painless')
.inline("doc['num1'].value > 1"))
// Use in filter context
const qry = esb.boolQuery().must(scriptQry);
Sets the script
for query.
(Script)
ScriptQuery
:
returns
this
so that calls can be chained.
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.
Extends Query
(string?)
The type / mapping of the document being percolated.
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);
Sets the field of type percolator
and that holds the indexed queries.
PercolateQuery
:
returns
this
so that calls can be chained.
Sets the type / mapping of the document being percolated.
Note: This param has been deprecated in elasticsearch 6.0. From 6.0 and
later, it is no longer required to specify the document_type
parameter.
(string)
The type / mapping of the document being percolated.
PercolateQuery
:
returns
this
so that calls can be chained.
Appends given source document to the list of source documents being percolated. Instead of specifying the source document being percolated, the source can also be retrieved from an already stored document.
(Object)
The source document being percolated.
PercolateQuery
:
returns
this
so that calls can be chained.
const qry = esb.percolateQuery('query', 'people')
.document({ name: 'Will Smith' });
Appends given source documents to the list of source documents being percolated. Instead of specifying the source documents being percolated, the source can also be retrieved from already stored documents.
PercolateQuery
:
returns
this
so that calls can be chained.
const qry = esb.percolateQuery('query', 'people')
.documents([{ name: 'Will Smith' }, { name: 'Willow Smith' }]);
Sets the index the document resides in. This is a required parameter if document
is not specified.
(string)
The index the document resides in.
PercolateQuery
:
returns
this
so that calls can be chained.
Sets the type of the document to fetch. This is a required parameter if document
is not specified.
(string)
The type of the document to fetch.
PercolateQuery
:
returns
this
so that calls can be chained.
Sets the id of the document to fetch. This is a required parameter if document
is not specified.
(string)
The id of the document to fetch.
PercolateQuery
:
returns
this
so that calls can be chained.
Sets the routing to be used to fetch document to percolate. Optional.
(string)
The routing to be used to fetch document to percolate.
PercolateQuery
:
returns
this
so that calls can be chained.
Sets the preference to be used to fetch document to percolate. Optional.
(string)
The preference to be used to fetch document to percolate.
PercolateQuery
:
returns
this
so that calls can be chained.
Sets the expected version of the document to be fetched. Optional. If the version does not match, the search request will fail with a version conflict error.
(string)
The expected version of the document to be fetched.
PercolateQuery
:
returns
this
so that calls can be chained.
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.
Extends Query
Matches spans containing a term. The span term query maps to Lucene SpanTermQuery
.
Extends SpanQueryBase
const qry = esb.spanTermQuery('user', 'kimchy');
const qry = esb.spanTermQuery()
.field('user')
.value('kimchy')
.boost(2.0);
Sets the field to search on.
(string)
SpanTermQuery
:
returns
this
so that calls can be chained.
Sets the query string.
SpanTermQuery
:
returns
this
so that calls can be chained.
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.
Extends SpanQueryBase
(MultiTermQueryBase?)
One of wildcard, fuzzy, prefix, range or regexp query
const spanQry = esb.spanMultiTermQuery()
.match(esb.prefixQuery('user', 'ki').boost(1.08));
Sets the multi term query.
(MultiTermQueryBase)
One of wildcard, fuzzy, prefix, range or regexp query
SpanMultiTermQuery
:
returns
this
so that calls can be chained.
Matches spans near the beginning of a field. The span first query maps to Lucene SpanFirstQuery
.
Extends SpanQueryBase
(SpanQueryBase?)
Any other span type query
const spanQry = esb.spanFirstQuery()
.match(esb.spanTermQuery('user', 'kimchy'))
.end(3);
Sets the match
clause which can be any other span type query.
(SpanQueryBase)
SpanFirstQuery
:
returns
this
so that calls can be chained.
Sets the maximum end position permitted in a match.
(number)
The maximum end position permitted in a match.
SpanFirstQuery
:
returns
this
so that calls can be chained.
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
.
Extends SpanQueryBase
const spanQry = esb.spanNearQuery()
.clauses([
esb.spanTermQuery('field', 'value1'),
esb.spanTermQuery('field', 'value2'),
esb.spanTermQuery('field', 'value3')
])
.slop(12)
.inOrder(false);
Sets the clauses element which is a list of one or more other span type queries.
(Array<SpanQueryBase>)
SpanNearQuery
:
returns
this
so that calls can be chained.
clauses
is not an instance of Array or if
any member of the array is not an instance of
SpanQueryBase
.
Configures the slop
(default is 0), the maximum number of intervening
unmatched positions permitted.
(number)
A positive integer value, defaults is 0.
SpanNearQuery
:
returns
this
so that calls can be chained.
(boolean)
SpanNearQuery
:
returns
this
so that calls can be chained.
Matches the union of its span clauses. The span or query maps to Lucene SpanOrQuery
.
Extends SpanQueryBase
const spanQry = esb.spanOrQuery()
.clauses([
esb.spanTermQuery('field', 'value1'),
esb.spanTermQuery('field', 'value2'),
esb.spanTermQuery('field', 'value3')
]);
Sets the clauses element which is a list of one or more other span type queries.
(Array<SpanQueryBase>)
SpanOrQuery
:
returns
this
so that calls can be chained.
clauses
is not an instance of Array or if
any member of the array is not an instance of
SpanQueryBase
.
Removes matches which overlap with another span query. The span not query
maps to Lucene SpanNotQuery
.
Extends SpanQueryBase
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));
Sets the include
clause which is the span query whose matches are filtered
(SpanQueryBase)
SpanNotQuery
:
returns
this
so that calls can be chained.
Sets the exclude
clause which is the span query whose matches must
not overlap those returned.
(SpanQueryBase)
SpanNotQuery
:
returns
this
so that calls can be chained.
If set the amount of tokens before the include span can't have overlap with the exclude span.
(number)
SpanNotQuery
:
returns
this
so that calls can be chained.
If set the amount of tokens after the include span can't have overlap with the exclude span.
(number)
SpanNotQuery
:
returns
this
so that calls can be chained.
If set the amount of tokens from within the include span can't have overlap
with the exclude span. Equivalent of setting both pre
and post
.
(number)
SpanNotQuery
:
returns
this
so that calls can be chained.
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.
Extends SpanQueryBase
Sets the little
clause.
(SpanQueryBase)
Any span type query
SpanLittleBigQueryBase
:
returns
this
so that calls can be chained.
Sets the big
clause.
(SpanQueryBase)
Any span type query
SpanLittleBigQueryBase
:
returns
this
so that calls can be chained.
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.
Extends SpanLittleBigQueryBase
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.
Extends SpanLittleBigQueryBase
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.
Extends SpanQueryBase
(string?)
(SpanQueryBase?)
Any other span type query
const spanQry = esb.spanNearQuery()
.clauses([
esb.spanTermQuery('text', 'quick brown'),
esb.spanFieldMaskingQuery()
.field('text')
.query(esb.spanTermQuery('text.stems', 'fox'))
])
.slop(5)
.inOrder(false);
Sets the span query.
(SpanQueryBase)
SpanFieldMaskingQuery
:
returns
this
so that calls can be chained.
Sets the field to mask.
(string)
SpanFieldMaskingQuery
:
returns
this
so that calls can be chained.
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.
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.
Sets name for aggregation.
Aggregation
:
Sets nested aggregations. This method can be called multiple times in order to set multiple nested aggregations.
Aggregation
:
returns
this
so that calls can be chained.
agg
is not an instance of
Aggregation
Sets nested aggregation. This method can be called multiple times in order to set multiple nested aggregations.
Aggregation
:
returns
this
so that calls can be chained.
Sets multiple nested aggregation items. This method accepts an array to set multiple nested aggregations in one call.
Aggregation
:
returns
this
so that calls can be chained.
Sets multiple nested aggregation items.
Alias for method aggregations
Aggregation
:
returns
this
so that calls can be chained.
You can associate a piece of metadata with individual aggregations at request time that will be returned in place at response time.
(Object)
Aggregation
:
returns
this
so that calls can be chained.
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.
Extends Aggregation
(string)
a valid aggregation name
(string)
type of aggregation
(string?)
The field to aggregate on
Sets field to run aggregation on.
(string)
a valid field name
MetricsAggregationBase
:
returns
this
so that calls can be chained
Sets script parameter for aggregation.
(Script)
MetricsAggregationBase
:
returns
this
so that calls can be chained
script
is not an instance of
Script
// 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 })
);
Sets the missing parameter which defines how documents that are missing a value should be treated.
(string)
MetricsAggregationBase
:
returns
this
so that calls can be chained
const agg = esb.avgAggregation('avg_grade', 'grade').missing(10);
Sets the format expression if applicable.
(string)
Format mask to apply on aggregation response. Example: ####.00
MetricsAggregationBase
:
returns
this
so that calls can be chained
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.
Aggregation that computes the average of numeric values that are extracted from the aggregated documents.
Extends MetricsAggregationBase
(string)
The name which will be used to refer to this aggregation.
(string?)
The field to aggregate on
// 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.
Aggregation that calculates an approximate count of distinct values.
Extends MetricsAggregationBase
(string)
The name which will be used to refer to this aggregation.
(string?)
The field to aggregate on
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')
);
The precision_threshold
options allows to trade memory for accuracy,
and defines a unique count below which counts are expected to be close to accurate.
(number)
The threshold value.
The maximum supported value is 40000, thresholds above this number
will have the same effect as a threshold of 40000. The default values is 3000.
CardinalityAggregation
:
returns
this
so that calls can be chained
const agg = esb.cardinalityAggregation(
'author_count',
'author_hash'
).precisionThreshold(100);
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.
Aggregation that computes extra stats over numeric values extracted from the aggregated documents.
Extends MetricsAggregationBase
(string)
The name which will be used to refer to this aggregation.
(string?)
The field to aggregate on
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);
Set sigma in the request for getting custom boundary. sigma controls how many standard deviations +/- from the mean should be displayed
(number)
sigma can be any non-negative double,
meaning you can request non-integer values such as 1.5.
A value of 0 is valid, but will simply return the average for both upper and lower bounds.
ExtendedStatsAggregation
:
returns
this
so that calls can be chained
const agg = esb.extendedStatsAggregation('grades_stats', 'grade').sigma(3);
A metric aggregation that computes the bounding box containing all geo_point values for a field.
Extends MetricsAggregationBase
(string)
The name which will be used to refer to this aggregation.
(string?)
The field to aggregate on
const agg = esb.geoBoundsAggregation('viewport', 'location').wrapLongitude(true);
(boolean)
Optional parameter which specifies whether
the bounding box should be allowed to overlap the international date line.
The default value is true
GeoBoundsAggregation
:
returns
this
so that calls can be chained
A metric aggregation that computes the weighted centroid from all coordinate values for a Geo-point datatype field.
Extends MetricsAggregationBase
(string)
The name which will be used to refer to this aggregation.
(string?)
The field to aggregate on. field must be a Geo-point datatype type
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')
)
);
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.
Aggregation that keeps track and returns the maximum value among the numeric values extracted from the aggregated documents.
Extends MetricsAggregationBase
(string)
The name which will be used to refer to this aggregation.
(string?)
The field to aggregate on
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.
Aggregation that keeps track and returns the minimum value among numeric values extracted from the aggregated documents.
Extends MetricsAggregationBase
(string)
The name which will be used to refer to this aggregation.
(string?)
The field to aggregate on
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.
Aggregation that calculates one or more percentiles over numeric values extracted from the aggregated documents.
Extends MetricsAggregationBase
(string)
The name which will be used to refer to this aggregation.
(string?)
The field to aggregate on
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 })
);
Enable the response to be returned as a keyed object where the key is the bucket interval.
(boolean)
To enable keyed response or not. True by default
PercentilesAggregation
:
returns
this
so that calls can be chained
// Return the ranges as an array rather than a hash
const agg = esb.percentilesAggregation('balance_outlier', 'balance').keyed(
false
);
Specifies the percents of interest. Requested percentiles must be a value between 0-100 inclusive
PercentilesAggregation
:
returns
this
so that calls can be chained
percents
is not an instance of Array
// Specify particular percentiles to calculate
const agg = esb.percentilesAggregation(
'load_time_outlier',
'load_time'
).percents([95, 99, 99.9]);
Compression controls memory usage and approximation error. The compression value limits the maximum number of nodes to 100 * compression. By increasing the compression value, you can increase the accuracy of your percentiles at the cost of more memory. Larger compression values also make the algorithm slower since the underlying tree data structure grows in size, resulting in more expensive operations. The default compression value is 100.
(number)
Parameter to balance memory utilization with estimation accuracy.
PercentilesAggregation
:
returns
this
so that calls can be chained
const agg = esb.percentilesAggregation(
'load_time_outlier',
'load_time'
).tdigest(200);
Compression controls memory usage and approximation error. The compression value limits the maximum number of nodes to 100 * compression. By increasing the compression value, you can increase the accuracy of your percentiles at the cost of more memory. Larger compression values also make the algorithm slower since the underlying tree data structure grows in size, resulting in more expensive operations. The default compression value is 100.
Alias for tdigest
(number)
Parameter to balance memory utilization with estimation accuracy.
PercentilesAggregation
:
returns
this
so that calls can be chained
const agg = esb.percentilesAggregation(
'load_time_outlier',
'load_time'
).compression(200);
HDR Histogram (High Dynamic Range Histogram) is an alternative implementation that can be useful when calculating percentiles for latency measurements as it can be faster than the t-digest implementation with the trade-off of a larger memory footprint.
The HDR Histogram can be used by specifying the method parameter in the request.
(number)
The resolution of values
for the histogram in number of significant digits
PercentilesAggregation
:
returns
this
so that calls can be chained
const agg = esb.percentilesAggregation('load_time_outlier', 'load_time')
.percents([95, 99, 99.9])
.hdr(3);
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.
Aggregation that calculates one or more percentiles ranks over numeric values extracted from the aggregated documents.
Extends MetricsAggregationBase
(string)
The name which will be used to refer to this aggregation.
(string?)
The field to aggregate on. It must be a numeric field
(Array?)
Values to compute percentiles from.
values
is not an instance of Array
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 })
);
Enable the response to be returned as a keyed object where the key is the bucket interval.
(boolean)
To enable keyed response or not.
PercentilesRanksAggregation
:
returns
this
so that calls can be chained
// Return the ranges as an array rather than a hash
const agg = esb.percentileRanksAggregation('balance_outlier', 'balance')
.values([25000, 50000])
.keyed(false);
Specifies the values to compute percentiles from.
PercentileRanksAggregation
:
returns
this
so that calls can be chained
values
is not an instance of Array
Compression controls memory usage and approximation error. The compression value limits the maximum number of nodes to 100 * compression. By increasing the compression value, you can increase the accuracy of your percentiles at the cost of more memory. Larger compression values also make the algorithm slower since the underlying tree data structure grows in size, resulting in more expensive operations. The default compression value is 100.
(number)
Parameter to balance memory utilization with estimation accuracy.
PercentileRanksAggregation
:
returns
this
so that calls can be chained