---
title: "Execute a structured query — schema-free, zero domain assumptions"
method: POST
path: "/v1/query"
tags: ["Semantic Query"]
---

# Execute a structured query — schema-free, zero domain assumptions

`POST /v1/query`

## Request

- Base URL: `https://api.algenta.ai`
- URL: `https://api.algenta.ai/v1/query`
- Auth: one of:
  - HTTP bearer
  - API key in header `X-API-Key`

**Structured query execution engine.**

This endpoint takes structured intent — produced by an LLM from the user's natural-language question. It does NOT accept raw text.

**Separation of concerns:**
- LLM: language → structured intent, ambiguity resolution, user interaction
- Algenta: schema understanding, math relationships, fast execution, correctness

**Role resolution:**
1. Detect derived formulas across all numeric column triples (Mojo, ~100ms)
2. Assign structural roles: derived_measure, base_measure, unit_measure…
3. Match requested role → best column
4. Execute aggregation, return result + all candidates for LLM disambiguation

**Ambiguity handling:**
If confidence < 0.7, check `candidates` — multiple columns may match the role. The LLM can present options to the user or pick the most contextually appropriate one.

## Request body

- QueryRequest: Structured query execution request. ═══════════════════════════════════════════════════════════ PRIMARY PATH — Exact spec (use after reading the schema) ═══════════════════════════════════════════════════════════ The correct flow: 1. Call POST /v1/sources/register or POST /v1/sources/schema 2. LLM reads the returned schema (column names, roles, formulas) 3. LLM sends exact column names — Mojo validates and executes Example (top 5 customers by revenue): { "source_name": "S0", "metric_column": "measure_total", "group_column": "dimension_label", "aggregation": "sum", "limit": 5 } For multi-hop joins: { "source_name": "S0", "metric_column": "measure_total", "group_column": "dimension_label", "join_path": { "base_source": "S0", "group_source": "S2", "edges": [ { "left_source": "S0", "right_source": "S1", "left_key": "k01_left", "right_key": "k01_right" }, { "left_source": "S1", "right_source": "S2", "left_key": "k12_left", "right_key": "k12_right" } ] }, "aggregation": "sum" } ═══════════════════════════════════════════════════════════ FALLBACK PATH — Hint spec (when schema is not yet known) ═══════════════════════════════════════════════════════════ The engine resolves source and columns from structural role hints. Use this ONLY for exploratory queries. Always migrate to exact spec once you have the schema — it is faster and never ambiguous. Example: { "metric": {"role": "derived_measure", "hint": "total value"}, "group_by": ["segment"], "aggregation": "sum", "limit": 5 }
  - `dataset_id` string, nullable: Public dataset ID alias for a registered source. When provided, query execution is scoped to that one registered dataset.
  - `source_name` string, nullable: EXACT source name from the registry (e.g. 'Bookings'). Bypasses source resolver entirely. Get this from POST /v1/sources/schema or the registration response.
  - `metric_column` string, nullable: EXACT column name for the metric (e.g. 'EXT_PRICE'). Bypasses column resolver. The engine validates this column exists in source_name.
  - `group_column` string, nullable: EXACT column name for group-by (e.g. 'CUSTOMER'). Bypasses group resolver. Can be in source_name or in the terminal source of join_path.
  - `join_path` JoinPathSpec: Explicit multi-hop join contract replacing single-hop join fields.
    - `base_source` string, required: Source that owns the metric column and anchors the path.
    - `group_source` string, nullable: Final source expected to provide the group column, if different from base_source.
    - `edges` JoinEdgeSpec[]: Ordered join edges from base_source toward the dimension source.
      - `left_source` string, required: Source on the left side of the join edge.
      - `right_source` string, required: Source on the right side of the join edge.
      - `left_key` string, required: Exact join key column in left_source.
      - `right_key` string, required: Exact join key column in right_source.
      - `join_type` string: Join type. Initial implementation supports inner.
      - `min_confidence` number: Minimum acceptable confidence for this hop.
      - `expected_cardinality` string, nullable: Optional expected cardinality such as one_to_many, many_to_one, or many_to_many.
      - `allow_many_to_many` boolean: If false, planner/executor must reject many_to_many fanout on this hop.
    - `max_hops` integer: Maximum allowed join hops for this request. Defaults to 4; explicit opt-in can raise this to 6 hops (7 tables).
    - `min_path_confidence` number: Minimum acceptable composed confidence across the full join path.
    - `reject_on_ambiguity` boolean: Reject if more than one viable path exists with insufficient score separation.
    - `reject_on_fanout` boolean: Reject if estimated path fanout exceeds safe execution thresholds.
  - `sources` DataSource[]: Raw data sources (inline CSV/JSON). Usually empty — use registry.
    - `name` string, required: Label for this source (e.g., 'sales', 'orders')
    - `dataset_id` string, nullable: Public dataset ID alias for a registered source.
    - `source_id` string, nullable: Registered source ID; fastest path and avoids re-uploading data.
    - `records` object[], nullable: Inline JSON records
    - `csv` string, nullable: Raw CSV text
    - `json_str` string, nullable: Raw JSON array/object text (nested auto-flattened)
    - `url` string, nullable: HTTP URL — format auto-detected
    - `excel_b64` string, nullable: Excel .xlsx file, base64-encoded
    - `parquet_b64` string, nullable: Parquet file, base64-encoded
    - `connection` object, nullable: Connector config dict — see DataSource docstring for all types
    - `table` string, nullable: Legacy field — use connection instead
  - `metric` MetricSpec: Structural role target. The LLM selects based on what the user wants. Use 'derived_measure' for revenue, spend, total value — the computed aggregate. Use 'base_measure' for counts, quantities, discrete amounts. Use 'unit_measure' for prices, rates, per-unit values. Use 'ratio' for percentages, margins, fill rates. Use 'metric' to let the engine pick the best numeric column.
    - `role` string: Structural role. One of: base_measure, category, component, derived_measure, identifier, metric, ratio, text, time, unit_measure. derived_measure = computed aggregate (revenue, total value). base_measure = count/quantity. unit_measure = price/rate. ratio = percentage/margin. metric = best numeric column.
    - `hint` string, nullable: Optional weak signal — a word from the user's question. Used only as a tiebreaker when multiple columns share the same role. Never the primary signal. Examples: 'revenue', 'quantity', 'price'.
  - `group_by` string[]: Hint mode only: dimension words from the user's question (e.g. ['customer', 'region']). Ignored when group_column is set.
  - `preferred_source` string, nullable: Hint mode only: source name the LLM believes is correct. Hard-locks the source resolver. Ignored when source_name is set.
  - `reject_on_ambiguity` boolean: Hint mode only: when True and resolver confidence < 0.40, return null result with source candidates instead of guessing.
  - `min_source_confidence` number: Hint mode only: minimum resolver confidence threshold.
  - `aggregation` string: sum | avg | count | max | min
  - `filter` FilterSpec: Time or value filter.
    - `time_filter` string, nullable: Relative time window. One of: last_quarter, this_quarter, last_month, this_month, last_year, this_year.
    - `conditions` FilterConditionSpec[]: Optional deterministic non-time predicates applied on the metric source. These are record predicates over normalized rows, not SQL clauses. Use exact column when schema is known, or dimension_hint for categorical dimensions when only the semantic label is known, including Redis and other non-SQL sources after normalization. Supported ops: eq, in, gt, gte, lt, lte, is_null, is_not_null.
      - `column` string, nullable: Exact source column name for this filter when schema is known.
      - `dimension_hint` string, nullable: Weak semantic label for the filter dimension when the exact column name is not known yet. Best for status/type/category style filters.
      - `op` 'eq' | 'in' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_null' | 'is_not_null': Deterministic filter operator.
      - `value` unknown
      - `values` unknown[], nullable: List comparison values for in.
        - unknown
  - `limit` integer, nullable: Top-N limit
  - `order` string: desc | asc
  - `min_confidence` number
  - `constraints` ConstraintSpec
    - `requires_derived` boolean: Reject if metric column is not a derived_measure (formula-proven).
    - `no_cross_source` boolean: Reject if query requires a cross-source join.
    - `min_column_confidence` number: Reject if column_confidence component < this value.
    - `max_join_hops` integer: Safe default join-path budget for planner-generated cross-source queries. Defaults to 4 hops; explicit opt-in can raise this to 6 hops (7 tables).
  - `resolved_plan` ResolvedPlanInput
    - `source_name` string, required
    - `metric_column` string, required
    - `aggregation` string: sum | avg | count | max | min
    - `group_column` string, nullable
    - `join_path` JoinPathSpec: Explicit multi-hop join contract replacing single-hop join fields.
      - `base_source` string, required: Source that owns the metric column and anchors the path.
      - `group_source` string, nullable: Final source expected to provide the group column, if different from base_source.
      - `edges` JoinEdgeSpec[]: Ordered join edges from base_source toward the dimension source.
        - `left_source` string, required: Source on the left side of the join edge.
        - `right_source` string, required: Source on the right side of the join edge.
        - `left_key` string, required: Exact join key column in left_source.
        - `right_key` string, required: Exact join key column in right_source.
        - `join_type` string: Join type. Initial implementation supports inner.
        - `min_confidence` number: Minimum acceptable confidence for this hop.
        - `expected_cardinality` string, nullable: Optional expected cardinality such as one_to_many, many_to_one, or many_to_many.
        - `allow_many_to_many` boolean: If false, planner/executor must reject many_to_many fanout on this hop.
      - `max_hops` integer: Maximum allowed join hops for this request. Defaults to 4; explicit opt-in can raise this to 6 hops (7 tables).
      - `min_path_confidence` number: Minimum acceptable composed confidence across the full join path.
      - `reject_on_ambiguity` boolean: Reject if more than one viable path exists with insufficient score separation.
      - `reject_on_fanout` boolean: Reject if estimated path fanout exceeds safe execution thresholds.
    - `filter` FilterSpec: Time or value filter.
      - `time_filter` string, nullable: Relative time window. One of: last_quarter, this_quarter, last_month, this_month, last_year, this_year.
      - `conditions` FilterConditionSpec[]: Optional deterministic non-time predicates applied on the metric source. These are record predicates over normalized rows, not SQL clauses. Use exact column when schema is known, or dimension_hint for categorical dimensions when only the semantic label is known, including Redis and other non-SQL sources after normalization. Supported ops: eq, in, gt, gte, lt, lte, is_null, is_not_null.
        - `column` string, nullable: Exact source column name for this filter when schema is known.
        - `dimension_hint` string, nullable: Weak semantic label for the filter dimension when the exact column name is not known yet. Best for status/type/category style filters.
        - `op` 'eq' | 'in' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_null' | 'is_not_null': Deterministic filter operator.
        - `value` unknown
        - `values` unknown[], nullable: List comparison values for in.
          - unknown
    - `limit` integer, nullable
    - `order` string: desc | asc
    - `constraints` ConstraintSpec
      - `requires_derived` boolean: Reject if metric column is not a derived_measure (formula-proven).
      - `no_cross_source` boolean: Reject if query requires a cross-source join.
      - `min_column_confidence` number: Reject if column_confidence component < this value.
      - `max_join_hops` integer: Safe default join-path budget for planner-generated cross-source queries. Defaults to 4 hops; explicit opt-in can raise this to 6 hops (7 tables).
    - `schema_revision` string, required

## Response `200`

Successful Response

- QueryResponse
  - `query_id` string, required
  - `result` unknown, required
  - `result_type` string, required
  - `confidence` number, required
  - `plan` string[], required
  - `resolved_column` string, required
  - `resolved_role` string, required
  - `resolved_source` string, required
  - `row_count` integer, required
  - `candidates` CandidateColumn[], required
    - `source` string, required
    - `column` string, required
    - `role` string, required
    - `magnitude` string, required
    - `formula` string, nullable, required
    - `confidence` number, required
    - `score_components` object
    - `notes` string[]
  - `source_scores` object, required
  - `ambiguous` boolean, required
  - `exact_spec` boolean, required
  - `explanation` string[]
  - `latency_ms` number, required
  - `decision_path` string, required
  - `plan_hash` string, required
  - `schema_revision` string, nullable
  - `validated` boolean, required
  - `deterministic_scope` string, required
  - `confidence_source` string, required
  - `clarification_required` boolean
  - `rejection_reason` string, nullable
  - `request_id` string, nullable
  - `source_set` string[]
  - `join_path` object[]
  - `planner_mode` string

## Other responses

- `422`: Validation Error

---

[API](https://skmtc.dev/codna/apis/algenta-api.md) · [All operations](https://skmtc.dev/codna/apis/algenta-api/llms.txt) · [OpenAPI document](https://skmtc.dev/codna/apis/algenta-api/revisions/35d30f84a5df?raw)
