SPARQL and XQuery Together
In this exercise, you'll learn how to use SPARQL and XQuery together in a few different ways. We'll write queries on the BBC news documents and related triples we loaded in the second exercise.
We have provided versions of these queries in the associated Query Console workspace, sparql-xquery.xml.
From Query Console, use query type "XQuery" against your "tutsem" database.
When you run in XQuery, wrap the SPARQL with
sem:sparql(), and don't forget:
For example, the following simple query for people born in Brooklyn can be written in XQuery:
If you recall from our previous exercise, for a specific IRI, we can find all the subjects added by OpenCalais and organize them by type with a query like:
But, let's say we'd like to do this for an arbitrary document. The
sem:sparql function takes a
second parameter, which is a map of parameter bindings. We can use it to pass in
an IRI like this:
Now, if you know how to use MarkLogic XQuery search APIs, you should be able to find all news items with "Elton John" in their title and show their OpenCalais subjects. Try this on your own (the answer is in the provided sparql-xquery.xml workspace).
actually takes several arguments beyond the bindings we used above. In particular,
you can use the fourth argument to constrain the query.
Let's say you're interested in cities. First you can find all the cities mentioned in the news like this:
But now, say you'd like to restrict that to city names mentioned in certain articles. Here, let's find all the city names referenced in articles that have the phrase "dark magic". We can constrain the SPARQL query as:
OK, now let's go the other way, taking something from SPARQL and passing it into XQuery.
Let's use SPARQL CONSTRUCT to construct triples and
xdmp:node-insert-child() to insert them into a document.
(Yes, you can embed triples directly in documents ourselves if you want).
Yes, it's that easy to take the output of a SPARQL query and use it in XQuery.
What formats does
You can try each of the different kinds of SPARQL queries (SELECT, CONSTRUCT, ASK, DESCRIBE)
and wrap them
xdmp:describe() to see the format
of the result.
There are queries in the associated workspace for this, but in case you're too impatient to click over, here's what you'll get:
|SELECT||sequence of JSON objects|
|CONSTRUCT||sequence of sem:triple()|
|DESCRIBE||sequence of sem:triple()|
There are a couple other useful functions for serializing RDF and SPARQL query results that you can use:
sem:tripleto RDF (turtle, ntriple, and so on)
sem:query-results-serialize()– serialize ANY SPARQL result (from sem:sparql) as XML or JSON
As an exercise, you can use these to format the results of each kind of SPARQL query as RDF (where applicable), XML, or JSON.
ReferencesQuery Console Workspace ts-sparql-xquery.xml.
Using the Triple Index