[SPARQL] SERVICE

SERVICE Keyword in SPARQL

How did I encounter this?

While working a story to enhance the searching featuring against Wikidata, I found a way to use external endpoints within the SPARQL query to Wikidata. Even though it ended up being not useful because calling external endpoints is not allowed security-wise on public Wikidata query service, I am leaving a trace here.

Syntax

A SPARQL query can call external endpoints using the SERVICE keyword. The query is not restricted to a single RDF dataset; it can retrieve or merge data from other sources. One example is calling the Wikidata Query Service or additional HTTP endpoints.

SERVICE <endpoint-URL> {
  ... patterns or parameters ...
}

Usage Scenarios

  • Federated Queries: Queries distributed across multiple SPARQL endpoints, merging related data.
  • Special Services: Wikibase-based platforms, such as Wikidata, often provide extra features (like SERVICE wikibase:label or SERVICE wikibase:mwapi) that perform actions beyond basic graph lookups.

Example

SELECT ?item ?itemLabel
WHERE {
  SERVICE <https://dbpedia.org/sparql> {
    ?item a dbo:Book .
    ?item rdfs:label ?itemLabel .
    FILTER(LANG(?itemLabel) = "en")
  }
}

In this example, the query calls the DBpedia SPARQL endpoint. The SERVICE block fetches English labels for resources typed as dbo:Book.

Points to Note

  1. Security & Permissions

    Some SPARQL endpoints limit which external hosts can be queried. If an external service is disallowed, the query fails with a host-not-allowed error.

  2. Performance

    Each service call adds overhead. Large-scale federations can experience timeouts or slow responses.

  3. Extended Features

    Wikibase-based endpoints sometimes define custom services (like mwapi), enabling calls to the MediaWiki API.

The SERVICE keyword brings flexibility to SPARQL, allowing a single query to gather data from multiple locations or invoke specialized functions.

Comments