A simple query builder for Elasticsearch. Outputs JSON ready to be sent to Elasticsearch via your favourite client.
from elasticquery import ElasticQuery, Filter, Query, Aggregate
query = ElasticQuery()
# Filter
query.must(Filter.range('price', 0, 500))
# Query
query.should(Query.nested('nested_key', musts=[
Query.terms(nested_key_key=['value']),
Query.prefix(another_key='prefixed_with_')
]))
# Aggregate
query.aggregate('key_terms', Aggregate.terms('key'))
json = query.compile()
query = ElasticQuery()
Return a json string ready to send to Elasticsearch.
fields: list of fields to return
Sort the result set by a field, order optional.
Search where the Query
/Filter
object matches.
Search where the Query
/Filter
object might matches.
Search where the Query
/Filter
object does not match.
Add an Aggregate
to our search query.
Adds a nested query.
musts, shoulds & must_nots: all lists containing Query
or Filter
objects.
Prefix multiple keys.
Search multiple key=>value terms.
Search multiple key=>[values] terms.
Filter for missing/null fields.
Adds a raw query string to match against.
This builds a query string based on kwargs
. Values can be simple (ints/strings) or lists, in which case they are OR
'd together.
Or the arg filters/queries together.
The Query
class inherits from Filter
, see above for API details.
Searches objects where field is similar to the match.
Puts **aggregates as sub-aggregats under aggregate.
Get sum of a field.
Get the average value across a field.
Get the lowest value of a field.
Get the highest value of a field.
Get stats on a field.
Get extended stats on a field.
Count how many documents are missing a given field.
Count how many documents contain a given field.
Generate a histogram.
Generate a date histogram.
Count number of terms on a field.
Create a nested aggregation (for use with sub aggregates, see Aggregate.sub).
Creates a filtered aggregate (for use with sub aggregates, see Aggregate.sub).
ElasticQuery
contains .structure
which represents the final output. Filter.*
, Query.*
and Aggregate.*
functions are essentially structs, each builds from its input and returns a dict representing the relevant json structure Elasticsearch wants.
Although there's multiple ways of doing most query/filter types in ES (ie query['range'] = { 'to': 500 '}
), ElasticQuery
stores everything inside a bool query. I haven't seen any performance degredation as a result makes everything a lot simpler. This way queries, filters and nested queries/filters all have a combination none or more of must
, should
and must_not
matches.