Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion documentation/client/scroll.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ count (an explicit ceiling below it is still a whole-shard split on the Elastics

**Limitations:**
- ❌ Not supported with aggregations
- ❌ Requires sort fields
- ⚠️ Needs a total order: the client pages on `_id` (see below)
- ⚠️ No consistent snapshot (data can change between pages)

```scala
Expand All @@ -253,6 +253,16 @@ val query = SQLQuery(
client.scroll(query).runWith(Sink.seq)
```

**The `_id` order.** A statement needs no `ORDER BY` to be paged with `search_after`: without one,
the client pages in `_id` order (ascending); with one, it appends `_id` as the tie-breaker unless
the sort already names it. Since **0.24.0** that `_id` sort carries `unmapped_type: keyword`. On
Elasticsearch 6 an index created without any mapping has no type, hence no `_id` to sort on, so
every shard of such an index failed the page, and a statement without `LIMIT` over a pattern that
includes one failed even when that index was empty; it is now read like the others. `_id` is
mapped in every other index, where the key changes nothing. The Elasticsearch 7 client pages the
same way below 7.12 and carries the same key; whether 7.0 – 7.11 failed such an index is not
measured.

---

### Classic Scroll
Expand Down Expand Up @@ -317,6 +327,10 @@ case class ScrollConfig(
// Retry configuration
retryConfig: RetryConfig = RetryConfig(),

// A statement without LIMIT whose window values cannot be computed:
// None or Some(true) fails the stream; Some(false) answers the rows without them
failOnWindowError: Option[Boolean] = None,

// Ceiling on concurrent PIT slices for a no-ORDER-BY extraction (ES 7.15+, 0.21.0+).
// None = inherit the client's `elastic.scroll.max-slices`; Some(n) explicit, n <= 1 sequential
maxSlices: Option[Int] = None,
Expand All @@ -341,9 +355,18 @@ explicit fields but still inherits the configured ceiling through `maxSlices = N
| `preferSearchAfter` | `Boolean` | `true` | Prefer search_after when available |
| `logEvery` | `Int` | `10` | Log progress every N batches |
| `metrics` | `ScrollMetrics` | `ScrollMetrics()` | Initial metrics state |
| `failOnWindowError` | `Option[Boolean]` | `None` | When the window values of a statement without `LIMIT` cannot be computed: `None` or `Some(true)` fails the stream, `Some(false)` answers the rows without them (see below) |
| `maxSlices` | `Option[Int]` | `None` | Ceiling on concurrent PIT slices; `None` inherits `elastic.scroll.max-slices` (default 8), `Some(1)` pages sequentially |
| `slices` | `Int` | `1` | Internal — the resolved slice count (read it on `ScrollMetrics.slices`) |

**Window functions: `failOnWindowError`.** A statement without `LIMIT` that carries a window
function first computes its window values with an aggregation, then pages its rows and adds the
values to each one. When those values cannot be computed — for instance because some shards of the
window aggregation fail — the stream fails with `Window function computation failed: …`. That is
the default since **0.24.0** (`None`), and what `Some(true)` asks for. `Some(false)` answers the rows
**without** their window values, a wrong answer for every projected window column, so it is an
explicit opt-in only. Before 0.24.0 the default was that fallback.

---

### ScrollMetrics
Expand Down Expand Up @@ -707,6 +730,18 @@ is the right place to decide what a partial read means for your application.
The failure is deliberately **not** retried: a scroll cursor that has already advanced cannot be
re-polled without skipping rows.

### A page on which some shards fail fails the stream

Elasticsearch answers a page on which **some** shards fail with HTTP 200 and the hits of the
shards that succeeded. Every paging path reads the page's `_shards` section, and a page with a
failed shard fails the stream with the shards' reasons — `Initial scroll failed: …`,
`Scroll continuation failed: …` (the scroll context is released and the page is not retried),
`Search after failed: …` or
`PIT search_after failed: …` — instead of handing over the other shards' rows as if they were the
whole page. The Elasticsearch 6 Jest client does so since **0.24.0**; before it, its three paging
doors judged a page by its HTTP status only. A one-shot search answers the same condition with an
error too — see [Search: a search whose shards fail](search.md#a-search-whose-shards-fail).

```scala
// Automatic error handling is built-in
client.scroll(query).runWith(Sink.seq).recover {
Expand Down
23 changes: 23 additions & 0 deletions documentation/client/search.md
Original file line number Diff line number Diff line change
Expand Up @@ -1700,6 +1700,29 @@ client.singleSearchAs[Product](query, Map.empty, Map.empty) match {

---

### A search whose shards fail

Elasticsearch answers a search on which **some** shards fail with HTTP 200, `_shards.failed > 0`,
and the hits / buckets of the shards that succeeded only. Since **0.24.0** every one-shot search
reads that section and answers an `ElasticFailure` instead of those partial rows:

- the message is `n of m shards failed`, then the first failure's type and reason, and its cause
when Elasticsearch gives one: `1 of 3 shards failed: null_pointer_exception: …`;
- `statusCode` is `400` when **every** failure is one Elasticsearch attributes to the request
(`script_exception`, `query_shard_exception`, `illegal_argument_exception`, `parsing_exception`,
`search_parse_exception`, `x_content_parse_exception`), and `None` otherwise;
- a multi-search is read response by response: the first one whose shards failed answers the
error, prefixed with its 1-based position (`Query 2: 1 of 3 shards failed: …`).

`skipped` shards are not failures. Before 0.24.0 the one-shot searches did not read `_shards`, so
such a search answered the other shards' rows as the whole result, with no error. The paging paths
fail the same way page by page — see
[Scroll: a page on which some shards fail](scroll.md#a-page-on-which-some-shards-fail-fails-the-stream).
For the SQL statement that most often meets it, see
[`ORDER BY` over a function of a column some documents do not carry](../sql/dql_statements.md#where).

---

### Multi-Search Partial Failures

```scala
Expand Down
14 changes: 8 additions & 6 deletions documentation/sql/ddl_statements.md
Original file line number Diff line number Diff line change
Expand Up @@ -539,11 +539,13 @@ ran without error before:
- **A cast of a string column now COMPUTES.** `SCRIPT AS (CAST(amount_str AS BIGINT) + fee)` sums
the two. Before 0.24.0 it concatenated the two renderings — `'125'` and `7` stored `1257` rather
than `132`, with no error.
- **A cast of a NUMERIC column to a different numeric type now decides the result type.**
`CAST(price AS INTEGER) / 2` over `price = 5.0` is `2`, because `CAST(price AS INTEGER)` really is
an integer; before 0.24.0 the column's own type won and it was `2.5`. The widening direction moves
the same way: `CAST(qty AS DOUBLE) / 2` over an `INTEGER` column is now `2.5` where it was `2`.
`WHERE` clauses over such an expression therefore match a different set of rows.
- **A cast of a NUMERIC column to a different numeric type now decides the OPERAND's type** in
the arithmetic around it: `CAST(price AS INTEGER)` really is an integer. It does not decide a
division: `/` always yields a `DOUBLE` whatever its operands are, so `CAST(price AS INTEGER) / 2`
over `price = 5.0` is `2.5` — the cast narrows the operand, it does not make the division
integral — and `CAST(qty AS DOUBLE) / 2` over an `INTEGER` column is `2.5` where it was `2`.
Write `(a / b)::INTEGER` for a truncated quotient. `WHERE` clauses over such an expression
therefore match a different set of rows.
- **A numeric column cast to a string now CONCATENATES.** `CAST(qty AS KEYWORD) + 2` yields
`'42'`-style text; before 0.24.0 the string was silently parsed back to a number and the
expression computed. Under `-`, `*` and `/` the same shape is now a runtime failure rather than a
Expand Down Expand Up @@ -1057,7 +1059,7 @@ FROM logs-*, metrics-* WHERE level = 'ERROR' WITHIN 5 MINUTES
>
> Pre-join the sources with a [`MATERIALIZED VIEW`](materialized_views.md) and point the watcher
> at the view instead.
>

A table alias may be used and is resolved in the `WHERE`, so `FROM orders o WHERE o.status =
'FAILED'` searches index `orders` for documents whose **`status`** field is `FAILED`.

Expand Down
68 changes: 48 additions & 20 deletions documentation/sql/dql_statements.md
Original file line number Diff line number Diff line change
Expand Up @@ -461,9 +461,13 @@ The `WHERE` clause supports:
> those 5 rows as the whole result, with no error.
>
> A statement without `LIMIT` is read page by page and fails the same way
> (`PIT search_after failed: …`). To sort such a column, sort by the bare column, or keep the field
> present on every document. The same applies to `ORDER BY` over a `CASE … END` with no `ELSE`,
> which is NULL-valued for the rows no branch matches.
> (`PIT search_after failed: …`). This is not specific to sorting: since **0.24.0**, a search on
> which some shards fail answers an error — `n of m shards failed`, then the first failure's type
> and reason — never the rows of the shards that succeeded (see
> [Search: a search whose shards fail](../client/search.md#a-search-whose-shards-fail)). To sort
> such a column, sort by the bare column, or keep the field present on every document. The same
> applies to `ORDER BY` over a `CASE … END` with no `ELSE`, which is NULL-valued for the rows no
> branch matches.
>
> Since **0.24.0**, a sort by the bare column over an index pattern or list also answers the
> documents of an index that does not map that column, sorted as `NULL`, when the other indices map
Expand Down Expand Up @@ -1542,8 +1546,8 @@ ORDER BY COUNT(*) DESC;
```

- `GROUP BY` supports nested fields (`profile.city`).
- A key over a date column, or over a function of any column, groups by the key's own value from
a single index, an index pattern or a list of indices:
- Since **0.24.0**, a key over a date column, or over a function of any column, groups by the key's
own value from a single index, an index pattern or a list of indices:
- `DATE_TRUNC(created_at, MONTH)` is one Elasticsearch `date_histogram` level with that calendar
interval;
- a bare date column (`GROUP BY created_at`) is a `terms` level on the field: one group per
Expand Down Expand Up @@ -1644,21 +1648,24 @@ ORDER BY COUNT(*) DESC;

#### Comparing a DATE aggregate

⚠️ **A comparison between a date aggregate and a date literal is refused**, function or not:
`HAVING MAX(created) > '2019-01-01'` and `HAVING MIN(created) < '2020-01-01'` are rejected at parse
time. A group filter reads every metric as a number — a date as epoch milliseconds — so the
generated comparison is text against a number and Elasticsearch fails the whole search with a
`class_cast_exception`. Compare in `WHERE` instead, or filter the result outside the query.
A date aggregate compares with a date literal as a date column does: `HAVING MAX(created) >
'2019-01-01'` keeps the groups whose latest `created` falls after that day, and
`HAVING MIN(created) < '2020-01-01'` those whose earliest falls before it (*since `0.24.0`*:
Elasticsearch failed the whole search, the comparison reading the date as text against a number).

### Conditions on the GROUP BY key

A `HAVING` condition over the grouping key filters GROUPS, and it is applied by the `terms` filter —
so it is correct for a multi-valued field, where one document belongs to several groups.
so it is correct for a multi-valued field, where one document belongs to several groups. Since **0.24.0**, a
condition the `terms` filter cannot apply as written is refused (see the combinations below); before
it, several of them returned a plausible-looking but wrong set of groups, without an error.

```sql
SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city = 'Paris';
SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city LIKE 'P%';
SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city <> 'Lyon';
SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city IN ('Paris', 'Lyon');
SELECT city, COUNT(*) AS cnt FROM dql_users GROUP BY city HAVING city NOT IN ('Pau', 'Pise');
```

- Supported: a direct comparison of the key — `=`, `<>`, `IN`, `LIKE` / `RLIKE` — whether the key
Expand Down Expand Up @@ -1979,6 +1986,11 @@ FROM dql_sales
ORDER BY product, ts;
```

Since **0.24.0**, a statement without `LIMIT` whose window values cannot be computed — for instance
because shards of the window aggregation fail — answers an error,
`Window function computation failed: …`. Before 0.24.0 it answered its rows without their window
values (see [`failOnWindowError`](../client/scroll.md#scrollconfig)).

#### ROW_NUMBER / RANK / DENSE_RANK (ranking windows)

`ORDER BY` is REQUIRED inside `OVER` for ranking functions (ANSI). `PARTITION BY`
Expand Down Expand Up @@ -2065,11 +2077,11 @@ All functions operate on Elasticsearch documents and are evaluated by the SQL en
| Function | Description |
|---------------|----------------------|
| `ABS(x)` | Absolute value |
| `CEIL(x)` | Round up |
| `CEIL(x)` / `CEILING(x)` | Round up |
| `FLOOR(x)` | Round down |
| `ROUND(x, n)` | Round to n decimals |
| `SQRT(x)` | Square root |
| `POW(x, y)` | Power |
| `POW(x, y)` / `POWER(x, y)` | Power |
| `EXP(x)` | Exponential |
| `LOG(x)` | Natural logarithm |
| `LOG10(x)` | Base-10 logarithm |
Expand All @@ -2096,7 +2108,7 @@ number: `ROUND(423789293, -5)` is `423800000`. See
| `ACOS(x)` | Arc-cosine |
| `ATAN(x)` | Arc-tangent |
| `ATAN2(y, x)` | Arc-tangent of y/x with quadrant |
| `PI()` | π constant |
| `PI` | π constant (no parentheses) |
| `RADIANS(x)` | Degrees → radians |
| `DEGREES(x)` | Radians → degrees |

Expand Down Expand Up @@ -2124,12 +2136,12 @@ FROM dql_users;
|------------------------------|-------------------------------|
| `CONCAT(a, b, ...)` | Concatenate strings |
| `SUBSTRING(str, start, len)` | Extract substring |
| `LOWER(str)` | Lowercase |
| `UPPER(str)` | Uppercase |
| `LOWER(str)` / `LCASE(str)` | Lowercase |
| `UPPER(str)` / `UCASE(str)` | Uppercase |
| `TRIM(str)` | Trim both sides |
| `LTRIM(str)` | Trim left |
| `RTRIM(str)` | Trim right |
| `LENGTH(str)` | String length |
| `LENGTH(str)` / `LEN(str)` | String length |
| `REPLACE(str, from, to)` | Replace substring |
| `LEFT(str, n)` | Left n chars |
| `RIGHT(str, n)` | Right n chars |
Expand Down Expand Up @@ -2165,11 +2177,11 @@ ORDER BY id ASC;

| Function | Description |
|-------------------------------------------|-----------------------------|
| `CURRENT_DATE` | Current date (UTC) |
| `CURRENT_DATE` / `CURDATE()` | Current date (UTC) |
| `TODAY()` | Alias for CURRENT_DATE |
| `CURRENT_TIMESTAMP` \| `CURRENT_DATETIME` | Current timestamp (UTC) |
| `CURRENT_TIMESTAMP` | Current timestamp (UTC) |
| `NOW()` | Alias for CURRENT_TIMESTAMP |
| `CURRENT_TIME` | Current time (UTC) |
| `CURRENT_TIME` / `CURTIME()` | Current time (UTC) |

##### **Extraction:**

Expand Down Expand Up @@ -2334,6 +2346,15 @@ Returns NULL if `a = b`, otherwise `a`.
`NULLIF(status, 0)` over a `KEYWORD` reads `status` as a `BIGINT`, and a `status` that spells no
number fails the query. A computed column keeps refusing a text against a number.

##### ISNULL / ISNOTNULL

```sql
ISNULL(expr)
ISNOTNULL(expr)
```

`ISNULL` is TRUE when `expr` is NULL, `ISNOTNULL` when it is not.

##### GREATEST / LEAST

```sql
Expand Down Expand Up @@ -2444,6 +2465,7 @@ Notes:
paged in `_id` order, and with one `_id` is the tie-breaker. Since `0.24.0`, on Elasticsearch 6,
a statement without `LIMIT` over a pattern that includes an index created without any mapping is
read in full, even when that index is empty: the `_id` order no longer fails that index's shards
(see [The `_id` order](../client/scroll.md#search_after))
- Without `ORDER BY`, result ordering is not guaranteed

### When some shards fail
Expand Down Expand Up @@ -2495,6 +2517,12 @@ the set operators other than `UNION ALL` need the relational engine wherever the
of these versions alike. See
[Known Limitations & Roadmap](known_limitations.md#which-forms-need-the-relational-engine).

On Elasticsearch 6.8, two forms still fail: a `GROUP BY` key that formats a bare date column
(`GROUP BY DATE_FORMAT(created_at, '%Y-%m')`) is refused by name, so truncate the column first; and a
boolean literal cast to a number (`CAST(TRUE AS INT)`) fails to compile in Elasticsearch. The same
formats in a `SELECT` or a `WHERE`, and a date column compared with another, run on 6.8. See
[Known Limitations & Roadmap](known_limitations.md).

---

## Limitations
Expand Down
13 changes: 11 additions & 2 deletions documentation/sql/functions_conditional.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,8 @@ END

**Output:**
- Type coerced from result expressions (THEN/ELSE).
- Used as an operand, a `CASE` is one value: `CASE WHEN n > 0 THEN n ELSE 0 END + 1` adds 1 on every
branch, `4` for `n = 3` (*since `0.24.0`*: the operator applied to the last branch only, `3`).

**Examples:**

Expand Down Expand Up @@ -305,6 +307,8 @@ END

**Output:**
- Type coerced from result expressions.
- The values keep their own type: `CASE k WHEN 'a' THEN 0 ELSE 1 END` answers the numbers `0` and `1`
(*since `0.24.0`*: the text `"0"` and `"1"`).

**Implementation notes:**
The simple form evaluates by comparing `expr = value` for each WHEN.
Expand Down Expand Up @@ -442,6 +446,8 @@ NULLIF(expr1, expr2)
**Output:**
- Type of `expr1` — a quoted literal first is the value it is read as beside `expr2`, and has its
type: `NULLIF('2024-01-31', ts)` is a `TIMESTAMP`, `NULLIF('3', n)` a number — or NULL if equal
- A quoted date compares with a `DATE` in either shape: `NULLIF(d, '2024-01-31')` and
`NULLIF(d, '2024-01-31T00:00:00Z')` are both NULL on that day

**Examples:**

Expand Down Expand Up @@ -693,9 +699,12 @@ SELECT GREATEST(price_us, price_eu, price_uk) AS max_price
FROM products
```

**2. Floor on a computed value:**
**2. Floor on a computed value** — an arithmetic expression is not accepted as a function
argument, so compute it as a column first (see
[Known Limitations](known_limitations.md#arithmetic-is-not-accepted-inside-a-function-a-cast-or-a-case-branch)):
```sql
SELECT GREATEST(0, base_price - rebate) AS net
-- net_raw DOUBLE SCRIPT AS (base_price - rebate) in the table definition
SELECT GREATEST(0, net_raw) AS net
FROM orders
-- Never lets the net go below zero
```
Expand Down
Loading
Loading