Skip to main content

Nanopublication query template

Query templates in the grlc style: placeholders, parameters, result columns, testing and the rules for writing them.

Based on grlc syntax​

Nanopublication SPARQL templates use an extended version of the grlc syntax.

Nanopublication · Open in Nanodash

The query endpoint​

Every query template names the repository it runs against, as the object of <https://w3id.org/kpxl/grlc/endpoint> in its assertion. The usual choice is the full repository, which holds every loaded nanopublication:

<https://w3id.org/np/l/nanopub-query-1.1/repo/full>

Other repositories are narrower and therefore faster: meta for nanopublication metadata, text for full-text search, last30d for recent nanopublications, and a per-type repository type/<hash> or per-key repository pubkey/<hash>. Two further repositories, spaces and trust, hold the server-side computed state of space membership and of the agent-to-key trust network; a query can reach them from another repository with a federated service clause.

Always write the endpoint with the generic w3id.org/np/l/nanopub-query-1.1/ prefix rather than the host name of one instance. The prefix is rewritten to whichever instance answers the query, so a template naming a single host stops working as soon as that host does.

Nanopublication · Open in Nanodash

Placeholder structure​

Nanopublication query templates use variable names starting with "_" to denote placeholders, following grlc syntax. Those that end in "_iri" like "?_resource_iri" are IRI placeholder; otherwise they are literal placeholders, like "?_name".

The name of the API parameter is the variable name with the prefix and the type suffix removed: ?_resource_iri is filled by a parameter called resource, and ?_name by one called name. The underscores and the "_iri" never appear in the request.

Nanopublication · Open in Nanodash

Optional placeholders​

Optional placeholders in nanopublication query templates also follow grlc syntax. Such optional placeholders, which don't necessarily need to be filled before running the query, start with two underscores instead of just one, e.g. "?__filter_iri" or "?__filtertext".

Nanopublication · Open in Nanodash

Multi-value placeholders​

Nanopublication query templates extend grlc syntax by supporting placeholders that can have more than one value. Those have the suffix of "_multi_iri" (for IRIs) or just "_multi" (for literals). Importantly, they only work if there is at least one occurrence of a "values" statement like "values ?_resource_multi_iri {}", which indicates where the values are filled in. These multi-value placeholders take 1 or more IRIs/literals.

Every subquery scope needs its own values block. A block in the outer query does not reach into a subquery, and the mistake is silent: the subquery simply matches nothing and the query returns no rows rather than an error.

Starting the name with two underscores instead of one makes a multi-value placeholder optional, as in ?__resource_multi_iri, which accepts zero or more values. With none given, the values block stays empty and the query still runs unconstrained. This is the only placeholder form that can both be tested in the query and be left unfilled.

Nanopublication · Open in Nanodash

Single placeholders are substituted as text​

A single-value placeholder is not a bound SPARQL variable. Its value is substituted into the query as text before the query is parsed, so by the time the query runs the placeholder is gone and only the value remains.

The practical consequence is that bound(?_name) cannot be used: it becomes bound("some value"), which is not valid SPARQL. Guard a comparison with coalesce instead, which yields the fallback when the comparison cannot be evaluated:

filter(coalesce(?date >= ?_startDate, false))

Multi-value placeholders behave differently: they are bound through their values block and are ordinary variables inside the query.

Nanopublication · Open in Nanodash

Date and time parameters​

A literal placeholder is substituted as an untyped string, so comparing one against a typed value such as dct:created silently matches nothing: an untyped string and an xsd:dateTime are not comparable in SPARQL.

Cast the placeholder explicitly wherever it is compared:

filter(?date >= xsd:dateTime(?_startDate))

The value passed by the caller must then be a full ISO 8601 date and time, for example 2026-03-01T00:00:00Z. A bare date such as 2026-03-01 makes the cast fail.

Nanopublication · Open in Nanodash

Session-bound parameters​

Three placeholder names are reserved and filled automatically from the browser session of whoever is looking at the view, with no form field shown: LOCALPUBKEY is the viewer's signing public key, CURRENTUSER their agent IRI, and SITEURL the address of the Nanodash instance. They let a view react to who is viewing it, for example by offering a "retract" action only on rows the viewer signed.

Declare them as optional multi-value placeholders, each with its own empty values block in every scope where it is used: ?__LOCALPUBKEY_multi, ?__CURRENTUSER_multi_iri, ?__SITEURL_multi.

A logged-out visitor has none of them, so the variable is simply unbound and every comparison must tolerate that. Wrap each one in coalesce, as in coalesce(str(?pubkey) = str(?__LOCALPUBKEY_multi), false), so the query still returns its rows instead of failing or dropping them.

Nanopublication · Open in Nanodash

The context parameter​

A placeholder whose parameter name is context is filled automatically with the resource whose page the view is being shown on. Nothing needs to be declared beyond the placeholder itself.

On a resource's own page that is the resource. On the page of one of its parts it is the owning resource, while the view's own target field receives the part; both arrive in the same request. This is what lets a query about one part still find the space that maintains it, without naming that space in the query.

Declare it as an optional multi-value placeholder, ?__context_multi_iri, with its own values block in each scope. A federated service sub-select that uses only this placeholder shares no variable with the outer query and is therefore evaluated once, rather than once per result row.

Nanopublication · Open in Nanodash

Label companions for result columns​

Result columns that hold a URI can have a companion variable with a "_label" suffix to control how the value is displayed. The UI renders the label text as a clickable link to the URI. For example, a "?event" column paired with "?event_label" will display the label linked to the event URI. Without a label companion, the system renders URIs with its default formatting.

Nanopublication · Open in Nanodash

To include a link to the source nanopub in query results, add "?np" and "?np_label" as the last two columns in the SELECT clause, in that order. Use ("^" as ?np_label) to display a short clickable caret symbol instead of the full nanopub URI. These should always be placed at the end of the column list.

Nanopublication · Open in Nanodash

Multi-value result columns​

Result columns (not placeholders) can use the "_multi_iri", "_multi", and "_multi_val" suffixes to hold multiple concatenated values produced by group_concat:

_multi_iri — all values are URIs, separated by any whitespace (spaces, newlines, or tabs). Example: (group_concat(str(?item); separator=" ") as ?items_multi_iri)

_multi — all values are literals, separated by newlines, with escaping. Example: (group_concat(replace(replace(?text, "\\\\", "\\\\\\\\"), "[\r\n]+", "\\\\n"); separator="\n") as ?texts_multi)

_multi_val — values can be a mix of URIs and literals, separated by newlines, with escaping. Each value is checked individually: URIs (matching https?://) are rendered as links, literals are rendered as text or sanitized HTML. Example: (group_concat(replace(replace(str(?val), "\\\\", "\\\\\\\\"), "[\r\n]+", "\\\\n"); separator="\n") as ?values_multi_val)

Nanopublication · Open in Nanodash

Escaping in multi-value literal columns​

When concatenating literal values with a newline separator in group_concat, always escape existing backslashes and replace CR/LF sequences in the individual values first: replace(replace(?val, "\\\\", "\\\\\\\\"), "[\r\n]+", "\\\\n"). First escape existing backslashes (\\ → \\\\), then replace any sequence of CR/LF characters with the two-character escape \\n. This ensures values containing these characters can be safely split on newlines later.

Nanopublication · Open in Nanodash

Label companions for multi-value columns​

The "_label" naming convention extends to multi-value columns. For a "?things_multi_iri" column holding whitespace-separated URIs, use "?things_label_multi" as its label companion holding newline-separated labels (with the same escaping as for "_multi" literals). For example, "?authors_multi_iri" (whitespace-separated ORCIDs) paired with "?authors_label_multi" (newline-separated names) displays each author name linked to their URI.

Nanopublication · Open in Nanodash

Hiding a column header​

A result column whose variable name ends in "_noheader" is still rendered, but with its header label blanked. When no remaining column has a visible header, the header row disappears altogether, which suits a view meant to read as a list rather than a table.

The marker is stripped before the column name is interpreted, so type suffixes, "_label" companions and action mappings all keep matching the name without it. The companion columns themselves are left unmarked.

Nanopublication · Open in Nanodash

Grouping rows​

A result column whose variable name ends in "_group" is not shown as a column. Instead the table gets a heading row wherever that column's value changes from one row to the next, so the query's order by decides the groups and their order. Clicking a column header then sorts the rows within each group and leaves the groups in place.

Give every row of a group exactly the same value, and make it read well on its own, since it becomes the heading. Nanodash supports this from version 5.17; older versions show the column as an ordinary one.

Nanopublication · Open in Nanodash

Writing the SPARQL into the TriG​

When a query nanopublication is written by hand, the SPARQL sits inside a TriG string literal, and the TriG parser resolves backslash escapes before the SPARQL is ever seen. Every backslash meant for the SPARQL must therefore be doubled in the file.

The one that catches people is the separator of group_concat. Written as a single backslash, separator="\n" becomes a real line break inside a quoted SPARQL string, which is not valid SPARQL. Written as separator="\\n" in the TriG, it reaches the query as the two characters that were intended.

The safe way to produce the file is to build it from the raw query text with the backslashes doubled programmatically, then parse the result back and check that the round-tripped literal still contains the escape rather than a line break.

Nanopublication · Open in Nanodash

The SPARQL must parse​

A nanopublication cannot be changed once published, so a query whose SPARQL does not parse would be broken permanently: it could never run, and the only remedy would be publishing a corrected version.

Since nanopub-java 1.94.0 both signing and publishing refuse such a nanopublication, reporting the parser's own error, and check reports it as an issue. This catches the doubled-backslash mistake at signing time rather than after publication.

Where the parser stops at a character outside ASCII, the message names it, because these queries are more often broken by a character picked up from a word processor or a web page than by a mistyped keyword. A non-breaking space, for instance, is reported as Encountered: '160' (160).

Older versions of the tool have no such check: they sign and publish the nanopublication, and only the query API rejects it afterwards.

Nanopublication · Open in Nanodash

Testing a query before publishing​

A query template can be run before it is published. Encode the signed nanopublication in base64url and pass it as the _nanopub_trig parameter of an ordinary API call, together with the parameters the query expects. The service then answers using that nanopublication as if it had been published.

The same parameter works on the OpenAPI page, which gives a form for the query's parameters and is the easier way to try several values.

Testing this way matters because the checks made at signing time are about syntax only. A query that parses can still join nothing, return the wrong rows, or be too slow, and none of that is visible until it runs. Note also that a large query nanopublication makes the request too long for the w3id.org redirector, which answers with error 414. The query service itself accepts it, so send the same request to an instance's own address, such as https://query.knowledgepixels.com/api/…, rather than falling back to the bare repository, which skips the template's parameter handling.

Nanopublication · Open in Nanodash

This page is a copy of the topic Nanopublication query template of the Nanopublication Docs. Each paragraph is a nanopublication. In Nanodash you also find their examples, related paragraphs, and version history, and members of the nanopub space can edit them there.