Skip to content

Instantly share code, notes, and snippets.

@rubensworks
Created March 22, 2018 05:44
Show Gist options
  • Save rubensworks/34bb69fa6c83176bce60a5e8a25051e8 to your computer and use it in GitHub Desktop.
Save rubensworks/34bb69fa6c83176bce60a5e8a25051e8 to your computer and use it in GitHub Desktop.

This is a short guide that explains how you can execute a federated query with Comunica.

Command line

We will execute a query to find all books in the Harvard Library that were written by people who were born in Ghent. We do this by federating over DBpedia (SPARQL), the Harvard library (TPF) and the VIAF dataset (TPF).

  1. Make sure Node.js (>=8.0.0) is installed: https://nodejs.org/en/
  2. Install Comunica: npm install -g @comunica/actor-init-sparql
  3. Execute the following command:
comunica-sparql \
sparql@https://dbpedia.org/sparql hypermedia@http://data.linkeddatafragments.org/viaf \
hypermedia@http://data.linkeddatafragments.org/harvard \
'PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX schema: <http://schema.org/>
PREFIX dc: <http://purl.org/dc/terms/>

SELECT ?person ?name ?book ?title {
  ?person dbpedia-owl:birthPlace ?birthplace.
  ?birthplace rdfs:label "Ghent"@en.
  ?viafID schema:sameAs ?person;
          schema:name ?name.
  ?book dc:contributor ?contributor;
        dc:title ?title.
  ?contributor foaf:name ?name.
}'

Code

If you're feeling adventurous, you can trigger the same query via the following JavaScript snippet:

const newEngine = require("@comunica/actor-init-sparql").newEngine;
const RdfString = require("rdf-string");

// Define our query and sources
const query = `
PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX schema: <http://schema.org/>
PREFIX dc: <http://purl.org/dc/terms/>

SELECT ?person ?name ?book ?title {
  ?person dbpedia-owl:birthPlace ?birthplace.
  ?birthplace rdfs:label "Ghent"@en.
  ?viafID schema:sameAs ?person;
          schema:name ?name.
  ?book dc:contributor ?contributor;
        dc:title ?title.
  ?contributor foaf:name ?name.
}`;
const sources = [
  { type: 'sparql', value: 'https://dbpedia.org/sparql' },
  { type: 'hypermedia', value: 'http://data.linkeddatafragments.org/viaf' },
  { type: 'hypermedia', value: 'http://data.linkeddatafragments.org/harvard' },
];

// Execute the query
newEngine().query(query, { sources: sources })
  .then(function (result) {
    result.bindingsStream.on('data', function (bindings) {
      console.log(JSON.stringify(bindings.map(RdfString.termToString)).trim());
    });
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment