Skip to main content

Elasticsearch query

The Elasticsearch query step allows users to execute queries against the internal Elasticsearch database. As Elasticsearch is a document-based database, only a list of individual elements can be returned.

Core features

  • Full-text search, including optional fuzziness, singular/plural handling etc.
  • Keyword search, i.e. searching for exact string matches.
  • Boolean queries, which allow multiple smaller queries to be combined.
  • Range queries, used to compare numeric or date fields. This works out of the box, as Elasticsearch automatically maps well-formed numbers and dates to the appropriate field types.
  • Vector search, useful for semantic search.
    • Vectors are properties of the type vector. They can be written by clients, or be calculated by the API from the text of the element with an embedding.
    • The text-embedding step turns the text of a search into a vector, which a kNN query of this step then uses, see the vector search example.
  • Geospatial search, i.e. searching for coordinates, lines, polygons, distances to other points, inside/outside polygon checks and more.
    • Properties of the geo types are mapped as geo_point (point) or geo_shape (all other geo types), see geo indices. Queries like geo_distance, geo_bounding_box and geo_shape work on them, see the geospatial search examples.
    • Expressions can calculate the geometries of a query with the geo functions, e.g. from a GeoJSON point of the parameters.

Note: The Elasticsearch mappings of properties follow their schemas and index intents; raw indices configure a mapping directly.

Step query

The query of the step can be written in two ways:

  • Short form: the query itself, i.e. an object like {"match": {"description": "lily"}}. This is the Elasticsearch Query DSL query, without any wrapping.

  • Long form: an object with the property query, which contains the Elasticsearch query, and the optional properties highlight and sort:

Elasticsearch has no query named query, therefore both forms can not be mixed up. Other properties of the long form are rejected, as are queries which wrap the query twice. Expressions can be used anywhere inside the long form, see parameterized Elasticsearch queries.

{
"type": "elasticsearch-query-dsl-mixin",
"query": {
"query": {
"match": {
"description": "lily"
}
},
"highlight": {
"fields": {
"description": {}
}
},
"sort": [
{
"name.keyword": "asc"
}
]
}
}

Highlighting

If the property highlight is set, the result contains the highlights of the matching text in metadata.highlight of each element. Elasticsearch’s highlight options are passed through, e.g. pre_tags, post_tags, fragment_size, number_of_fragments or encoder. The property fields is required.

  • Fields starting with an underscore (_), i.e. internal fields, are rejected. As wildcards could be used to reach them, field names starting with a wildcard (* or ?) are rejected as well. This also applies to matched_fields. Wildcards later in the name, e.g. desc*, are supported.
  • Custom highlight queries (highlight_query) are supported. They only change what is highlighted in the elements which the main query found, and are checked for unsupported features like the main query. Scripts are rejected.
  • Highlights contain the stored text of properties. If they are rendered as HTML, set "encoder": "html" so that Elasticsearch escapes the text, and only the tags are markup.

See the highlighting example.

Sorting

If the property sort is set, results are ordered by it instead of by score. It accepts a field name, an object like {"name.keyword": "asc"}, or a list of them. The supported options of a field are order (asc or desc), missing, mode, unmapped_type, numeric_type and format.

  • Text properties can not be sorted directly, use their keyword variant instead, e.g. name.keyword. Elasticsearch’s error is explained in the response, see understanding search errors.
  • _score can be used to sort by relevance, optionally combined with other fields.
  • _geo_distance sorts by the distance of a geo field to a point, e.g. {"_geo_distance": {"location": [13.4, 52.5], "order": "asc", "unit": "m"}}. It takes exactly one field, whose value is the point (or a list of points) to measure from, and the options order, unit, mode, distance_type and ignore_unmapped. The distances are returned in metadata.sort, see points near a position.
  • Internal fields (starting with _) are rejected, as well as _script and nested sorting.
  • The score of every element is still calculated and returned in metadata.score and maxScore, also if the sort does not use it. The sort values of every element are returned in metadata.sort.
  • The order is kept by the element hydration step.
  • Pagination with page and pageSize continues the order of the sort.

See the sorting example.

Step parameters

In addition to query, the step’s parameters object supports the following options:

  • nodeTypes: Optional, list of node types. If provided the search is restricted to the provided node types.
  • relationTypes: Optional, list of relation types. If provided the search is restricted to the provided relation types.
  • page: Optional, int, default is 1. The page of results to return.
  • pageSize: Optional, int, default is 25. Limits the number of results per page.
  • minScore: Optional, numeric, default is null. If set to a numeric value like 1.0, removes all search results with a lower score.

Step result

  • elements: List of search element objects returned by Elasticsearch. Each object contains:
    • id: Element id (UUID).
    • type: Type of the element.
    • metadata.score: Numeric value returned by Elasticsearch. A high score implies a high fit between the query and the element.
    • metadata.highlight: Only if highlight was requested and the element has highlights. Object of field names to lists of highlighted text fragments.
    • metadata.sort: Only if sort was requested. List of the values which the element was sorted by.
    • metadata.matchedQueries: Only if the query contains named queries (_name) which match the element. Object of query names to their own scores, e.g. the similarity of a kNN query, while metadata.score is the score of the whole query. kNN queries without _name are named after their field, e.g. descriptionEmbedding, further kNN queries of the same field descriptionEmbedding#2 etc., so an element can have several vector scores.
  • totalHits: Integer, number of total elements found by the query. Can be used to calculate how many pages of results are available. Very high numbers of results might be rounded or estimates by Elasticsearch.
  • maxScore: Maximum score achieved by any element, regardless of whether it is part of the current page of results.

The metadata of the elements is also made available to all following steps, and returned by the element hydration step next to the elements. It is associated with the element id, therefore it is also returned if other steps, e.g. a Cypher path search, are executed in between.

Parameterized Elasticsearch queries

Elasticsearch on its own does not support parameters in their Query DSL language. However, Ember Nexus uses the Expr Lang language to integrate expressions directly into the Query DSL query. These expressions need to be defined as strings surrounded by two curly brackets, e.g. {{your_expression}}, and their result will replace the expression string inside the query. The replaced value can be a string itself, but also all other JSON data types like numbers, arrays and objects are supported.
Expressions will receive the search step’s resolved parameters object as their only input - see how parameters are resolved for where those values come from.

See Expr Lang for the language’s features and a link to its playground, and parameters and expressions for a walkthrough of how parameters flow between search steps.

See the parameterized search example below.

Examples

See writing an Elasticsearch query for a walkthrough of building and running a custom query against this step, including how to use Kibana’s console and how to parameterize queries.

Unsupported Elasticsearch features

  • Other query languages like ES|QL, PromQL, SQL, EQL and others are not supported.
    If there is demand, please open a feature request ticket on GitHub.
  • Aggregations are not supported, as only elements can be returned.
  • Scripts of any kind (script, script_score, script fields, script sorts etc.) are rejected.
  • Features which look up data of other documents are rejected: terms lookups (terms with index, id and path), document references of more_like_this, pre-indexed shapes (indexed_shape) and percolate queries.
  • Joining queries (nested, has_child, has_parent, parent_id) are rejected. Joins need custom index definitions, which are not supported yet; they will stay unavailable once administrators can define their own indices.
  • wrapper queries are rejected, as they would hide such features.
  • query_vector_builder of kNN queries is rejected. Vectors of texts are calculated with the search step text-embedding and passed as query_vector.
  • Inference models and query rules which are configured in Elasticsearch are rejected: inference_id (e.g. of sparse_vector and semantic queries), text_expansion, weighted_tokens and the rule sets of rule queries (ruleset_ids).

Security aspects

This search step is limited in three ways:

  • Elasticsearch search requests are readonly by default.
  • Only elements accessible by the user can be searched. For kNN queries, the access filter is added to the filter of the kNN query itself, so the nearest accessible elements are found; filters outside of a kNN query are only applied by Elasticsearch to the nearest elements it already found.
  • The access conditions are applied in filter context: they restrict the results, but do not change their scores.
  • Only accessible element ids are returned.

While this removes support for aggregated properties and direct property lookups, this approach also disables additional dangerous approaches like the terms lookup query and joins. Note that joins are considered to be expensive, and are therefore already disabled in normal Elasticsearch deployments.

The rejected features listed above are detected by their names, on any level of the query, including results of expressions. As Elasticsearch’s Query DSL has no formal grammar, this is a check of names and not a full validation. A side effect is that properties which are named like such a feature (or contain script as a word, e.g. my_script) can not be used inside queries. The response of a rejected query names the feature and its location.

Elements are returned by this step, and their highlights and sort values are visible, because the user has search access to them. Search access implies read access inside of search requests, but not for GET /<uuid>. Properties which must never be visible, like password hashes and token hashes, are not indexed in Elasticsearch in the first place.

As there is no way to manipulate or exfiltrate arbitrary data, this search step is considered safe and can therefore be executed by any user.