> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreflux.org/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenSearch Connector

> Index MQTT data in OpenSearch for real-time search, analytics, and visualization

## OpenSearch Overview

The `OPENSEARCH` connector indexes MQTT messages as documents in OpenSearch and publishes search results back to MQTT. Each event either indexes one document or runs one search, and models can store into an index with `STORE IN`. The connector talks to the OpenSearch REST API over HTTP or HTTPS, with basic authentication.

> [!NOTE]
>
> OpenSearch suits logs, events, and sensor data you want to search and chart. Connect OpenSearch Dashboards to the same indices for visualizations.

**When to use it:** full-text search across messages, dashboards over recent data, and log or event archives. For a table with a fixed schema, use a SQL connector such as [PostgreSQL](https://docs.coreflux.org/latest/connectors/data-storage/postgresql.md).

***

## Quick Start

> [tab] Index messages
>
> Index each reading as a new document:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR PlantSearch WITH TYPE OPENSEARCH
>     ADD OPENSEARCH_CONFIG
>         WITH BASE_URL "https://opensearch.example.com:9200"
>         WITH USERNAME "iot_writer"
>         WITH PASSWORD GET SECRET "OPENSEARCH_PASSWORD"
>     ADD EVENT IndexReading
>         WITH SOURCE_TOPIC "sensors/+/reading"
>         WITH QUERY "CLEAN:{index: readings, body: {sensor: {topic.2}, value: {payload.json.value}, at: {timestamp}}}"
> ```
>
> Publishing `{"value": 21.5}` to `sensors/s1/reading` indexes one document into `readings`.

> [tab] Search on request
>
> Publish to a topic and get the matching documents back:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR PlantSearch WITH TYPE OPENSEARCH
>     ADD OPENSEARCH_CONFIG
>         WITH BASE_URL "https://opensearch.example.com:9200"
>         WITH USERNAME "iot_writer"
>         WITH PASSWORD GET SECRET "OPENSEARCH_PASSWORD"
>     ADD EVENT LatestReadings
>         WITH SOURCE_TOPIC "sensors/+/latest"
>         WITH DESTINATION_TOPIC "sensors/+/latest/result"
>         WITH QUERY "CLEAN:{index: readings, query: {match: {sensor: {topic.2}}}, sort: [{at: {order: desc}}], size: 10}"
> ```
>
> Publishing anything to `sensors/s1/latest` publishes the ten newest documents for `s1` to `sensors/s1/latest/result` as a JSON array.

***

## Connection Configuration

### OPENSEARCH\_CONFIG Parameters

**BASE\_URL** `string` *required*

Server root with scheme and port, for example `https://opensearch.example.com:9200`. A path is kept, so a reverse-proxy prefix such as `https://gateway.example.com/opensearch` works. A host without a scheme uses `https://`.

> [accordion] Optional Settings
>
> **USERNAME** `string`
>
> User for basic authentication. It must not contain `:`. Leave out `USERNAME` and `PASSWORD` for a cluster without security.
>
> **PASSWORD** `string`
>
> Password for `USERNAME`. Use `GET SECRET`. Any character works, including `; = ' @ : /` and non-ASCII characters.
>
> **IGNORE\_CERT\_ERRORS** `boolean`
>
> `true` accepts any server certificate, such as a self-signed one or one for another host name. Use it only in a test setup. Default: `false`, which checks the certificate against the CAs trusted by the broker host.
>
> **REQUEST\_TIMEOUT** `integer`
>
> Seconds one request may take, from sending it to the end of the answer. A request that takes longer fails. From 1 to 3600. Default: `30`.
>
> **CONNECTION\_TIMEOUT** `integer`
>
> Seconds to open the TCP and TLS connection. From 1 to 3600. Default: `5`.
>
> **USE\_SSL** `boolean`
>
> Only picks the scheme of a `BASE_URL` written without one: `false` uses `http://`. Leave it out when `BASE_URL` has a scheme.

> [!WARNING]
>
> **Never hardcode credentials in production.** Use environment variables and encrypted secrets to keep sensitive values out of your connector definitions:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR PlantSearch WITH TYPE OPENSEARCH
>     ADD OPENSEARCH_CONFIG
>         WITH BASE_URL GET ENV "OPENSEARCH_URL"
>         WITH USERNAME GET ENV "OPENSEARCH_USER"
>         WITH PASSWORD GET SECRET "OPENSEARCH_PASSWORD"
> ```
>
> See [Environment Variables & Secrets](https://docs.coreflux.org/latest/mqtt-broker/secrets-and-env.md) for setup and usage.

### Settings checked at deploy

A connector whose settings cannot work is refused when you deploy it. The message names the setting and never repeats the password. These are refused:

* A `BASE_URL` that is not an `http://` or `https://` URL, or that has a query (`?…`) or a fragment (`#…`)
* A login inside `BASE_URL`, such as `https://user:password@opensearch.example.com:9200`. Put it in `USERNAME` and `PASSWORD`.
* `USE_SSL false` with an `https://` `BASE_URL`, or `USE_SSL true` with `http://`
* A `USERNAME` that contains `:`, or a `PASSWORD` without a `USERNAME`
* A boolean that is not `true` or `false`, or a timeout that is not a whole number from 1 to 3600

A `USERNAME` with an empty `PASSWORD`, for example a `GET SECRET` that is not set yet, still deploys. Requests then fail with an authentication error.

### Credentials

The login is sent as basic authentication (`Authorization: Basic`, UTF-8) on every request. It never appears in the log, in a connection check reply, or in a status message.

| Server | Settings |
| - | - |
| Security plugin on (HTTPS, internal user) | `BASE_URL "https://…"`, `USERNAME`, `PASSWORD` |
| Self-signed certificate in a test setup | As above, plus `IGNORE_CERT_ERRORS true` |
| Security plugin off | `BASE_URL "http://…"`, no `USERNAME` or `PASSWORD` |

API keys, AWS IAM (SigV4) signing, and client certificates are not supported. On Amazon OpenSearch Service, use an internal user of fine-grained access control.

**Least privilege.** The connector needs no cluster permissions. For events and `STORE IN`, a role with these index permissions on its own indices is enough:

```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
{"index_patterns": ["readings*"], "allowed_actions": ["crud", "create_index", "indices:admin/mapping/put"]}
```

***

## Event Configuration

### EVENT Parameters

**SOURCE\_TOPIC** `string`

MQTT topic pattern that triggers the event. Supports wildcards. Use `SOURCE_TOPIC` or `EVERY`.

**QUERY** `string` *required*

An index request or a search, as a CLEAN or JSON object. See [Query format](#query-format).

> [accordion] Optional Settings
>
> **DESTINATION\_TOPIC** `string`
>
> MQTT topic where the result is published. A `+` in it takes the matching level of the source topic. Required for an `EVERY` event.
>
> **EVERY** `string`
>
> Run the event on a schedule, for example `WITH EVERY 1 MINUTE`. Use it for searches: an index event on a schedule writes the same document again.

***

## Query format

`QUERY` is a JSON object, written as `CLEAN:{key: value}` with unquoted keys and simple values, or as plain JSON with its quotes escaped for the LoT string (`"{\"index\": \"readings\", …}"`).

A query with both `index` and `body` indexes a document. Any other query is a search.

| Operation | Keys | Published to `DESTINATION_TOPIC` |
| - | - | - |
| Index one document | `index` (required), `body` (a JSON object), `id` (optional) | `{"success": true, "documentId": "…", "index": "…", "result": "created", "shards": {…}}` |
| Search | `index`, and any `_search` option: `query`, `sort`, `size`, `from`, `_source`, … | The hits' `_source` as a JSON array |

> [!WARNING]
>
> **Do not wrap a search in `body`.** `CLEAN:{index: logs, body: {query: …}}` has both `index` and `body`, so it stores the query as a document. Put the search options next to `index`: `CLEAN:{index: logs, query: …}`.

### Index options

| Key | Meaning |
| - | - |
| `index` | Index to write to. OpenSearch creates it on first use. It must name one index, not a pattern or a list. See [Index names](#index-names). |
| `body` | The document, a JSON object. `{value.json}` places the whole JSON payload. No timestamp is added, so put one in the body (`at: {timestamp}`). |
| `id` | Document ID. Indexing again with the same ID replaces the document. Without it, each event creates a new document with a random ID. |

### Search options

Every key except `index` is sent as the `_search` request body, so any search option that OpenSearch accepts works.

| Key | Meaning |
| - | - |
| `index` | Index, comma-separated indices, or a pattern such as `readings*`. Without it, the search covers every index the user may read, which needs read permission on all of them. Name the index. |
| `query` | OpenSearch query DSL. Without it, every document matches. |
| `sort`, `size`, `from`, `_source` | As in OpenSearch. `size` defaults to 10 in OpenSearch. |

Only the hits are published. Aggregations (`aggs`) run, but their results are not published. A search with no match publishes `[]`.

### Index names

An event's `index` is lowercased, and `\ / ? " < > |`, spaces, and hyphens become `_`. So `coreflux-events` is written to and searched in `coreflux_events`. Use underscores in event index names.

`STORE IN` only lowercases its `WITH TABLE` name and keeps hyphens.

### Placeholders

| Placeholder | Description |
| - | - |
| `{payload}` | The whole payload |
| `{value.json}` | The whole JSON payload |
| `{payload.json.key}` / `{value.json.key}` | A field of the JSON payload |
| `{topic.N}` | Level `N` of the source topic (1-based) |
| `{source_topic}` | The source topic |
| `{timestamp}` | The current time as ISO 8601 text (UTC) |
| `{env.NAME}` / `{secret.NAME}` | An environment variable or a secret |

Each placeholder goes in as one JSON value, so a payload cannot change the structure of the query, and values are stored as sent:

* **Unquoted** (`value: {payload.json.value}`): a JSON number, `true`, `false`, or `null` keeps its type. A JSON object or array goes in as that JSON. Any other text is stored as a string, with its quotes, apostrophes, commas, braces, and backslashes. Text such as `{topic}` inside a value is not expanded.
* **Quoted** (`text: \"{payload}\"`): always one JSON string, whatever the payload holds. Quote free text that goes into a search, so a payload is searched for as text.

Dates and other values are stored and returned exactly as sent. A date string such as `2026-01-02T03:04:05.678+02:00` keeps its offset in the document and in search results.

> [!WARNING]
>
> An unquoted placeholder whose value is a JSON object goes into the query as an object, so a publisher can set query options. Quote placeholders that must stay text, and do not build `index` from a payload. Keep untrusted publishers off the event's source topic with a [rule](https://docs.coreflux.org/latest/lot-language/rules/overview).

***

## Writing Data

> [tab] Whole Payload
>
> Index each JSON payload with its line and the time it arrived:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR PlantEvents WITH TYPE OPENSEARCH
>     ADD OPENSEARCH_CONFIG
>         WITH BASE_URL GET ENV "OPENSEARCH_URL"
>         WITH USERNAME GET ENV "OPENSEARCH_USER"
>         WITH PASSWORD GET SECRET "OPENSEARCH_PASSWORD"
>     ADD EVENT StoreEvent
>         WITH SOURCE_TOPIC "plant/+/events"
>         WITH DESTINATION_TOPIC "plant/+/events/indexed"
>         WITH QUERY "CLEAN:{index: plant_events, body: {line: {topic.2}, received: {timestamp}, data: {value.json}}}"
> ```
>
> Each index request publishes a result to `DESTINATION_TOPIC`:
>
> ```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> {"success": true, "documentId": "3f2b9c1e-7d4a-4b8e-9a61-0c5d2e8f4a17", "index": "plant_events", "result": "created", "shards": {"total": 2, "successful": 1, "failed": 0}}
> ```

> [tab] One Document per Machine
>
> Use the machine name as the document ID, so each update replaces the machine's document:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR MachineState WITH TYPE OPENSEARCH
>     ADD OPENSEARCH_CONFIG
>         WITH BASE_URL GET ENV "OPENSEARCH_URL"
>         WITH USERNAME GET ENV "OPENSEARCH_USER"
>         WITH PASSWORD GET SECRET "OPENSEARCH_PASSWORD"
>     ADD EVENT StoreState
>         WITH SOURCE_TOPIC "machines/+/state"
>         WITH QUERY "CLEAN:{index: machine_state, id: {topic.2}, body: {machine: {topic.2}, state: {payload.json.state}, at: {timestamp}}}"
> ```

> [tab] Self-Signed Certificate
>
> Connect to a test cluster with a self-signed certificate:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR TestSearch WITH TYPE OPENSEARCH
>     ADD OPENSEARCH_CONFIG
>         WITH BASE_URL "https://localhost:9200"
>         WITH USERNAME "iot_writer"
>         WITH PASSWORD GET SECRET "OPENSEARCH_PASSWORD"
>         WITH IGNORE_CERT_ERRORS "true"
>     ADD EVENT IndexData
>         WITH SOURCE_TOPIC "data/#"
>         WITH QUERY "CLEAN:{index: test_data, body: {topic: {source_topic}, payload: {value.json}, at: {timestamp}}}"
> ```
>
> > [!WARNING]
> >
> > Use `IGNORE_CERT_ERRORS` only in a test setup. In production, install the cluster's CA on the broker host.

> [!NOTE]
>
> **Alternative: STORE IN with Models.** Instead of writing an index query, bind a [model](https://docs.coreflux.org/latest/lot-language/models/overview) to this connector. Each model update indexes one new document with the model's fields into the index named by `WITH TABLE`, plus a UTC `timestamp` unless the model has a `timestamp` field. OpenSearch creates the index on first use:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE MODEL LineReading COLLAPSED WITH TOPIC "plant/line1/reading"
>     ADD STRING "sensor" WITH TOPIC "plant/line1/sensor"
>     ADD INT "count" WITH TOPIC "plant/line1/count"
>     ADD DOUBLE "speed" WITH TOPIC "plant/line1/speed" AS TRIGGER
>     STORE IN "PlantSearch"
>         WITH TABLE "line-readings"
> ```
>
> `STORE IN` keeps the hyphen, so this writes to `line-readings`. See [Data Storage Overview](https://docs.coreflux.org/latest/connectors/data-storage/overview#step-2-store-data) for the full STORE IN workflow.

### When a field changes type

OpenSearch builds the index mapping from the first document. If a field later changes type, for example a number becomes text, OpenSearch refuses the documents that do not fit. Each refusal is logged with OpenSearch's reason, such as `mapper_parsing_exception: failed to parse field [count] of type [long]`. Use a new index, or reindex.

***

## Reading Data

A search event reads documents on demand. Publish to its `SOURCE_TOPIC`, and the matching documents are published to `DESTINATION_TOPIC` as one JSON array:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR PlantSearch WITH TYPE OPENSEARCH
    ADD OPENSEARCH_CONFIG
        WITH BASE_URL "https://opensearch.example.com:9200"
        WITH USERNAME "iot_writer"
        WITH PASSWORD GET SECRET "OPENSEARCH_PASSWORD"
    ADD EVENT SearchNotes
        WITH SOURCE_TOPIC "notes/search"
        WITH DESTINATION_TOPIC "notes/search/result"
        WITH QUERY "CLEAN:{index: notes, query: {match_phrase: {text: \"{payload}\"}}, _source: [author, text], size: 20}"
```

To run it, publish the text to search for:

```
Topic:   notes/search
Payload: bearing temperature
```

The result is the `_source` of each hit:

```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
[{"author": "line2-operator", "text": "Bearing temperature above limit on press 4"}]
```

### Plain JSON queries

Write the query as JSON, with its quotes escaped for the LoT string:

```lot wrap focus={6-8} theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR PlantSearch WITH TYPE OPENSEARCH
    ADD OPENSEARCH_CONFIG
        WITH BASE_URL "https://opensearch.example.com:9200"
        WITH USERNAME "iot_writer"
        WITH PASSWORD GET SECRET "OPENSEARCH_PASSWORD"
    ADD EVENT FindOrder
        WITH SOURCE_TOPIC "orders/find"
        WITH DESTINATION_TOPIC "orders/find/result"
        WITH QUERY "{\"index\": \"orders\", \"query\": {\"term\": {\"order_id.keyword\": \"{payload}\"}}, \"size\": 1}"
```

### Paging and sorting

Take the range and the page from the payload:

```lot wrap focus={6-8} theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR PlantSearch WITH TYPE OPENSEARCH
    ADD OPENSEARCH_CONFIG
        WITH BASE_URL "https://opensearch.example.com:9200"
        WITH USERNAME "iot_writer"
        WITH PASSWORD GET SECRET "OPENSEARCH_PASSWORD"
    ADD EVENT ReadingsPage
        WITH SOURCE_TOPIC "readings/page"
        WITH DESTINATION_TOPIC "readings/page/result"
        WITH QUERY "CLEAN:{index: readings, query: {range: {value: {gte: {payload.json.min}}}}, sort: [{at: {order: desc}}], from: {payload.json.from}, size: 50}"
```

### Timed Polling

An `EVERY` event runs the same search on a schedule:

```lot wrap focus={6-8} theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR PlantSearch WITH TYPE OPENSEARCH
    ADD OPENSEARCH_CONFIG
        WITH BASE_URL "https://opensearch.example.com:9200"
        WITH USERNAME "iot_writer"
        WITH PASSWORD GET SECRET "OPENSEARCH_PASSWORD"
    ADD EVENT LatestAlarm
        WITH EVERY 1 MINUTE
        WITH DESTINATION_TOPIC "alarms/latest"
        WITH QUERY "CLEAN:{index: alarms, sort: [{at: {order: desc}}], size: 1}"
```

### Query patterns

| SQL equivalent | OpenSearch CLEAN syntax |
| - | - |
| `SELECT *` | `query: {match_all: {}}`, or leave `query` out |
| `WHERE a = 1` | `query: {term: {a: 1}}` |
| `WHERE a > 10` | `query: {range: {a: {gt: 10}}}` |
| `ORDER BY a DESC` | `sort: [{a: {order: desc}}]` |
| `LIMIT 10` | `size: 10` |
| `OFFSET 5` | `from: 5` |

### When an event fails

A request that OpenSearch refuses, such as a bad query, a mapping conflict, `403`, or `429`, or a request that cannot reach OpenSearch, fails the event. Nothing is published, the error is logged, and the event's `ON ERROR` block runs. The error carries OpenSearch's own type and reason, for example:

```
OpenSearch at https://opensearch.example.com:9200 refused a search of 'readings' (400 BadRequest). parsing_exception: unknown query [nosuchquery]
```

The same message is kept as the connector's last error. A refused `STORE IN` document is logged the same way. Requests are not retried.

***

## While OpenSearch is unreachable

A request that cannot reach OpenSearch (refused, unreachable, a TLS failure, or no answer within the timeout) marks the connector disconnected. An answer that is an error, such as `400`, `403`, or `429`, leaves it connected, because the server answered.

After a connection failure, the next event or `STORE IN` checks OpenSearch at once. If OpenSearch answers, the work runs. If not, the work is skipped and later checks run at most every 5 seconds. Work that arrives between checks is skipped instead of each request waiting out a timeout.

Each check logs how many events and `STORE IN` documents were skipped: a warning while OpenSearch is still down, and an information line with the total when the connector reconnects.

A removed or redeployed connector closes its connections.

***

## Checking the connection

`-checkConnectorConnection <Name>` sends `GET /` with the connector's own settings and login. The check passes when OpenSearch answers, and also on `403`: the login was accepted, and the user only lacks cluster permissions, which the connector does not need. The reply names the endpoint (scheme, host, port, and path), never the login. The check waits at most 8 seconds.

```
Topic:   $SYS/Coreflux/Command
Payload: -checkConnectorConnection PlantSearch
```

A failed check says what to look at: authentication, TLS, a refused connection, an unknown host, or no answer. A timeout says how many seconds it waited: `CONNECTION_TIMEOUT` while connecting, `REQUEST_TIMEOUT` once connected.

***

## Troubleshooting

> [accordion] Deploy refused
>
> * Put the scheme and port in `BASE_URL`, with no login, query, or fragment
> * Move a login from `BASE_URL` to `USERNAME` and `PASSWORD`
> * Remove `USE_SSL`, or make it match the scheme of `BASE_URL`

> [accordion] Authentication failed
>
> * Check `USERNAME` and `PASSWORD`
> * A `GET SECRET` that is not set leaves `PASSWORD` empty, which fails the same way

> [accordion] TLS handshake failed
>
> * Install the cluster's CA on the broker host
> * For a self-signed certificate in a test setup, set `IGNORE_CERT_ERRORS "true"`
> * "Closed the connection" usually means `http://` against an HTTPS port, or the reverse. Fix the scheme in `BASE_URL`.

> [accordion] Connection refused or no answer
>
> * Check that OpenSearch is running and listening on that host and port. Managed services often use port 443.
> * Check that a firewall allows the connection
> * Raise `CONNECTION_TIMEOUT` for a slow link

> [accordion] 403 Forbidden on an event
>
> * Grant the user the index permission it needs on that index pattern. See [Credentials](#credentials).
> * Name the `index` in every search

> [accordion] A search event writes documents
>
> * The query has both `index` and `body`. Move the search options out of `body`, next to `index`.

> [accordion] Documents land in my\_index instead of my-index
>
> * Event index names turn hyphens into `_`. Use underscores, or `STORE IN`, which keeps hyphens.

> [!WARNING]
>
> **Not supported:** update by query, delete, bulk requests, publishing aggregation results, API keys, AWS SigV4 signing, client certificates, and retries.

***

## Next Steps

> [card] [Data Storage Connectors Overview](https://docs.coreflux.org/latest/connectors/data-storage/overview)
>
> Compare all storage options.

> [card] [CrateDB Connector](https://docs.coreflux.org/latest/connectors/data-storage/cratedb.md)
>
> Configure CrateDB for time-series data.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.