Developer guide: 6. Querying

The query endpoint, query building blocks, funnels, retention, SQL, saved queries and endpoints.

Embed
Preview of the card
<a href="https://lucidace.com/help/developer-guide-querying"><img src="https://lucidace.com/help/_api/public/orgs/af34862a-c837-4478-8335-0505efe40459/spaces/2f4b888b-c4e6-488b-81bd-6e838fb12d2e/pages/911f4d71-8c6d-4198-ac6b-46ceb1d4a485/social-card.svg?v=3e7ae33eec8b" alt="Developer guide: 6. Querying" width="600" height="315"></a>

6. Querying

Every chart, table and metric in Lucida is a query: a JSON document with a kind. You run it with POST {p}/query, keep it as an insight (section 7), or write SQL (POST {p}/sql). Examples below assume the shell from part A plus two helpers:

P="$LUCIDA_API/v1/projects/$PROJECT_ID"                            # {p} in the tables
q() { lc -X POST "$P/query" -d "{\"query\":$1}"; }                # q '<query json>'

The project must have events first (part A, "send events"). Counts use person_id, so send a stable distinct_id.

6.1 The query endpoint

Method and path

Scope

Purpose

POST {p}/query

insight:read

Run a query. Body: {query, refresh?, name?, client_query_id?, filters_override?, variables_override?, validate_only?}

GET {p}/query/{query_id}

insight:read

Poll a running query: 200 result, 202 still running, 404 unknown or expired. Any server replica answers, not only the one that started it

DELETE {p}/query/{query_id}

insight:read

Cancel a running query (204)

POST {p}/query/forecast

insight:read

Project a trends query forward: {query, horizon?(1-90, default 7), season?, confidence?(0-1, default 0.8), refresh?}

POST {p}/query/survival

insight:read

Kaplan-Meier curve for a survival query: {query, confidence?, refresh?}

POST {p}/query/impact

insight:read

Significance for an impact query: {query, alpha?, refresh?}

POST {p}/query/personas

insight:read

Cluster a persona_features query: {query, k?(2-8, default 4), refresh?}

GET {p}/query_definitions

insight:read

Event aliases and virtual events (6.5)

GET {p}/query-log

insight:read

Recent runs: `?status=ok

GET /v1/query.schema.json

none

JSON Schema of every query kind (no auth needed)

q '{"kind":"trends","date_range":{"from":"-30d","to":"now"},"interval":"day",
    "series":[{"source":{"type":"event","name":"signed_up"},"math":"dau"}]}' | jq '{columns, rows: .rows[0:2], meta: .meta.cache_hit}'

The answer is {columns, rows, meta}. rows are arrays in columns order. meta has sql_hash, cache_hit, computed_at, execution_ms, rows_read, bytes_read, sampled, clamped_range, cache_key and next_allowed_client_refresh.

Request fields

  • refresh is one of blocking (default: cached result, else compute), async (cached, else start and answer 202 at once), force_blocking (recompute), force_async (recompute in the background, 202 at once), force_cache (cached only, 404 on a miss), lazy_async (same as async), async_except_on_cache_miss (same as blocking). The old booleans work: true is force_blocking, false is blocking.

  • name: a label for the query log, at most 128 characters.

  • client_query_id: your id for the run, 1-64 of [A-Za-z0-9_-]. You poll and cancel by it. A second call with the same id while the first is running does not fail: it attaches to the running query and answers 202 with the same query_id, never 409, whichever server replica gets the call. The claim on the id expires after 60 s, so a crashed run does not block the id for long. Without it the server makes an id.

  • validate_only: true: parse and compile only. Answer 200 {valid, kind, columns}; for kind:"sql" the columns are the real result columns (as POST {p}/sql returns them).

  • filters_override: {date_range?: {from, to}, filters?: <property group>} replaces the date range and ANDs the filters, as dashboards do. Only for kinds that have a date_range (otherwise 400).

  • variables_override: {name: value} replaces variables of a sql query (400 for any other kind).

  • offset is refused with 400. Use limit inside the query.

Async. A query still running after 5 s answers 202 {query_id, status:"running"}. Force it earlier with refresh: "async" or "force_async":

lc -X POST "$P/query" -d '{"query":{"kind":"funnel","date_range":{"from":"-30d","to":"now"},
  "steps":[{"source":{"type":"event","name":"signed_up"}},{"source":{"type":"event","name":"purchase"}}]},
  "refresh":"force_async","client_query_id":"signup-funnel-1"}'
# 202 {"query_id":"signup-funnel-1","status":"running"}
until [ "$(lc -o /dev/null -w '%{http_code}' "$P/query/signup-funnel-1")" != 202 ]; do sleep 1; done
lc "$P/query/signup-funnel-1"                      # 200 {columns, rows, meta}
lc -X DELETE "$P/query/signup-funnel-1"            # 204: cancel (works on a running query)

Jobs are kept about ten minutes, and the outcome is stored in the shared database, so a poll answers the same whichever replica receives it. Polling an unknown, cancelled or expired id is 404. The forecast, survival, impact and personas routes answer 202 the same way; repeat the call once the query has finished (the result is cached).

Limits and errors. 400 for a compile error, a bad relative date and offset. A bad relative date names the bound: errors[].field is date_range.from or date_range.to (from or to for query-string parameters such as ?from=), errors[].message is invalid relative date "-7x"; expected an RFC 3339 timestamp or a relative date like -7d, mtd, now, and detail is invalid query: date_range.from: .... 422 for an unknown field (fields the schema does not list are rejected), for a combination the compiler refuses (a funnel time_to_convert viz with a breakdown), and for a kind this endpoint does not compile (below). 429 when the project hits the query concurrency or rate limit (wait for Retry-After). An API key may read at most 10 GiB per query by default.

6.2 Query building blocks (exact values)

date_range is {from, to, explicit?}. Each bound is an RFC 3339 timestamp, a date YYYY-MM-DD (UTC midnight), or a relative value resolved on every run in the query's timezone (else the project's): now, today, yesterday, mtd, ytd, all, -Nh, -Nd, -Nw, -Nm, -Ny. A saved insight with -30d therefore moves with the calendar. GET /v1/query.schema.json documents these relative values on every date_range bound. The same forms work in tile overrides.date_range and in dashboard templates (a template made from a dashboard with relative-date tiles instantiates; verified).

interval: minute, hour, day (default), week, month, quarter, year.

source (what to count), by type:

type

Fields

event

name

events

names (array, OR-ed)

action

id (a saved action, 8)

metric

id (a saved proportion or mean metric, 8)

warehouse

table, timestamp_field, distinct_id_field?, id_field?

agent_conversation

status (started, message, ended, resolved, unresolved, escalated, abandoned, rage, positive_feedback, negative_feedback), agent?

Series (trends): {source, math?, math_property?, math_multiplier?, label?, filters?}. math is one of total (default), dau, weekly_active, monthly_active, unique_sessions, first_time_for_user, sum, avg, min, max, median, p75, p90, p95, p99, per_user_avg, per_user_min, per_user_median, per_user_p75, per_user_p90, per_user_p95, per_user_p99, per_user_max, or an object: {"unique_groups": n}, {"weekly_active_groups": n}, {"monthly_active_groups": n} (n is the group type index, 0-4), {"expression": "<LQL aggregate>"} (for example sum(toFloat64OrZero(properties.amount)); a bad type is 400 with the ClickHouse error). The property maths (sum, avg, ... and per_user_*) need math_property.

Filters (filters on the query, a series or a step): {"and":[...]} or {"or":[...]}, nestable. A leaf is {key, op, value?, type?, group_index?}. type is event (default), person, session, cohort, element, feature_flag, external, group (with group_index), expression, product_area. op is one of eq, neq, contains, icontains, ncontains, not_icontains, regex, nregex, gt, gte, lt, lte, is_set, is_not_set, is_date_before, is_date_after, between, not_between, in, not_in, starts_with, not_starts_with, ends_with, not_ends_with, semver_eq, semver_neq, semver_gt, semver_gte, semver_lt, semver_lte, semver_tilde, semver_caret, semver_wildcard.

Breakdown: a list of {key, type?, limit?(default 25), other_bucket?(default true), group_index?, histogram_bins?, clean_paths?, normalize_url?}; type takes the same values as filter type. A row with the property missing lands in the bucket $$_lc_none_$$. Output gets one bd_N column per breakdown, before value.

Compare: {"type":"prev"} (the window before date_range) or {"type":"custom","date_range":{...}}. Rows are tagged period: "current" | "previous".

Other shared options: timezone, environment, filter_bots (default true), include_internal (default false), test_account_filter, sampling (0-1).

6.3 Every query kind, with an example

GET /v1/query.schema.json lists 28 kinds. 22 run through POST {p}/query as shown below, and sql runs with a query string (6.4). Five are accepted by the schema but answer 422 unsupported: <kind> queries: cohort, replay_list, web_overview, experiment_result and heatmap_query. Use their own routes: cohorts in 8, replays (POST {p}/replays/search), web reports (GET {p}/web/*), experiment results (GET {p}/experiments/{id}/results) and heatmaps. Examples below were run against a live project.

R='"date_range":{"from":"-30d","to":"now"}'
FUNNEL='{'$R',"steps":[{"source":{"type":"event","name":"signed_up"}},{"source":{"type":"event","name":"purchase"}}]}'

trends (required: date_range, series). Extras: formula ("A / B", series lettered by position), formulas ([{expr,label?}], each an output series, takes precedence), breakdown, compare, compare_segments (up to 5 cohort ids, adds a segment column), confidence_level (90, 95 or 99, adds a ci column), hide_weekends. Rows: series, period, bucket, [bd_N...], value.

q '{"kind":"trends",'$R',"interval":"day",
  "series":[{"source":{"type":"event","name":"purchase"},"math":"sum","math_property":"amount","label":"Revenue"}],
  "breakdown":[{"key":"plan","type":"event","limit":5}],"compare":{"type":"prev"},
  "filters":{"and":[{"key":"source","type":"event","op":"neq","value":"ads"}]}}'
q '{"kind":"trends",'$R',"interval":"week","series":[
  {"source":{"type":"event","name":"purchase"},"label":"A"},{"source":{"type":"event","name":"signed_up"},"label":"B"}],
  "formulas":[{"expr":"A / B","label":"Conversion"}],"confidence_level":95}'

funnel (required: date_range, steps). steps are {source, filters?, label?}. Options: window ({amount, unit}, unit second|minute|hour|day|week|month, default 14 days), order (sequential default, strict, any), viz ({"type":"steps"} default, {"type":"trends"}, {"type":"time_to_convert","bins":n,"from_step?","to_step?"}), breakdown (not with time_to_convert: 422 unsupported: breakdown with this funnel viz), breakdown_attribution ({"type":"first_touch|last_touch|all_steps"} or {"type":"specific_step","step":n}), exclusions ([{event, after_step, until_step?}]), aggregate_by (persons, sessions or {"groups":n}), count_mode (unique, totals), hold_constant (max 3 keys), optional_steps, first_time_steps, compare_cohorts (also accepted under the name compare_segments, up to 5 cohort ids, as on trends and retention), value_property. Rows (steps viz): step_1 ... step_n counts. Trends viz: bucket, started, converted, rate.

q '{"kind":"funnel",'$R',"steps":[{"source":{"type":"event","name":"signed_up"}},
  {"source":{"type":"event","name":"added_to_cart"}},{"source":{"type":"event","name":"purchase"}}],
  "window":{"amount":14,"unit":"day"},"order":"sequential","viz":{"type":"steps"}}'
# {"columns":["step_1","step_2","step_3"],"rows":[[39,31,13]]}

retention (required: date_range, start). start and return_event are {source, filters?}; no return_event means any event. retention_type: n_day (default), return_on_or_after, rolling, bracketed (with brackets: [{from,to}]). start_type: first_time (default), recurring, first_ever. period: hour|day|week|month. periods default 7. Also min_occurrences, time_window (calendar default or rolling, as in /v1/query.schema.json), aggregate_by, value_property. Rows: cohort, period, retained, cohort_size, in_progress; an unfinished period has retained: null and in_progress: true.

q '{"kind":"retention",'$R',"start":{"source":{"type":"event","name":"signed_up"}},
  "return_event":{"source":{"type":"event","name":"purchase"}},"period":"day","periods":7,"retention_type":"n_day"}'

paths (required: date_range). mode: all (default), conversion, abandonment (both need goal), entry_pages, exit_pages. event_types: pageview (default), screen, custom, all. Also step_limit (1-20, default 5), start, end, exclude, min_edge_weight, edge_limit (1-1000), step_gap_minutes, cleaning_rules ([{regex, alias}]), collapse_repeats, strip_query, prefixes. Rows (edges): source_step, source, target_step, target, weight, avg_time_ms, loop_weight, is_loop. entry_pages rows: path, sessions, bounces, avg_duration_s.

q '{"kind":"paths",'$R',"event_types":["pageview"],"step_limit":3,"mode":"all"}'

stickiness (required: date_range, event). event is {source, filters?}. criteria: {"op":"gte|lte|eq","count":n} sets what makes an interval active. series adds up to 5 more events. Rows: active_intervals, persons. compare: {"type":"prev"} also runs the previous period and adds a trailing period column (current or previous); breakdown is not supported.

q '{"kind":"stickiness",'$R',"event":{"source":{"type":"event","name":"$pageview"}},"criteria":{"op":"gte","count":2}}'

lifecycle (required: date_range, event). Rows: bucket, status, persons; status is new, returning, resurrecting or dormant. With compare, a trailing period column (current or previous) is added.

q '{"kind":"lifecycle",'$R',"event":{"source":{"type":"event","name":"$pageview"}},"interval":"day"}'

persons (no date range): {search?, order_by:"created_at", direction:"asc|desc", limit (default 100), cursor?, filters? (person and cohort filters only)}. Rows: person_id, created_at, properties, distinct_ids, cursor. Properties your key cannot read are masked.

q '{"kind":"persons","limit":3,"search":"user_1"}'

sessions_list (required: date_range): order_by is start, duration, pageviews, events or frustration_count; plus direction, limit, cursor, filters. Rows include session_id, distinct_id, person_id, started_at, ended_at, duration_s, pageviews, events, entry_path, exit_path, channel, device_type, country, has_replay, frustration_count, is_bounce, cursor.

q '{"kind":"sessions_list",'$R',"limit":3,"order_by":"duration","direction":"desc"}'

funnel_persons: who dropped at or passed one step. {funnel, step (1-based, 1 to steps-1), converted?:false, limit?(default 100, max 10000), breakdown?:[...], performed?}. funnel is a funnel body without kind. Rows: entity, person_id, distinct_id, session_ids. Page with meta.next_cursor sent as the request cursor.

q '{"kind":"funnel_persons","funnel":'"$FUNNEL"',"step":1,"converted":false,"limit":5}'

funnel_correlation: events or properties over- and under-indexed among converters. {funnel, target:{"type":"events"} | {"type":"properties","properties":[{key,type?}]}, limit?(50), exclude?}. Rows: name, success_count, failure_count, success_total, failure_total, odds_ratio, chi_square, p_value, direction. The project exclusion list (6.7) is merged in.

q '{"kind":"funnel_correlation","funnel":'"$FUNNEL"',"target":{"type":"events"},"limit":10}'

funnel_effort: time, clicks and inputs per step. {funnel}. Rows: step, reached, avg_seconds, median_seconds, avg_clicks, avg_inputs, avg_keystrokes. Keystrokes need the browser SDK.

q '{"kind":"funnel_effort","funnel":'"$FUNNEL"'}'

insight_actors: the persons behind one chart point. {source:<a trends|stickiness|lifecycle|retention|paths query>, point, limit?(100)}. point by source kind: trends {"type":"trends","series":0,"bucket":"<bucket from the result>","breakdown?","previous?","segment?"}, stickiness {"type":"stickiness","active_intervals":n}, lifecycle {"type":"lifecycle","bucket","status"}, retention {"type":"retention","cohort","period?"}, paths {"type":"paths","step","node"}. Rows: person_id, properties, session_ids.

q '{"kind":"insight_actors","limit":5,"source":{"kind":"trends",'$R',"series":[{"source":{"type":"event","name":"signed_up"},"math":"dau"}]},
    "point":{"type":"trends","series":0,"bucket":"2026-11-05T00:00:00Z"}}'

ecommerce (required: date_range): part is overview (default), products, carts, checkout, item_lists, promotions, coupons, refunds, refund_reasons; funnel_window_days 1-90 (default 7). It reads the standard ecommerce events; with none it returns zero rows (overview columns: currency, orders, revenue, aov, customers, items).

q '{"kind":"ecommerce",'$R',"part":"overview"}'

survival (required: date_range, start, end): time from event A to event B with censoring. start and end are bare sources ({"type":"event","name":"..."}), unit is minute|hour|day (default hour), window_days 1-365 (default 30). Rows: t, events, censored.

q '{"kind":"survival",'$R',"start":{"type":"event","name":"signed_up"},"end":{"type":"event","name":"purchase"},"unit":"hour"}'

impact (required: date_range, anchor, goal): which early behaviours go with reaching a goal. anchor and goal are bare sources; behaviour_days 1-90 (7), goal_days 1-365 (30), candidates (up to 50 event names, empty tests the most common), limit 1-100, split_property, include_early_goal, include_open_windows. Rows: cand, people, converted (empty until enough people).

q '{"kind":"impact",'$R',"anchor":{"type":"event","name":"signed_up"},"goal":{"type":"event","name":"purchase"},"candidates":["added_to_cart"]}'

propensity (required: as_of, goal, features): per-person feature counts and a goal label to train or score a model. as_of plus horizon_days (default 7) must lie in the past (400 otherwise). features are 1-20 event names, lookback_days default 30, mode is train (default) or score (page with after), property_features, value_property, seed, limit (default 10000). Rows: pid, label, counts, total.

q '{"kind":"propensity","as_of":"2026-10-28T00:00:00Z","goal":{"type":"event","name":"purchase"},"features":["$pageview","added_to_cart"]}'

cohort_overlap: {cohorts:[2 to 10 cohort ids]} (400 otherwise). Rows: a, b, overlap.

composition: people split by a person property. {property, cohort?}. Rows: value, people.

q '{"kind":"composition","property":"plan"}'

persona_features (required: date_range, events): 1-12 event names, one count column each. Rows: person_id, active_days, c1..cN. Feed it to POST {p}/query/personas.

health_score (required: signals): usage-weighted score per person or account. signals: [{event, weight, target?(10)}], window_days (30), entity ("persons" or {"groups":{"index":n}}), healthy_at (70), at_risk_at (40), part (entities or bands), entity_key, fit ([{filter, weight}] ICP rules) with fit_weight. Rows: entity, score, band, last_seen, events, icp_fit; band is healthy, at_risk or critical. Saved versions: 8.

q '{"kind":"health_score","signals":[{"event":"$pageview","weight":1,"target":10},{"event":"purchase","weight":2,"target":2}],"window_days":30}'

box_plot (required: date_range, event, property): five-number summary of a numeric property per bucket. exclude_outliers?. Rows: bucket, min, p25, median, p75, max, mean, n; with compare, a trailing period column (current or previous).

q '{"kind":"box_plot",'$R',"event":{"source":{"type":"event","name":"purchase"}},"property":"amount","interval":"week"}'

weekday_hour (required: date_range, event): aggregate is events (default) or users. Rows: weekday, hour, value; with compare, a trailing period column (current or previous).

q '{"kind":"weekday_hour",'$R',"event":{"source":{"type":"event","name":"$pageview"}},"aggregate":"events"}'

6.4 SQL

POST {p}/sql runs one read-only SELECT in the LQL dialect (ClickHouse SQL, restricted). It uses the same cache, limits and async path as /query. A sql query also works inside /query, insights, dashboards, alerts and endpoints: {"kind":"sql","query":"...","date_range":{...},"filters":{...},"variables":{...}}.

Method and path

Scope

Purpose

POST {p}/sql

insight:read

Run SQL (the key's access is checked before the body: a key without access gets 404 whatever it sends)

GET {p}/sql/schema

insight:read

Tables and columns your key can read

POST {p}/sql/complete

insight:read

Editor completions: {sql, cursor} (cursor is a byte offset) returns [{label, kind, detail}]

lc -X POST "$P/sql" -d '{
  "sql":"SELECT event, count() AS n, uniq(person_id) AS people FROM events WHERE {filters} AND event = {variables.event} GROUP BY event",
  "date_range":{"from":"2026-10-01T00:00:00Z","to":"2026-11-10T00:00:00Z"},
  "variables":{"event":"purchase"}}'
# {"columns":["event","n","people"],"rows":[["purchase",18,18]],"meta":{...}}

Request fields: sql (required), variables ({name: value} for {variables.name}), date_range ({from, to?, explicit?} for {filters}; bounds may be RFC 3339, a date, or relative values such as -7d, mtd, yesterday, now, resolved in the project timezone; unless explicit, days snap to whole days), filters (a property group), interval ({filters.interval}), breakdown (an event property key, {filters.breakdown}), refresh (boolean, skip the result cache), validate_only (answer {valid, kind, columns}; columns are the real result column names, found by running the query with LIMIT 0, so validation does touch ClickHouse).

Placeholders are substituted as escaped literals before parsing, so they cannot widen what a query reads:

  • {filters}: the date range and property filters as one boolean over timestamp, properties.<key> and person.properties.<key>. {filters(day AS timestamp, plan_col AS 'plan')} rebinds the timestamp and property columns (warehouse tables, subqueries). Also {filters.date_from}, {filters.date_to}, {filters.interval}, {filters.breakdown}.

  • {variables.name}: a typed literal. Strings are quoted, numbers and booleans plain, null is NULL, an array works with IN, an object is 400.

  • filters or a date_range set without a {filters} placeholder in the SQL is 400 (it would be silently ignored otherwise); add the placeholder or drop the field.

Tables (from GET {p}/sql/schema on a live project):

Table

Columns

events

uuid, event, distinct_id, person_id, session_id, timestamp, environment, properties (JSON text), person_properties, source, elements_chain, is_internal, plus hot columns $current_url, $pathname, $host, $referrer, $referring_domain, $channel, $utm_source, $utm_medium, $utm_campaign, $browser, $os, $device_type, $country, $region, $city, $group_0..$group_4

persons

person_id, properties, created_at, last_seen_at, platform

sessions

session_id, distinct_id, person_id, session_start, session_end, pageviews, events, frustration_count, entry_url, exit_url, channel, utm_source, utm_medium, utm_campaign, device_type, country, has_replay, duration_s

groups

group_type_index, group_key, properties, created_at

replays

session_id, distinct_id, person_id, session_start, session_end, active_ms, click_count, keypress_count, size_bytes, first_url, urls

warehouse_rows

table_name, row_key, data, properties, source, synced_at

cohort_members

cohort_id, person_id

activity_log

id, actor_user_id, actor_kind, action, resource_type, resource_id, detail, created_at

sql_view_rows

view_id, version, data (use your view's own name instead, 6.5)

query_log, information_schema_metrics, information_schema_tables, information_schema_relationships, information_schema_data_quality_checks

catalog tables; query_log columns: id, kind, name, status, duration_ms, row_count, error, user_id, api_key_id, created_at

Read a property with properties.plan or person.properties.plan. Your SQL views, synced warehouse tables (synced_<table>) and live warehouse views (wh_<name>) also appear as tables. Tables synced from a warehouse source are read as warehouse.<source>.<table> (SELECT count() FROM warehouse.pg_main.orders): same project scope and the same masking and hidden-table rules as the other warehouse tables.

Rules and limits. Only a plain SELECT (CTEs, joins, subqueries and window functions are fine). Refused with 400: other statements, SETTINGS/FORMAT, INTO, recursive CTEs, table functions, and functions off the allow-list (sleep is refused). A compile error is 400 problem+json with message, line, column, end_line, end_column; an unknown table lists the available ones (the base tables, revenue_events, query_log, the information_schema_* tables and your SQL views). With no LIMIT, 100 rows come back (meta.limit, meta.truncated); LIMIT may be at most 50,000. A read of events with no condition on timestamp gets AND timestamp >= now() - INTERVAL 90 DAY and meta.injected_bounds says so: always state your window. meta also has tables, warnings, and generated_sql only when the body sets "explain": true. persons.properties comes back without the server-owned $lc_* keys (the same as /query). Restricted properties and hidden warehouse tables are masked for keys that may not read them.

6.5 SQL views, data views, query definitions, endpoints

SQL views save a query as a table. A materialized view stores a snapshot and can refresh on a schedule.

Method and path

Scope

Purpose

GET/POST {p}/sql-views

insight:read / insight:write

List; create {name, query, description?, materialized?, refresh_minutes?}

GET/PATCH/DELETE {p}/sql-views/{id}

read / write

PATCH takes query, description, materialized, refresh_minutes (null = off), incremental_column, incremental_lookback_minutes (0-10080), suspend_after (1-100), block_on_failed_checks

POST {p}/sql-views/{id}/refresh

insight:write

Refresh now

POST {p}/sql-views/{id}/resume

insight:write

Resume a suspended schedule

GET {p}/sql-views/{id}/data

insight:read

The stored snapshot {columns, rows, refreshed_at} (404 until the first refresh)

GET {p}/sql-views/{id}/runs

insight:read

Refresh history (status, rows_written, failed_checks, error)

GET {p}/sql-views/lineage

insight:read

Dependency graph; ?view=<name> narrows to one view

VIEW=$(lc -X POST "$P/sql-views" -d '{"name":"daily_purchases","materialized":true,"refresh_minutes":60,
  "description":"orders per day",
  "query":"SELECT toDate(timestamp) AS day, count() AS orders FROM events WHERE event = '"'"'purchase'"'"' GROUP BY day"}' | jq -r .id)
lc -X POST "$P/sql-views/$VIEW/refresh" | jq '{refreshed_at, stored_rows}'
lc -X POST "$P/sql" -d '{"sql":"SELECT * FROM daily_purchases ORDER BY day LIMIT 3"}' | jq .rows

name: lowercase letters, digits and underscores, starting with a letter; it becomes the table name. refresh_minutes 5-10080, materialized only. 400 for a bad name, schedule, query or a cycle between views; 409 for a name that exists. A view's snapshot is kept when a data-quality check fails (block_on_failed_checks, default true). After suspend_after failed refreshes in a row (default 3) the schedule suspends; fix the query and call resume.

Data views limit which events and properties a team sees, rename properties and fix defaults. Admin to write.

Method and path

Scope

Purpose

GET {p}/data-views, GET {p}/data-views/{view_id}

insight:read

List, read

GET {p}/data-views/active

insight:read

The views that apply to the caller

POST {p}/data-views

admin

Create

PATCH/DELETE {p}/data-views/{view_id}

admin

Update, delete

lc -X POST "$P/data-views" -d '{"name":"Checkout","events":["signed_up","added_to_cart","purchase"],"properties":["plan","amount"],
  "labels":{"amount":"Order amount"},"formats":{"amount":"number"},
  "attribution":{"funnel_breakdown":"first_touch","lookback_days":30},
  "persistence":{"allocation":"most_recent","expiration":"days:30"},"team_ids":[],"enforced":false,"is_default":false}'

Rules: name 1-128 characters; events (at most 2000) and properties (at most 5000) are include-lists where prefix* matches by prefix and empty means everything; formats values are number, percent, duration, date, bytes; funnel_breakdown is first_touch, last_touch or all_steps; allocation is most_recent or original; expiration is session, person or days:<1-365>; at most 100 team_ids; an enforced view needs at least one team. See Data views.

Query definitions rewrite names at query time (history included; stored events never change).

lc -X POST "$P/query_definitions" -d '{"name":"signup","kind":"alias","source":"signed_up"}'
lc -X POST "$P/query_definitions" -d '{"name":"cart_click","kind":"virtual","steps":[{"selector":"button.add-to-cart"},{"event":"added_to_cart"}]}'

kind: alias (event name to stored event name, needs source, no steps), property_alias (property key to stored key, needs source), virtual (1-20 alternatives in steps, OR-ed, each an action step like {event, selector, tag_name, text, text_match, href, href_match, url, url_match, screen_name, properties}; no source). name 1-200 characters, and an alias cannot point at itself (400); a taken name is 409. GET lists, PATCH {p}/query_definitions/{id} takes description, source, steps, DELETE removes.

Endpoints serve a saved query as an API with versions, variables, caching and usage.

Method and path

Scope

Purpose

GET/POST {p}/endpoints

insight:read / insight:write

List; create

GET/PATCH/DELETE {p}/endpoints/{slug}

read / write

PATCH takes name (required), description, refresh_every_minutes

POST {p}/endpoints/{slug}/run

a scope-less secret key may run endpoints (it reads like a viewer); a key with explicit scopes needs endpoint:read, query:read, a broad read (*:read) or admin, else 403 naming the scopes. A capture-only key gets 403 here; an inaccessible project stays 404

Run: {variables?, limit?(1-50000), offset?, refresh?, version?, debug?}

GET {p}/endpoints/{slug}/result

insight:read

The stored result (?version=&refresh=)

PUT {p}/endpoints/{slug}/active

insight:write

{active}: an inactive endpoint answers 404 on run

PUT {p}/endpoints/{slug}/materialization

insight:write

{enabled}

GET/POST {p}/endpoints/{slug}/versions

read / write

Versions; POST {query, note?, variables?} makes the new current one

PATCH {p}/endpoints/{slug}/versions/{version}

insight:write

{disabled?, note?} (a disabled version answers 404; the current one cannot be disabled)

POST {p}/endpoints/{slug}/pin

insight:write

{version}: roll back or forward

GET {p}/endpoints/{slug}/openapi.json

insight:read

OpenAPI document of this endpoint

GET {p}/endpoints/{slug}/logs

insight:read

Run log: `?level=info

GET {p}/endpoints/{slug}/history

insight:read

Change history (newest 200)

GET {p}/endpoint-usage

insight:read

Usage per day: `?from=&to=&endpoint=&mode=cache

lc -X POST "$P/endpoints" -d '{"slug":"event-count","name":"Event count","note":"v1",
  "query":{"kind":"sql","query":"SELECT event, count() AS n FROM events WHERE {filters} AND event = {variables.event} GROUP BY event"},
  "variables":[{"name":"event","type":"string","default":"purchase","required":false,"description":"event name"}],
  "refresh_every_minutes":60}'
lc -X POST "$P/endpoints/event-count/run" -d '{"variables":{"event":"signed_up"},"limit":10}'
# {"execution_id":"...","endpoint":"event-count","version":1,"mode":"direct","cache_hit":false,"columns":["event","n"],"results":[["signed_up",40]],"has_more":false,"computed_at":"..."}

slug: lowercase letters, digits and dashes, 1-63 characters, 409 when taken. query is any query IR (it becomes version 1). Variable type is string, number, boolean, date, uuid or string_list; date_from/date_to and breakdown keys are built in. refresh_every_minutes 5-10080 or omitted for on-demand. run refresh: cache (default), force (recompute and update the cache), direct (skip materialized rows and the cache). Run errors: 400 with a code such as required_variable_missing, 404 unknown, inactive or disabled version, 429/503 with Retry-After, 504. Materialization works only for <expr> = {variables.x} conditions combined with AND, with no {filters} or date variables (otherwise 400 cannot materialize: ...). See Analytics limits.

6.6 Query log

GET {p}/query-log?status=error&limit=20 returns {data:[{id, kind, name, status, duration_ms, row_count, error, user_id, api_key_id, created_at}], next_cursor}, newest first. status is ok, cached or error. Set name on queries to find them here. The same rows are the query_log SQL table.

6.7 Correlation exclusions

Event and property names to leave out of funnel_correlation (noise like $pageview). The list is merged into every correlation query.

lc -X PUT "$P/correlation_exclusions" -d '{"events":["$pageview"],"properties":["$browser"]}'   # replaces the lists
lc "$P/correlation_exclusions"                                                                   # {events, properties}

PUT needs insight:write, GET needs insight:read.

Updated