# Spreadsheet & JSON Query Engine for AI Agents (`geeky_goth_gamer/spreadsheet-json-query-engine`) Actor

Profile, filter, aggregate or SQL-query CSV, Excel, JSON and NDJSON (inline or from a URL) and diff two tables — without loading the whole file into a language model. Exact counts, sandboxed read-only SQL, and bounded results. $0.003 inline or $0.005 per URL.

- **URL**: https://apify.com/geeky_goth_gamer/spreadsheet-json-query-engine.md
- **Developed by:** [Chris Day](https://apify.com/geeky_goth_gamer) (community)
- **Categories:** AI, Developer tools, Automation
- **Features:** Limited permissions, Single-tenant, Server interface
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.00 / 1,000 query inlines

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Spreadsheet & JSON Query Engine for AI Agents

Give this Actor a **CSV, TSV, Excel (.xlsx), JSON or NDJSON** file — inline or from a public URL — and it will **profile** the table, run a **structured or sandboxed SQL query**, or **diff** two datasets. Exact row counts, column stats, aggregations and bounded result sets come back as JSON, so a language model does not have to load a giant spreadsheet into its context window or guess at a total.

It does **not** call a language model. Loading, typing, querying and diffs are deterministic.

### When an AI agent should use this

Use `geeky_goth_gamer/spreadsheet-json-query-engine` when:

- You have a CSV, Excel workbook, JSON array or NDJSON dump that is too large (or too easy to miscount) to paste into the model.
- You need an exact `row_count`, per-column types/nulls/distinct values, numeric min/max/sum/mean/median, or a few sample rows.
- You want to filter, sort, group or aggregate without writing SQL, or you want to run a read-only `SELECT` / `WITH ... SELECT` (including joins across Excel sheets).
- You need to compare two versions of a table (added / removed / changed rows, schema changes, numeric sum deltas).

Don't use it for:

- Writing back to a file, or any SQL that is not a single `SELECT`.
- Private, intranet or metadata URLs (they are rejected).
- Legacy `.xls` workbooks (save as `.xlsx`) or files larger than 25 MB.

**Example input:**

```json
{
  "mode": "query",
  "format": "csv",
  "data": "region,units,price\nTasmania,3,10.5\nTasmania,1,10.5\nVictoria,2,8\n",
  "sql": "SELECT region, SUM(units) AS units, ROUND(AVG(price), 2) AS avg_price FROM data GROUP BY region ORDER BY units DESC"
}
```

**Output:** A single dataset item with `status`, compact `source` metadata (row/column counts and the original→SQL-safe `columnMap`), the result `rows`, and `truncated` if `maxRows` was hit. Profile mode adds per-column stats and `sampleRows`. Diff mode adds `addedCount` / `removedCount` / `changedCount`, `schema`, `sumDeltas` and bounded samples.

**Cost:** $0.003 per inline profile, query or diff; $0.005 per public URL fetched (a two-URL diff charges twice). Invalid input is not billed. Apify also charges the standard $0.00005 Actor-start fee on ordinary runs.

**Call it from an agent:**

- Apify MCP server: add `https://mcp.apify.com/?tools=geeky_goth_gamer/spreadsheet-json-query-engine` to your MCP client; the tool is `geeky_goth_gamer--spreadsheet-json-query-engine`. Or use `call-actor` with `"actor": "geeky_goth_gamer/spreadsheet-json-query-engine"`.
- Standby HTTP: `POST https://geeky-goth-gamer--spreadsheet-json-query-engine.apify.actor/query` (also `POST /profile`, `POST /diff`) with `Authorization: Bearer YOUR_TOKEN` and the input JSON. `GET /health` is a liveness check.
- Python: `ApifyClient(token).actor("geeky_goth_gamer/spreadsheet-json-query-engine").call(run_input=...)`, then read `client.dataset(run["defaultDatasetId"]).list_items().items`.
- HTTP run: `POST https://api.apify.com/v2/acts/geeky_goth_gamer~spreadsheet-json-query-engine/run-sync-get-dataset-items?token=YOUR_TOKEN` with the input JSON as the body.

### Why this exists

Agents miscount rows, drop filters, and blow their context window when they ingest a whole spreadsheet. This Actor loads the file once (inline or SSRF-safe URL, 25 MB cap), flattens nested JSON, normalises headers to SQL-safe names, infers types, and then either profiles the table, runs a structured query, or executes a **read-only, sandboxed** `SELECT` against in-memory SQLite (`table data`, plus named sheets). A second dataset can be diffed with optional key columns.

### Input

| Field | Default | Notes |
|---|---|---|
| `mode` | `query` | `profile`, `query` or `diff`. Standby routes set this for you. |
| `data` / `url` | (one required) | Inline text (or a JSON array/object on the HTTP API) **or** one public `http(s)` URL. Not both. Max 25 MB. |
| `format` | `auto` | `csv`, `tsv`, `xlsx`, `json`, `ndjson` (or `jsonl`). |
| `jsonPath` | (none) | Dot-path to the records inside a JSON payload, e.g. `items` or `data.rows`. |
| `sheet` | (none) | Load only this Excel sheet; otherwise every sheet is a SQL table (first sheet is also `data`). |
| `sql` | (none) | A single `SELECT` or `WITH ... SELECT`. Do not also pass structured filters. |
| `filters` | (empty) | `{column, op, value}` with `eq`/`neq`/`gt`/`gte`/`lt`/`lte`/`contains`/`in`/`is_null`/`not_null`. |
| `groupBy` / `aggregations` / `sortBy` | (empty) | Aggregations: `count`, `sum`, `avg`, `min`, `max`, `count_distinct`. |
| `limit` / `maxRows` | 200 | Output cap, 1–1000. |
| `sampleRows` | 5 | Profile (and query preview) sample size. |
| `left` / `right` | (diff) | Each is `{url}` or `{data}` plus optional `format` / `jsonPath` / `sheet`. |
| `keyColumns` | (none) | Diff keys so changed rows can be reported (without keys, only added/removed multisets). |
| `timeoutSeconds` | 30 | Download time limit. |
| `maxFileSizeMb` | 25 | Download / inline size cap. |

### Output

The default dataset holds one envelope. Common fields: `status`, `mode`, `source`, `billed`, `eventsCharged`, `durationSeconds`.

- **profile:** `rowCount`, `columnCount`, `duplicateRowCount`, `columns` (inferred type, null/distinct counts, numeric stats, `topValues`), `sampleRows`.
- **query:** `columns`, `rows`, `rowCount`, `truncated`, the SQL that ran (`sql`).
- **diff:** `addedCount`, `removedCount`, `changedCount`, `schema` (`addedColumns`, `removedColumns`, `typeChanges`), `sumDeltas`, and bounded `addedSample` / `removedSample` / `changedSample`.

### Standby / Server mode

When started through Apify's server interface (`APIFY_META_ORIGIN=STANDBY`), the Actor listens on `ACTOR_WEB_SERVER_PORT` and handles:

- `GET /health` — liveness
- `POST /profile` — profile a table
- `POST /query` — structured or SQL query
- `POST /diff` — compare two datasets
- Any request carrying the `x-apify-container-server-readiness-probe` header is answered immediately with HTTP 200 and body `ok`

Standby URL: `https://geeky-goth-gamer--spreadsheet-json-query-engine.apify.actor`

### Pricing

| Event | Price | When it is charged |
|---|---|---|
| `query-inline` (primary) | **US$0.003** | One successful inline profile, query or diff. |
| `query-url` | **US$0.005** | One successful URL-fetched file (a two-URL diff charges 2). |
| `apify-actor-start` | US$0.00005 (Apify default) | Once when a standard run starts. |

Failed input (the Actor refused the request) is not billed. Your maximum cost per run is respected.

### Safety

URL fetches are SSRF-safe: only `http`/`https` on standard ports, every redirect hop is re-validated, and private, loopback, link-local, CGNAT and cloud-metadata addresses are blocked. Downloads and inline payloads are size- and time-capped. Excel workbooks are opened in `read_only` mode after zip-bomb / oversized-part checks.

SQL runs against in-memory SQLite with `conn.set_authorizer(...)` allowing only `SELECT` / `READ` and a tight function allowlist. `ATTACH`, `DETACH`, `PRAGMA`, `INSERT`/`UPDATE`/`DELETE`, `DROP`/`CREATE`/`ALTER`, `VACUUM`, `load_extension` and multi-statement SQL are rejected. A progress-handler time limit (2 s) and `maxRows` cap stop hostile or cartesian queries from tying up the process.

### Limitations

- Legacy `.xls` is not supported; save as `.xlsx`.
- Very wide (over 200 columns) or very tall (over 200,000 rows) tables are rejected.
- Nested JSON arrays are flattened as a JSON string in one cell; objects are flattened with dot notation.
- Without `keyColumns`, a diff cannot pair “changed” rows and reports only added/removed counts.
- The SQL sandbox is intentionally narrow: useful analytics functions are allowed, write and extension APIs are not.

# Actor input Schema

## `mode` (type: `string`):

REQUIRED for a standard run (Standby paths set this for you). "profile" returns exact counts and per-column stats. "query" runs structured filters/aggregations or sandboxed SQL. "diff" compares left and right datasets.

## `data` (type: `string`):

Optional. The file contents as text (CSV/TSV/JSON/NDJSON). For JSON you can also pass a JSON object/array via the HTTP API. Do not also pass url. Max 25 MB. For Excel, pass a url to a public .xlsx file.

## `url` (type: `string`):

Optional. One public http(s) file to fetch (CSV, TSV, .xlsx, JSON or NDJSON). Private, loopback and metadata addresses are rejected. Max 25 MB.

## `format` (type: `string`):

"auto" (default) sniffs the format from the filename, content-type or contents. Set this when sniffing would be wrong.

## `jsonPath` (type: `string`):

Optional. Dot-path to the array (or object) of records inside a JSON payload, e.g. "items" or "data.rows". Nested objects are flattened with dot notation.

## `sheet` (type: `string`):

Optional. For .xlsx workbooks, load only this sheet. Otherwise every sheet becomes a SQL table (first sheet is also available as data).

## `sql` (type: `string`):

Optional, query mode. A single SELECT or WITH ... SELECT against table data (plus named sheets). Read-only sandbox: ATTACH, PRAGMA, INSERT/UPDATE/DELETE/DROP/CREATE, load_extension and multi-statement SQL are rejected. A 2-second time limit and maxRows cap apply. Do not also pass structured filters.

## `filters` (type: `array`):

Optional, query mode. List of {"column", "op", "value"}. ops: eq, neq, gt, gte, lt, lte, contains, in, is_null, not_null. Combined with AND. Values are bound as parameters.

## `groupBy` (type: `array`):

Optional, query mode. Column names to group by (original or SQL-safe names).

## `aggregations` (type: `array`):

Optional, query mode. List of {"fn", "column", "alias"}. fn: count, sum, avg, min, max, count_distinct. For count of rows, omit column.

## `sortBy` (type: `array`):

Optional. List of {"column", "direction": "asc"|"desc"}.

## `limit` (type: `integer`):

Max rows returned for a structured query (1–1000). Default 200.

## `maxRows` (type: `integer`):

Hard cap on rows returned from SQL (1–1000). Default 200.

## `sampleRows` (type: `integer`):

How many sample rows to include in a profile (or in a query preview). Default 5, max 50.

## `left` (type: `object`):

Required in diff mode. Object with url or data, plus optional format, jsonPath, sheet.

## `right` (type: `object`):

Required in diff mode. Same shape as left.

## `keyColumns` (type: `array`):

Optional, diff mode. Column(s) that identify a row so the engine can report changed records (not just added/removed).

## `timeoutSeconds` (type: `integer`):

Download time limit when url (or left/right url) is set.

## `maxFileSizeMb` (type: `integer`):

Larger downloads or inline payloads are rejected. Default and maximum 25 MB.

## Actor input object example

```json
{
  "mode": "query",
  "data": "region,units,price\nTasmania,3,10.5\nTasmania,1,10.5\nVictoria,2,8\n",
  "format": "auto",
  "sql": "SELECT region, SUM(units) AS units, ROUND(AVG(price), 2) AS avg_price FROM data GROUP BY region ORDER BY units DESC",
  "limit": 200,
  "maxRows": 200,
  "sampleRows": 5,
  "timeoutSeconds": 30,
  "maxFileSizeMb": 25
}
```

# Actor output Schema

## `results` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "mode": "query",
    "data": `region,units,price
Tasmania,3,10.5
Tasmania,1,10.5
Victoria,2,8`,
    "sql": "SELECT region, SUM(units) AS units, ROUND(AVG(price), 2) AS avg_price FROM data GROUP BY region ORDER BY units DESC"
};

// Run the Actor and wait for it to finish
const run = await client.actor("geeky_goth_gamer/spreadsheet-json-query-engine").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "mode": "query",
    "data": """region,units,price
Tasmania,3,10.5
Tasmania,1,10.5
Victoria,2,8
""",
    "sql": "SELECT region, SUM(units) AS units, ROUND(AVG(price), 2) AS avg_price FROM data GROUP BY region ORDER BY units DESC",
}

# Run the Actor and wait for it to finish
run = client.actor("geeky_goth_gamer/spreadsheet-json-query-engine").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "mode": "query",
  "data": "region,units,price\\nTasmania,3,10.5\\nTasmania,1,10.5\\nVictoria,2,8\\n",
  "sql": "SELECT region, SUM(units) AS units, ROUND(AVG(price), 2) AS avg_price FROM data GROUP BY region ORDER BY units DESC"
}' |
apify call geeky_goth_gamer/spreadsheet-json-query-engine --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,geeky_goth_gamer/spreadsheet-json-query-engine"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/0VcsfQSVzQP4pllrA/builds/bWfZbZjtOqGB9cxbk/openapi.json
