> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kiwifs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# DQL

> Query frontmatter, kiwi-data records, and claims across your knowledge base with a Dataview-style language.

DQL (Dataview Query Language) treats your frontmatter as a table. You ask for pages by folder, tag, or field value and get rows back. It is modeled on Obsidian Dataview but runs on the server against the SQLite index, so agents, scripts, and the web UI all get the same answer.

```sql theme={null}
TABLE title, status, priority
FROM "projects/"
WHERE status = "active" AND priority >= 2
SORT priority DESC
LIMIT 20
```

> [!NOTE]
>
> DQL needs the default `sqlite` search engine. With `--search grep`, query endpoints return `501`.

## Run a query

> [tab] CLI
>
> ```bash Terminal theme={null}
> kiwifs query 'TABLE title, status FROM "concepts/" WHERE status = "draft"'
> kiwifs query 'LIST FROM #security' --format json
> ```
>
> Flags: `--format` (`table`, `list`, `json`, `count`), `--limit`, `--sort`, `--order`, `--root`.

> [tab] REST
>
> ```bash Terminal theme={null}
> curl -G 'http://localhost:3333/api/kiwi/query' \
>   --data-urlencode 'q=TABLE title, status FROM "concepts/" WHERE status = "draft"'
> ```
>
> Returns `columns`, `rows`, `total`, and `has_more` as JSON. Add `format=table`, `list`, `count`, or `distinct` for rendered text, and `limit` or `offset` to page.

> [tab] MCP
>
> Call `kiwi_query` with `query`, and optionally `format` (`table`, `list`, `json`) and `limit`.

> [tab] In a page
>
> Embed a live table in any page with a `kiwi-query` fence:
>
> ````markdown theme={null}
> ```kiwi-query
> TABLE title, status FROM "concepts/" SORT _updated DESC
> ```
> ````

## Query types

The first word picks the shape of the result.

| Type | Returns |
| - | - |
| `TABLE f1, f2 AS alias, ...` | One row per page with the listed columns |
| `LIST [field]` | Page paths, optionally with one value each |
| `COUNT` | The number of matching pages |
| `DISTINCT field` | Each unique value of one field |
| `CALENDAR date_field` | Pages keyed by a date field, for calendar views |
| `TASK` | Markdown task items (`- [ ]`) from matching pages, with `text`, `completed`, `line`, `tags`, and `due` |
| `JSON f1, f2, ...` | Like `TABLE`, shaped for programmatic use |

Add `WITHOUT ID` after `TABLE` or `LIST` to drop the page path column.

## Clauses

Clauses can appear in any order after the type. `WHERE` and `SORT` can repeat; repeated `WHERE` clauses are joined with `AND`.

| Clause | Description |
| - | - |
| `FROM "folder/"` | Only pages under a folder |
| `FROM #tag` | Only pages with a tag. Combine with `AND`, `OR`, and `-#tag` to exclude. |
| `FROM RECORDS "kind" [IN "folder/"]` | One row per `kiwi-data` record instead of per page. See [Records](#records-and-claims). |
| `FROM CLAIMS ["evidence"] [IN "folder/"]` | One row per claim directive. See [Records](#records-and-claims). |
| `WHERE expr` | Filter rows |
| `SORT field [ASC\|DESC]` | Order rows. Repeat for tie-breakers. |
| `GROUP BY field` | Group rows by a field value |
| `FLATTEN field` | Expand an array field into one row per element |
| `LIMIT n` | Cap rows. Default `50`, maximum `200`. |
| `OFFSET n` | Skip rows, for paging |

```sql theme={null}
LIST FROM #runbook AND -#deprecated SORT _updated DESC
```

## Fields

A bare name reads a frontmatter key: `status` reads `status:`. Use dots for nested keys (`owner.team`) and backticks for names with spaces or other characters (`` `due date` ``). Hyphens are allowed in bare names, so `source-of-truth` and `missing-rate` work as written.

### Implicit fields

Every page has these, with or without frontmatter:

| Field | Value |
| - | - |
| `_path` | Path from the knowledge base root, such as `concepts/auth.md` |
| `_name` | File name, such as `auth.md` |
| `_folder` | Containing folder, such as `concepts/` |
| `_ext` | Extension, such as `.md` |
| `_updated` | Last-modified timestamp |

### Computed fields

At index time, KiwiFS adds these keys to each page's indexed frontmatter. They are queryable like any other field and never written to your files.

| Field | Value |
| - | - |
| `_word_count` | Words in the body |
| `_link_count` | Outbound wiki links |
| `_heading_count` | Headings |
| `_backlink_count` | Pages that link here |
| `_has_frontmatter` | Whether the page has frontmatter |
| `_quality_score` | A page health score from `0` to `1` |
| `_blocked` | `true` when a page in `blocked-by` is not `done` or `cancelled` |

```sql theme={null}
TABLE _word_count, _backlink_count FROM "concepts/" WHERE _backlink_count = 0 SORT _word_count DESC
```

## Expressions

`WHERE` clauses and `TABLE` columns accept expressions.

| Kind | Syntax |
| - | - |
| Comparison | `=` or `==`, `!=` or `<>`, `<`, `>`, `<=`, `>=` |
| Boolean | `AND` or `&&`, `OR` or `\|\|`, `NOT`, parentheses |
| Pattern | `LIKE "auth%"`, `NOT LIKE` |
| Set | `IN ("a", "b")`, `NOT IN (...)` |
| Range | `BETWEEN 1 AND 5`, `NOT BETWEEN` |
| Null | `IS NULL`, `IS NOT NULL` |
| Literals | `"text"` or `'text'`, numbers, `true`, `false`, `null` |

Keywords are case-insensitive. DQL has no arithmetic operators; use [custom computed fields](#custom-computed-fields) when you need a derived number.

```sql theme={null}
TABLE title, owner FROM "incidents/"
WHERE severity IN ("sev1", "sev2") AND resolved IS NULL AND opened >= days_ago(30)
```

## Functions

Function names are case-insensitive.

> [accordion] Text
>
> | Function | Result |
> | - | - |
> | `lower(s)`, `upper(s)` | Case conversion |
> | `length(field)` | Array length, or string length for scalars |
> | `substring(s, start[, len])` | Part of a string (1-based) |
> | `replace(s, from, to)` | Literal replace |
> | `startswith(s, prefix)`, `endswith(s, suffix)` | Prefix and suffix tests |
> | `matches(s, pattern)` | SQL `LIKE` pattern test with `%` and `_` wildcards |
> | `regextest(pattern, s)` | Regular expression test |
> | `regexreplace(s, pattern, replacement)` | Regular expression replace |

> [accordion] Dates
>
> | Function | Result |
> | - | - |
> | `now()` | The current UTC time |
> | `date(s)` | Normalize to `YYYY-MM-DD` |
> | `striptime(s)` | Drop the time part |
> | `days_ago(n)` | The timestamp `n` days before now |
> | `days_since(d)` | Days between `d` and now |
> | `dateformat(d, format)` | Format with `strftime` codes such as `%Y-%m` |

> [accordion] Values and logic
>
> | Function | Result |
> | - | - |
> | `contains(field, value)` | `true` when an array field contains `value` |
> | `default(v, fallback)` | `fallback` when `v` is null |
> | `nonnull(v)` | `true` when `v` is not null |
> | `choice(cond, a, b)` | `a` if `cond` is true, else `b` |
> | `number(v)`, `string(v)` | Type conversion |
> | `typeof(v)` | The value's type |
> | `round(n[, digits])` | Rounding |

> [accordion] Aggregates
>
> `sum(f)`, `average(f)`, `min(f)`, `max(f)`, and `join(f, separator)` combine values across rows.

> [accordion] Linked pages
>
> `rollup(link_field, expr)` evaluates `expr` on every page the row links to and returns the results as an array.
>
> ```sql theme={null}
> TABLE title, rollup(related-notes, title) AS notes FROM "datasets/"
> ```
>
> The first argument names a typed link field listed in `[links] typed_fields`. Use `links` or `outlinks` to follow every outbound wiki link instead. Traversal is one hop, and a page with no matching links gets an empty array.

## Records and claims

Frontmatter holds one set of values per page. When a page holds a table of values, put it in a `kiwi-data` block and query each record as its own row.

````markdown datasets/housing.md theme={null}
```kiwi-data
kind: dataset-schema
records:
  - name: price
    dtype: float
    missing-rate: 0.116
  - name: id
    dtype: int
    missing-rate: 0
```
````

```sql theme={null}
TABLE dataset, name, dtype, missing-rate
FROM RECORDS "dataset-schema" IN "datasets/"
WHERE missing-rate > 0.1
SORT missing-rate DESC
```

Field names resolve against the record first, then fall back to the page's frontmatter. Force one side with `record.field` or `page.field`. Record rows add `_kind`, `_block` (which block on the page), and `_record` (position in the block).

`FROM CLAIMS` works the same way over `:::claim` directives, one row per claim, with fields such as `text`, `evidence`, `confidence`, and `source`. The evidence class is optional:

```sql theme={null}
TABLE text, confidence FROM CLAIMS "inferred" WHERE confidence < 0.7
TABLE text FROM CLAIMS WHERE source IS NULL
```

See [Widgets](https://docs.kiwifs.com/concepts/widgets.md) for the `kiwi-data` and `:::claim` syntax.

## Aggregation

Group pages by a field and compute summaries without writing a query.

```bash CLI theme={null}
kiwifs aggregate --group status --calc count,avg:priority --path projects/
```

```bash REST theme={null}
curl 'http://localhost:3333/api/kiwi/query/aggregate?group_by=status&calc=count,avg:priority&path_prefix=projects/'
```

Calculations are `count`, `avg:field`, `sum:field`, `min:field`, and `max:field`. Narrow the input with a DQL `where` filter. Over MCP, call `kiwi_aggregate`.

## Computed views

A computed view is a markdown file whose body is generated from a query. Set `kiwi-view: true` and `kiwi-query` in its frontmatter:

```markdown reports/drafts.md theme={null}
---
title: Open drafts
kiwi-view: true
kiwi-query: 'TABLE title, owner FROM "concepts/" WHERE status = "draft" SORT _updated DESC'
kiwi-format: table
---

Notes above the generated block are kept.
```

KiwiFS renders the results between `<!-- kiwi:auto -->` and `<!-- /kiwi-view -->` markers and leaves the rest of the body alone. The file is rewritten only when the output changes. `kiwi-format` accepts `table` (default), `list`, `count`, `distinct`, `json`, and `task`.

Views regenerate when you read them through the API, and on demand:

```bash Terminal theme={null}
kiwifs view create --name drafts --query 'TABLE title FROM "concepts/" WHERE status = "draft"'
kiwifs view refresh reports/drafts.md
kiwifs view list
```

Over REST, use `POST /api/kiwi/view/refresh` with `{"path": "reports/drafts.md"}`. Over MCP, call `kiwi_view_refresh`.

## Custom computed fields

Define your own derived fields in config. They are evaluated at index time from frontmatter, stored in the index alongside it, and queryable in DQL.

```toml .kiwi/config.toml theme={null}
[dataview.custom_fields]
age_days = "days_since(updated)"
priority_score = "priority * 10 + len(tags)"
is_long = "_word_count > 2000"
```

Expressions support `+`, `-`, `*`, `/`, comparisons, `&&`, `||`, and the functions `len`, `days_since`, `min`, `max`, and `abs`. Run `kiwifs reindex` after you change them. Your source files are never modified.

## Related

> [card] [Metadata API](https://docs.kiwifs.com/api/metadata.md)
>
> Query, aggregate, and view refresh endpoints.

> [card] [Bases views](https://docs.kiwifs.com/concepts/bases-views.md)
>
> Saved table and board views built on queries.

> [card] [Search](https://docs.kiwifs.com/concepts/search.md)
>
> Find pages by text instead of fields.

> [card] [Schemas](https://docs.kiwifs.com/concepts/schemas.md)
>
> Keep the frontmatter you query consistent.


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