API version: 0.3.0

---

# 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](https://www.elastic.co/docs/solutions/search/full-text), including optional fuzziness,
  singular/plural handling etc.
- [Keyword search](https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/keyword), i.e. searching for
  exact string matches.
- [Boolean queries](https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-bool-query), which allow
  multiple smaller queries to be combined.
- [Range queries](https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-range-query), 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](https://www.elastic.co/docs/solutions/search/vector/knn), useful for semantic search.
  - Vectors are properties of the type [`vector`](/reference/schemas/types/vector.md). They can be written by clients, or
    be calculated by the API from the text of the element with an [embedding](/reference/schemas/types/vector.md#embeddings).
  - The [`text-embedding`](/reference/search/text-embedding.md) step turns the text of a search into a vector, which a kNN
    query of this step then uses, see the [vector search example](/reference/search/elasticsearch-query-dsl-mixin/vector-search.md).
- [Geospatial search](https://www.elastic.co/docs/reference/query-languages/query-dsl/geo-queries), i.e. searching for
  coordinates, lines, polygons, distances to other points, inside/outside polygon checks and more.
  - Properties of the [geo types](/reference/formats-and-languages/geojson.md#supported-geometries) are mapped as
    `geo_point` (`point`) or `geo_shape` (all other geo types), see [geo indices](/reference/indices/geo.md). Queries like
    `geo_distance`, `geo_bounding_box` and `geo_shape` work on them, see the
    [geospatial search examples](/reference/search/elasticsearch-query-dsl-mixin/geospatial-search.md).
  - Expressions can calculate the geometries of a query with the
    [geo functions](/reference/formats-and-languages/expr-lang/geo-functions.md), e.g. from a GeoJSON point of the
    parameters.

**Note**: The Elasticsearch mappings of properties follow their [schemas](/reference/schemas.md) and
[index intents](/reference/indices.md); [raw indices](/reference/indices/raw-indices.md) 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](https://www.elastic.co/docs/explore-analyze/query-filter/languages/querydsl) query, without any wrapping.
- **Long form**: an object with the property `query`, which contains the Elasticsearch query, and the optional
  properties `highlight` and `sort`:
  - `query`: Required, the Elasticsearch query, same as the short form.
  - `highlight`: Optional, Elasticsearch's
    [highlight options](https://www.elastic.co/docs/reference/elasticsearch/rest-apis/highlighting),
    see [highlighting](#highlighting).
  - `sort`: Optional, Elasticsearch's
    [sort definition](https://www.elastic.co/docs/reference/elasticsearch/rest-apis/sort-search-results),
    see [sorting](#sorting).

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](#parameterized-elasticsearch-queries).

```json
{
  "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](/reference/search/elasticsearch-query-dsl-mixin/highlighting.md).

### 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](/guide/search/understanding-search-errors.md).
- `_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](/reference/search/elasticsearch-query-dsl-mixin/geospatial-search.md#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](/reference/search/element-hydration.md) step.
- Pagination with `page` and `pageSize` continues the order of the sort.

See the [sorting example](/reference/search/elasticsearch-query-dsl-mixin/sorting.md).

## 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](/reference/search/element-hydration.md#metadata) 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](/reference/search/cypher-path-subset.md), 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](/reference/formats-and-languages/expr-lang.md) 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](/reference/search.md#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](/guide/search/parameters-and-expressions.md) for a walkthrough of how parameters flow between
search steps.

See the [parameterized search example](/reference/search/elasticsearch-query-dsl-mixin/parameterized-search.md) below.

## Examples

- [Full text search](/reference/search/elasticsearch-query-dsl-mixin/full-text-search.md)
- [Exact keyword matching](/reference/search/elasticsearch-query-dsl-mixin/exact-keyword-matching.md)
- [Vector search](/reference/search/elasticsearch-query-dsl-mixin/vector-search.md)
- [Geospatial search](/reference/search/elasticsearch-query-dsl-mixin/geospatial-search.md)
- [Combining queries with bool](/reference/search/elasticsearch-query-dsl-mixin/combining-queries-with-bool.md)
- [Range queries on numeric fields](/reference/search/elasticsearch-query-dsl-mixin/range-queries-on-numeric-fields.md)
- [Restricting results with minScore](/reference/search/elasticsearch-query-dsl-mixin/restricting-results-with-min-score.md)
- [Query string](/reference/search/elasticsearch-query-dsl-mixin/query-string.md)
- [Text prefix search](/reference/search/elasticsearch-query-dsl-mixin/text-prefix-search.md)
- [Wildcard search](/reference/search/elasticsearch-query-dsl-mixin/wildcard-search.md)
- [Parameterized search](/reference/search/elasticsearch-query-dsl-mixin/parameterized-search.md)
- [Highlighting](/reference/search/elasticsearch-query-dsl-mixin/highlighting.md)
- [Sorting](/reference/search/elasticsearch-query-dsl-mixin/sorting.md)
- [Reverse sorting](/reference/search/elasticsearch-query-dsl-mixin/reverse-sorting.md)

See [writing an Elasticsearch query](/guide/search/writing-an-elasticsearch-query.md) 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](https://github.com/ember-nexus/api/issues/new).
- 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](https://www.elastic.co/docs/reference/query-languages/query-dsl/query-dsl-terms-query#query-dsl-terms-lookup)
and [joins](https://www.elastic.co/docs/reference/query-languages/query-dsl/joining-queries). 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>`](/api/get-element.md). 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.

---

Home: [Ember Nexus API docs](/index.md)

Full site map: [llms.txt](/llms.txt)

Previous: [Search](/reference/search.md)

Next: [Full text search](/reference/search/elasticsearch-query-dsl-mixin/full-text-search.md)
