> ## 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.

# File Storage Connector

> Store MQTT data to local CSV and JSON files for simple persistence and backups

## File Storage Overview

The `FILE_STORAGE` connector writes MQTT messages to local CSV or JSON files. It provides simple persistence for logging, backups, and data export without requiring a database server.

> [!NOTE]
>
> File storage is ideal for simple logging, local backups, and exporting data for offline analysis. Use it when you don't need a full database but want persistent records.

## Basic Syntax

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR DataLogger WITH TYPE FILE_STORAGE
    ADD FILE_STORAGE_CONFIG
        WITH STORAGE_DIR "logs"
        WITH FORMAT "CSV"
        WITH FILE_PATTERN "{0}.csv"
        WITH APPEND "true"
    ADD EVENT LogSensorData
        WITH SOURCE_TOPIC "sensors/#"
        WITH QUERY "CLEAN:{table: sensor_data, data: {value.json}}"
```

***

## Connection Configuration

### FILE\_STORAGE\_CONFIG Parameters

**STORAGE\_DIR** `string` *required*

Directory for the files. Use a relative path such as `"logs"`: it resolves under the broker's storage root, so the same connector works on every host. See [Where files are written](#where-files-are-written).

> [accordion] Storage Location Options
>
> **FILE\_PATTERN** `string`
>
> File name pattern. `{0}` is replaced with the table name. Default: `{0}.csv` for CSV and `{0}.json` for JSON.
>
> `{0}` is the only placeholder. Others, such as `{date}`, are not supported: the connector fails when it writes. For daily files, publish to a table name that includes the date.

> [accordion] Format
>
> **FORMAT** `string`
>
> File format: `CSV` or `JSON`. Default: JSON.
>
> **CSV\_DELIMITER** `string`
>
> CSV delimiter character. Default: comma (`,`).

> [accordion] Write Options
>
> **APPEND** `boolean`
>
> Append to existing files. Default: true.
>
> **INCLUDE\_TIMESTAMP** `boolean`
>
> Add a `timestamp` field to each record, unless the record already has one. Default: true.
>
> **MAX\_RECORDS** `integer`
>
> JSON only: the most records a file keeps. Older records are dropped once the file is full. Default: 10000. Files are not rotated.

> [accordion] Timestamp
>
> **DATE\_FORMAT** `string`
>
> Timestamp format string. Default: `yyyy-MM-dd HH:mm:ss`.

> [!WARNING]
>
> **Use environment variables for paths in production.** Keep deployment-specific values out of your connector definitions:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> WITH STORAGE_DIR GET ENV "STORAGE_PATH"
> ```
>
> See [Environment Variables & Secrets](https://docs.coreflux.org/latest/mqtt-broker/secrets-and-env.md) for setup and usage.

***

## Where files are written

A relative `STORAGE_DIR` resolves under the broker's **storage root**, the `storage` folder in the broker's [data directory](https://docs.coreflux.org/latest/mqtt-broker/startup-options.md). Files then live with the rest of the broker's data. In Docker, that is the data volume, so they survive a container recreate.

| How the broker runs | Storage root | `WITH STORAGE_DIR "history"` writes to |
| - | - | - |
| Docker image | `/etc/project/storage` | `/etc/project/storage/history` |
| Debian package (systemd) | `/var/lib/coreflux/storage` | `/var/lib/coreflux/storage/history` |
| Windows service | `<install dir>\Coreflux\storage` | `<install dir>\Coreflux\storage\history` |
| Tarball or zip, no data directory set | `<binary dir>/Coreflux/storage` | `<binary dir>/Coreflux/storage/history` |

Setting `COREFLUX_DATA_PATH` (or `CONFIG_PATH`) moves the storage root with the data directory.

| `STORAGE_DIR` | Resolves to |
| - | - |
| Relative, such as `"history"` | `<storage root>/history`. `..` may not climb out of the storage root |
| Relative, and that folder already exists under the broker's working directory | The existing folder, with a deprecation warning in the log and in the deploy result. Earlier brokers resolved relative paths against the working directory, so this keeps an older deployment's files in place. **Action:** move the folder under the storage root when convenient |
| Absolute, such as `"/mnt/historian"` | Used as written. Check that it exists and that the broker can write there on that host |

The broker always refuses a `STORAGE_DIR` that points at the data directory itself, the install directory, or the broker's own `bin/`, `config/`, `projects/`, `log/`, `logs/`, `stats/`, or `cluster/` folders. A `FILE_PATTERN`, or a table name from an event query, that would place a file outside `STORAGE_DIR` (with `..` or an absolute path) is refused too.

Set the environment variable `COREFLUX_STORAGE_RESTRICT_TO_ROOT=true` to refuse every path outside the storage root, including absolute paths and the working-directory fallback. It is off by default so existing connectors with absolute paths keep working. Turn it on where AI assistants deploy connectors.

### Deploy checks the folder

When you add a `FILE_STORAGE` connector, the broker resolves `STORAGE_DIR`, creates the folder, and writes a test file before it accepts the connector. If that fails, the error names the storage root and a relative path to retry with:

```text wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
STORAGE_DIR "/data" resolves to '/data', which the broker cannot write (Read-only file system). Use a relative path such as WITH STORAGE_DIR "MachineStateHistory"; relative paths resolve under the broker storage root '/etc/project/storage'. The get_storage_locations MCP tool reports where this broker can write.
```

An AI assistant connected to the broker's [MCP Server](https://docs.coreflux.org/latest/mqtt-broker/mcp-server.md#what-the-tools-do) can call the read-only `get_storage_locations` tool first. It reports the OS, whether the broker runs in a container, the data directory and storage root (each with a write check and free space), and a recommended relative `STORAGE_DIR`.

***

## CLEAN Query Format

File storage connectors use the CLEAN format:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
WITH QUERY "CLEAN:{table: <name>, data: {value.json}}"
```

The `table` name is used in the file pattern with `{0}`.

***

## Writing Data

> [tab] CSV Logging
>
> Log sensor data to daily CSV files:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR CSVLogger WITH TYPE FILE_STORAGE
>     ADD FILE_STORAGE_CONFIG
>         WITH STORAGE_DIR "logs"
>         WITH FORMAT "CSV"
>         WITH FILE_PATTERN "{0}.csv"
>         WITH APPEND "true"
>         WITH CSV_DELIMITER ","
>         WITH INCLUDE_TIMESTAMP "true"
>         WITH MAX_RECORDS "10000"
>     ADD EVENT LogSensorData
>         WITH SOURCE_TOPIC "sensors/#"
>         WITH DESTINATION_TOPIC "file/status"
>         WITH QUERY "CLEAN:{table: sensor_data, data: {value.json}}"
> ```
>
> Creates `sensor_data.csv` under the storage root's `logs` folder.

> [tab] JSON Storage
>
> Store events as JSON lines:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR JSONLogger WITH TYPE FILE_STORAGE
>     ADD FILE_STORAGE_CONFIG
>         WITH STORAGE_DIR "json"
>         WITH FORMAT "JSON"
>         WITH FILE_PATTERN "{0}.json"
>         WITH APPEND "true"
>         WITH INCLUDE_TIMESTAMP "true"
>         WITH MAX_RECORDS "5000"
>     ADD EVENT LogEvents
>         WITH SOURCE_TOPIC "events/#"
>         WITH DESTINATION_TOPIC "file/json/status"
>         WITH QUERY "CLEAN:{table: events, data: {value.json}}"
> ```

> [tab] Multiple Files
>
> Connector to different files by data type:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR MultiFileLogger WITH TYPE FILE_STORAGE
>     ADD FILE_STORAGE_CONFIG
>         WITH STORAGE_DIR "logs"
>         WITH FORMAT "CSV"
>         WITH FILE_PATTERN "{0}.csv"
>         WITH APPEND "true"
>         WITH INCLUDE_TIMESTAMP "true"
>
>     ADD EVENT LogTemperature
>         WITH SOURCE_TOPIC "sensors/+/temperature"
>         WITH QUERY "CLEAN:{table: temperature, data: {value.json}}"
>
>     ADD EVENT LogPressure
>         WITH SOURCE_TOPIC "sensors/+/pressure"
>         WITH QUERY "CLEAN:{table: pressure, data: {value.json}}"
>
>     ADD EVENT LogAlerts
>         WITH SOURCE_TOPIC "alerts/#"
>         WITH QUERY "CLEAN:{table: alerts, data: {value.json}}"
> ```
>
> Creates `temperature.csv`, `pressure.csv`, and `alerts.csv`.

> [tab] Backup Storage
>
> Create a rolling backup file that keeps the newest records:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE CONNECTOR BackupStorage WITH TYPE FILE_STORAGE
>     ADD FILE_STORAGE_CONFIG
>         WITH STORAGE_DIR "backup/mqtt"
>         WITH FORMAT "JSON"
>         WITH FILE_PATTERN "{0}.json"
>         WITH APPEND "true"
>         WITH MAX_RECORDS "100000"
>         WITH INCLUDE_TIMESTAMP "true"
>     ADD EVENT BackupAll
>         WITH SOURCE_TOPIC "#"
>         WITH QUERY "CLEAN:{table: mqtt_backup, data: {value.json}}"
> ```

> [!NOTE]
>
> **Alternative: STORE IN with Models** — Instead of writing EVENT queries, you can bind a [model](https://docs.coreflux.org/latest/lot-language/models/overview) directly to this connector. Every `PUBLISH MODEL` call automatically inserts a row — no query needed:
>
> ```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
> DEFINE MODEL SensorReading
>     ADD STRING "sensor_id"
>     ADD DOUBLE "value"
>     STORE IN "DataLogger"
>         WITH TABLE "sensor_data"
> ```
>
> See [Data Storage Overview](https://docs.coreflux.org/latest/connectors/data-storage/overview#with-models-store-in) for the full STORE IN workflow.

***

## Reading Data

EVENTs also support read queries to retrieve data from stored files. Publish a message to the event's `SOURCE_TOPIC`, and the matching rows are published to `DESTINATION_TOPIC` as one JSON array. File Storage read queries use the CLEAN format with `filter`, `sort`, and `limit` instead of SQL.

A query is a **store** when its object has a top-level `data` key, and a **read** otherwise. A filter or projection that names a field called `data` is still a read. `filter`, `sort`, `skip`, `limit`, and `projection` apply to CSV and JSON files alike. CSV cells are compared as numbers when the value in the filter is a number, so `{count: {$gte: 7}}` works on a CSV file.

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR DataLogger WITH TYPE FILE_STORAGE
    ADD FILE_STORAGE_CONFIG
        WITH STORAGE_DIR "logs"
        WITH FORMAT "CSV"
        WITH FILE_PATTERN "{0}.csv"
        WITH APPEND "true"
    ADD EVENT GetLatestEntry
        WITH SOURCE_TOPIC "file/query/latest"
        WITH DESTINATION_TOPIC "file/result/latest"
        WITH QUERY "CLEAN:{table: sensor_data, filter: {\"sensor_id\": \"{payload}\"}, sort: {\"timestamp\": -1}, limit: 1}"
```

To trigger this query, publish the sensor ID to the source topic:

```
Topic:   file/query/latest
Payload: temp001
```

The matching record is published to `file/result/latest`, where your actions or external clients can consume it.

One connector can store and read the same table. The automatic column is `timestamp`, so sort by it to get the newest rows:

```lot wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
DEFINE CONNECTOR Packer01History WITH TYPE FILE_STORAGE
    ADD FILE_STORAGE_CONFIG
        WITH STORAGE_DIR "packer01_history"
        WITH FORMAT "CSV"
        WITH FILE_PATTERN "{0}.csv"
    ADD EVENT StorePacker01State
        WITH SOURCE_TOPIC "factory/packer01/state"
        WITH QUERY "CLEAN:{table: packer01_state, data: {value.json}}"
    ADD EVENT QueryPacker01State
        WITH SOURCE_TOPIC "historian/packer01/query"
        WITH DESTINATION_TOPIC "historian/packer01/result"
        WITH QUERY "CLEAN:{table: packer01_state, filter: {}, sort: {timestamp: -1}, limit: 100}"
```

Publish any message to `historian/packer01/query` to get the 100 newest rows on `historian/packer01/result`. An assistant on the MCP Server can run the read event directly with `run_connector` (`target`: `Packer01History.QueryPacker01State`).

### CLEAN Read Operators

| SQL Equivalent | File Storage CLEAN Syntax |
| - | - |
| `SELECT *` | `{"table": "x"}` |
| `WHERE a = 1` | `filter: {"a": 1}` |
| `WHERE a > 10` | `filter: {"a": {"$gt": 10}}` |
| `ORDER BY a DESC` | `sort: {"a": -1}` |
| `LIMIT 10` | `limit: 10` |
| `OFFSET 5` | `skip: 5` |
| `SELECT a, b` | `projection: {"a": 1, "b": 1}` |

`limit` is applied before `skip`: `limit: 10, skip: 5` returns rows 6 to 10 of the result.

***

## File Pattern Placeholders

| Placeholder | Description | Example |
| - | - | - |
| `{0}` | Table name from CLEAN query | `sensor_data` |

`{0}` is the only supported placeholder. A pattern with others, such as `{date}`, fails when the connector writes.

***

## Output Examples

### CSV Output

```csv wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
timestamp,sensor_id,temperature,humidity
2025-01-15 10:30:00,temp001,23.5,65
2025-01-15 10:30:05,temp002,24.1,62
```

### JSON Output (JSON Lines format)

```json wrap theme={"theme":{"light":"css-variables","dark":"css-variables"},"languages":{"custom":["/languages/lot.json"]}}
{"timestamp":"2025-01-15T10:30:00Z","sensor_id":"temp001","temperature":23.5,"humidity":65}
{"timestamp":"2025-01-15T10:30:05Z","sensor_id":"temp002","temperature":24.1,"humidity":62}
```

***

## Troubleshooting

> [accordion] Permission Denied
>
> * Use a relative `STORAGE_DIR` so files go under the storage root. See [Where files are written](#where-files-are-written)
> * For an absolute path, check that the folder exists and that the broker process can write there
> * Read the deploy error: it names the storage root and a relative path to retry with

> [accordion] File Not Created
>
> * Check where a relative `STORAGE_DIR` resolves on this host in [Where files are written](#where-files-are-written)
> * Look for a deprecation warning in the log: an older relative folder under the working directory is still used
> * Check disk space is available

> [accordion] Data Not Appearing
>
> * Verify SOURCE\_TOPIC matches incoming messages
> * Check QUERY syntax is correct
> * Verify APPEND is set correctly

> [accordion] Connector fails to write
>
> * `FILE_PATTERN` accepts only `{0}` (the table name). Remove other placeholders such as `{date}`.
> * For JSON, `MAX_RECORDS` caps the file and drops the oldest records. Files are not rotated.

***

## Next Steps

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

> [card] [PostgreSQL Connector](https://docs.coreflux.org/latest/connectors/data-storage/postgresql.md)
>
> Configure PostgreSQL database storage.


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