# Dataset Analyst (`nmanerikar/dataset-analyst`) Actor

Query Apify datasets with SQL or plain English. Narrow down large amounts of scraped data to the exact items matching your requirement. Perfect for AI agents: get exact results without filling up the context window.

- **URL**: https://apify.com/nmanerikar/dataset-analyst.md
- **Developed by:** [Nishad Manerikar](https://apify.com/nmanerikar) (community)
- **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 $10.00 / 1,000 natural language question answereds

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

### What is Dataset Analyst?

You ran a scraper and it worked well. Now thousands of rows are sitting in an Apify dataset, and you need answers: *How many products cost more than $50? Which cities have the most listings? What's the average rating per category?*

**Dataset Analyst** answers those questions. Ask in plain English, or write SQL yourself, and get a results table in seconds. You don't download the data or open a spreadsheet. It runs full **DuckDB SQL** over any Apify dataset, read straight from the dataset API, including nested JSON fields.

The easiest way to try it: select your dataset in the **Dataset** field (or leave the input empty and paste a Dataset ID in the page), run the Actor, open the **Live View** tab, and type a question.

![Dataset Analyst Live View: a geospatial question about a Google Maps dataset answered in seconds](https://api.apify.com/v2/key-value-stores/qviwjfKFPEsAwpbAc/records/dataset-analyst-live-view.gif?v=88a984bc)

### Query Apify datasets with SQL or plain English

Dataset Analyst is a SQL and natural-language analytics engine for Apify datasets. Use it to aggregate, filter, rank and group the rows of a dataset, and to join or unnest data within it, without writing any code to download it first.

- **Ask in plain English.** An AI model turns your question into DuckDB SQL, runs it, and shows you the results and the SQL it used. The model call is billed to your Apify account through the [`apify/openrouter`](https://apify.com/apify/openrouter) Actor, on top of this Actor's per-question price: typically under a cent per question on a paid Apify plan, and about 5 to 10 cents on the Free plan (see [pricing](#how-much-does-it-cost-to-query-a-dataset)).
- **Or write the SQL yourself** if you prefer. The full DuckDB dialect works, including `UNNEST` and spatial functions such as `ST_Distance`.
- **Works on nested data.** Fields inside other fields, and lists of values, can be queried directly. No flattening step.
- **Export anywhere.** Download results as JSON or CSV, or save them to a new Apify dataset for another Actor to use.
- **Runs on the Apify platform,** with scheduling, monitoring, an API, and integrations.

#### What can you ask?

Say you scraped every restaurant in Italy with the Google Maps Scraper. You could ask Dataset Analyst, in plain English:

- "How many pizza restaurants are in Rome?"
- "List the wine bars in Milan with their phone numbers."
- "Which restaurants in Florence have phone numbers but not websites?"
- "What are the 10 most common categories of restaurants in cities that have more than 1000 listings? Give the list per city"
- "List all restaurants rated 4 or higher within 3 km of the Colosseum, sorted by distance"

These range from a simple count to a filter, a ranking, a grouping over array fields, and a geospatial search, all asked the same way.

### Three ways to use it

The same engine runs as an interactive page, as a batch job, and as an HTTP API.

#### Live View: query a dataset with no code

1. Select your dataset in the **Dataset** field (or leave the input empty and paste a Dataset ID in the page) and run the Actor from Apify Console.
2. Open the **Live View** tab once the run starts. A dataset you selected is already filled in.
3. Type a question, or switch to the **SQL Query** tab. You can change the Dataset ID on the page at any time. Each question costs $0.01 plus the AI model usage billed to your account (under a cent on a paid plan, about 5 to 10 cents on the Free plan); SQL queries cost $0.01 only.
4. Read the results as a table, then download them as JSON or CSV, or save them to a dataset.
5. When you're done, just leave. The run shuts itself down after 5 minutes without a request, so you don't pay for idle time. To continue later, start a new run.

If your account's [General resource access](https://docs.apify.com/account/collaboration/general-resource-access) is set to Restricted (the default for new accounts), the run can read only the dataset selected in the input, so pick it there.

#### Batch mode: run many queries at once

Good for scheduled reports, pipelines, and AI agents. Give a `datasetId` and a list of `queries` as the Actor input. In Apify Console, `datasetId` is the **Dataset** picker; through the API or MCP, you pass the dataset ID as a string. Each query has a `type`, either `ask` (plain English) or `sql` (raw SQL), and a `query` string:

```json
{
    "datasetId": "your-dataset-id",
    "queries": [
        { "type": "ask", "query": "What are the top 5 categories by average price?" },
        { "type": "sql", "query": "SELECT city, COUNT(*) AS n FROM input_dataset GROUP BY city" }
    ]
}
```

Each query's rows are saved to a new dataset, and the run's default dataset gets one summary row per query. A failed query is reported with its error and doesn't stop the rest. Optional inputs: `maxRows`, `llmModel`, `dataSampling`.

#### Standby API: query datasets over HTTP

In Standby mode the Actor stays available at `https://nmanerikar--dataset-analyst.apify.actor`. Send a plain-English question to `POST /ask`, raw SQL to `POST /query`, or ask for the column list with `POST /schema`. Examples are in the next section, and the full OpenAPI description is on the [API tab](https://apify.com/nmanerikar/dataset-analyst/api) of the [Dataset Analyst page](https://apify.com/nmanerikar/dataset-analyst).

### Dataset analytics for AI agents and MCP

Dataset Analyst lets an AI agent **answer questions over datasets that are far too large to fit in its context window**. The filtering, counting and aggregation happen on the server, and the agent gets back only the small result.

In every query, the dataset is the SQL table **`input_dataset`**. Write `FROM input_dataset`; never put the dataset ID in the SQL.

#### Through the Apify MCP server or API (batch mode)

When an agent calls this Actor as a tool through the [Apify MCP server](https://mcp.apify.com), or starts a run through the Apify API, the Actor runs in batch mode:

1. Run the Actor with input `{ "datasetId": "...", "queries": [ { "type": "ask" | "sql", "query": "..." } ] }`.
2. Read the run's default dataset. It holds one summary row per query with these fields: `queryNumber`, `status` (`ok` or `error`), `type`, `query`, `generatedQuery` (the SQL that ran), `rowCount`, `datasetId`, `datasetLink`, `error`, `warning`.
3. Fetch the result rows from the dataset named in that row's `datasetId`.

A `warning` means the source dataset wasn't loaded in full, so counts may be too low.

#### Over HTTP (Standby API)

Send JSON to the Standby URL with your Apify token in the `Authorization` header and in the `token` field. The Actor runs with limited permissions, so it reads your dataset with the token you send, not with its own:

```bash
curl -X POST https://nmanerikar--dataset-analyst.apify.actor/query \
  -H "Authorization: Bearer $APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"datasetId": "your-dataset-id", "token": "'"$APIFY_TOKEN"'", "query": "SELECT category, COUNT(*) AS n FROM input_dataset GROUP BY category ORDER BY n DESC"}'

curl -X POST https://nmanerikar--dataset-analyst.apify.actor/ask \
  -H "Authorization: Bearer $APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"datasetId": "your-dataset-id", "token": "'"$APIFY_TOKEN"'", "question": "Which 2 categories have the highest average price?"}'
```

`POST /schema` with `{"datasetId": "your-dataset-id"}` returns `columns`, a list of `{ "name", "type" }` objects. Call it first when you don't know the field names.

Optional request fields:

- `saveToNewDataset: true` saves the rows to a new dataset and returns its ID as `savedDatasetId`. Use it to keep a large result out of the context window.
- `format: "csv"` (`/query` only) returns CSV instead of JSON.
- `maxRows`: how many items to read from the dataset (default 100,000).
- `cacheDataset: false` re-reads the dataset on every request, for datasets that are still changing.
- `token`: the Apify token used to read the dataset (and, on `/ask`, to bill the model call to). Required for your own datasets in Standby mode, see above.
- `/ask` also accepts `model` and `dataSampling`.

#### Response format

A successful response looks like this:

```json
{
    "success": true,
    "generatedQuery": "SELECT category, AVG(price) AS avg_price FROM input_dataset GROUP BY category ORDER BY avg_price DESC LIMIT 2",
    "executionTimeMs": 1250,
    "rowCount": 2,
    "data": [
        { "category": "Laptops", "avg_price": 934.51 },
        { "category": "Speakers", "avg_price": 288.4 }
    ],
    "datasetStats": { "itemCount": 1000, "loadedRows": 1000, "skippedRows": 0, "rowLimit": 100000, "truncated": false }
}
```

- `generatedQuery`: `/ask` only.
- `datasetStats`: how much of the dataset was loaded (present when caching is on, the default).
- `warnings`: a list of strings, present when rows were skipped or the dataset was cut off at `maxRows`.
- `savedDatasetId`: present when you set `saveToNewDataset`.
- Errors look like `{ "success": false, "error": "SQL Syntax Error", "details": "..." }`, with an HTTP status such as 400 (bad request or SQL error), 403 (statement not allowed), 404 (dataset not found) or 402 (your spending limit was reached). A failed `/ask` may also include the `generatedQuery`.

#### Limits

- 100,000 rows are read per query by default. Raise it with `maxRows`; the dataset is loaded into memory, so large values need more memory.
- One dataset per query. JOINs across datasets aren't supported yet.
- Default run memory is 4 GB.
- Only `SELECT` and `WITH` statements run. Anything else is rejected.
- A Live View run ends after 5 minutes without a request.
- `/ask` needs an Apify token for the AI model call. The run's own token is used by default, so your account pays, unless you send a `token`.

### Example input and output

A dataset of scraped products:

```json
[
    { "title": "Nimbus Wireless Headphones", "category": "Headphones", "price": 89.9, "rating": 4.6, "inStock": true },
    { "title": "Vertex Studio Speaker", "category": "Speakers", "price": 279.0, "rating": 4.2, "inStock": false },
    { "title": "Aero 14 Laptop", "category": "Laptops", "price": 899.0, "rating": 4.4, "inStock": true },
    ...
]
```

Ask *"average price per category, most expensive first"*. Dataset Analyst writes and runs this SQL:

```sql
SELECT category, AVG(price) AS avg_price FROM input_dataset GROUP BY category ORDER BY avg_price DESC
```

and returns:

```json
[
    { "category": "Laptops", "avg_price": 934.51 },
    { "category": "Speakers", "avg_price": 288.4 },
    { "category": "Headphones", "avg_price": 121.75 }
]
```

### How much does it cost to query a dataset?

Dataset Analyst uses [pay-per-event](https://docs.apify.com/actors/monetize) pricing: you pay per query plus a tiny start fee, not for compute time.

| Event | When it's charged | Price (USD) |
| --- | --- | --- |
| Actor start | Once per run, per GB of run memory (minimum one). At the default 4,096 MB, a run costs $0.0002 to start. | $0.00005 |
| SQL query executed | Each raw SQL query: the `/query` endpoint, the SQL Query tab, and `sql` batch queries. | $0.01 |
| Natural language question answered | Each plain-English question: the `/ask` endpoint, the Ask tab, and `ask` batch queries. | $0.01 |
| Batch summary row | Batch mode only: each summary row written to the run's default dataset (one per query). Charged automatically by the platform. | $0.00001 |

**SQL queries** involve no AI model, so they cost only the $0.01 event.

**Plain-English questions** have a second cost. The AI model call goes through the [`apify/openrouter`](https://apify.com/apify/openrouter) Actor and is billed to your own Apify account as usage of that Actor (the "AI model tokens" event, priced at the model's real token cost), on top of the $0.01 event. It appears on your bill as `apify/openrouter`, not as Dataset Analyst. Only column names, types and a few sample values are sent: a typical question is about 2,300 prompt tokens plus a short SQL answer, which at the default model's (`anthropic/claude-sonnet-5.5`) list price is under a cent. **What you are charged depends on your Apify plan.** On paid plans the OpenRouter Actor bills close to the model's price, so expect under a cent per question. On the **Free plan** it bills at a higher free-tier rate, which in our measurements came to **5 to 10 cents per question**; the monthly free credit still covers roughly 50 questions. Datasets with many columns cost more. A cheaper `llmModel` (for example `anthropic/claude-haiku-5.5`) lowers it, but cheaper models are often less reliable at writing correct SQL over nested data. A question the model judges unrelated to the dataset is still charged, because the model was called.

Example: a Live View session with 10 questions and 10 SQL queries costs about $0.20 in events, plus model usage of roughly $0.10 on a paid plan or $0.50 to $1.00 on the Free plan.

The Apify Free plan's monthly credit covers both charges, so you can try Dataset Analyst at no cost. Current prices are always shown on the Actor's page on Apify Store.

### Privacy and data handling

For a plain-English question, the Actor sends the AI model each column's name and type, plus a few example values per column taken from the first 100 rows by default. Whole rows are never sent. Set `dataSampling` to a smaller number to sample fewer rows, or to `0` to send no scraped values to the AI model on OpenRouter. SQL queries never leave the Apify platform.

### Tips for better results

- **Be specific.** "Show me the 5 cheapest phones with at least 4 stars" beats "find cheap phones".
- **Use the real field names.** If the dataset has a `price` field, say "price" in your question.
- **Start simple.** Ask for 5 rows first to see the columns, then ask targeted questions.
- **Keep caching on** (the default) so repeat queries on the same dataset stay fast.

### FAQ

#### Which datasets does it work with?

Your own datasets, datasets shared with you, and public datasets. The Actor runs with [limited permissions](https://docs.apify.com/actors/development/permissions), so what its own token can read depends on your account's [General resource access](https://docs.apify.com/account/collaboration/general-resource-access) setting. On a Restricted account (the default for new accounts), a run can read only the dataset selected in the **Dataset** input field; in the Standby API, it can read any dataset the `token` you send can read. If your account allows anyone with the ID to read, a pasted Dataset ID (the code in its URL) also works. A dataset name (`username~name`) always needs a personal token.

#### Is my data sent to an AI model?

Only for plain-English questions, and only column names, types and a few sample values. You can turn the sampling off. Raw SQL stays on the Apify platform. See [Privacy and data handling](#privacy-and-data-handling). The model call is also billed to your account, see the next question.

#### What does a plain-English question cost?

Two charges: Dataset Analyst's $0.01 per question, plus the AI model usage, billed to your Apify account through the [`apify/openrouter`](https://apify.com/apify/openrouter) Actor. With the default model that is typically under a cent on a paid Apify plan and about 5 to 10 cents on the Free plan. SQL queries involve no model, so they cost $0.01 only. Details in [How much does it cost to query a dataset?](#how-much-does-it-cost-to-query-a-dataset)

#### Can it handle nested JSON?

Yes. Query `STRUCT` fields with dot notation (`price.current`) and expand arrays with `UNNEST`.

#### Does it change my data?

No. Only read-only `SELECT` and `WITH` queries are allowed, and results are written to new datasets, never back to the source.

#### How large a dataset can it handle?

By default it reads up to 100,000 items per query and tells you when a dataset is larger. Raise this with `maxRows` at your own risk: the dataset is loaded into memory, so a value too large for the run's memory fails the run. Then give the Actor more memory or lower `maxRows`. A large value mainly slows the first query (roughly a few seconds per 100,000 rows); after that the dataset is cached.

# Actor input Schema

## `datasetId` (type: `string`):

Optional. The Apify dataset to query. Selecting it here is recommended and works on every account: it grants this run read access to the dataset. Without queries, the Live View opens with this dataset prefilled. With queries, the batch job runs against it, so it is required when 'queries' is provided. You can leave it empty and paste a dataset ID in the Live View instead, but that only works if your account's General resource access setting allows reading by ID (new accounts default to Restricted, which doesn't).

## `queries` (type: `array`):

Batch job: a list of queries to run against the dataset, one by one. Each item is an object with a 'type' ("ask" for natural language, "sql" for raw SQL) and a 'query' string. Each result is saved to a new dataset; a summary is written to this run's default dataset. Leave empty to use the Live View instead.

## `llmModel` (type: `string`):

OpenRouter model ID for natural-language-to-SQL translation (default anthropic/claude-sonnet-5.5). Model usage is billed to your Apify account through the apify/openrouter Actor, on top of this Actor's per-question price (typically under a cent per question on a paid plan, about 5 to 10 cents on the Free plan); SQL queries use no model. A cheaper model (for example anthropic/claude-haiku-5.5) lowers that cost, but cheaper models are often less reliable at writing correct SQL. If OpenRouter no longer serves the chosen model, the Actor falls back to anthropic/claude-sonnet-4.5. See https://openrouter.ai/models for available models.

## `dataSampling` (type: `integer`):

How many rows (0–100) to look at when picking example values to send to the LLM for context on natural-language queries. For each column, the LLM gets its name, its type, and a few example values taken from the first N rows: all of the column's values if it has 20 or fewer different ones, otherwise 3 examples. Whole rows are never sent. Higher values produce better SQL but send more of your data to an external LLM. Set to 0 if your dataset contains sensitive or private data that should not leave your infrastructure.

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

The maximum number of items read from the dataset per query (default 100,000). The dataset is loaded into memory, so the default protects against running out of memory on very large datasets; results report when a dataset was truncated. You can raise this to query more rows, at your own risk: a value too large for the Actor's available memory will cause the run to fail. If that happens, increase the Actor's memory or lower this value. There is no upper limit. Note: a large value mainly slows the FIRST query against a dataset, which has to download all those items (roughly a few seconds per 100,000 rows); after that the dataset is cached in memory and follow-up queries stay fast.

## Actor input object example

```json
{
  "llmModel": "anthropic/claude-sonnet-5.5",
  "dataSampling": 100,
  "maxRows": 100000
}
```

# Actor output Schema

## `summary` (type: `string`):

One row per query from the batch run: status, the executed SQL, and a link to the dataset holding that query's results.

# 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 = {};

// Run the Actor and wait for it to finish
const run = await client.actor("nmanerikar/dataset-analyst").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 = {}

# Run the Actor and wait for it to finish
run = client.actor("nmanerikar/dataset-analyst").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 '{}' |
apify call nmanerikar/dataset-analyst --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,nmanerikar/dataset-analyst"
        }
    }
}
```

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/OkclkoVrLIAskSM6a/builds/evfNLdNJN2TRVJLgH/openapi.json
