cyroxx
cyroxx

Reputation: 3877

Boolean checks in SPARQL, check for existence of a statement

Let's say I have a triple store full of video metadata. A video can have an arbitrary selection of pre-defined tags, like this:

v1 ex:hasTag A.
v2 ex:hasTag B.
v3 ex:hasTag A;
   ex:hasTag B.

So for the sake of this example, there are only the two pre-defined tags A and B.

Now I would like to get an overview of which video has which tags attached, in a matrix like this (or similar):

    A     B 

v1  true  false
v2  false true
v3  true  true

However, I do not know how to achieve this. First of all, I would need a boolean test, e.g. something like isTrue(?video ex:hasTag A) or whatever it looks like. Even then, I do not know where to put it. If I put the previous statement in the WHERE clause, the query result only contains the videos having the tag A, of course.

Coming from SQL, I can imagine I need to use subqueries in some way, but these seem not to be standardized at the moment. I also saw the FILTER keyword, but I don't feel that is what I want.

I'm currently at a loss but always willing to learn. Any help is appreciated.

Upvotes: 7

Views: 8656

Answers (2)

AndyS
AndyS

Reputation: 16700

Subqueries are in SPARQL 1.1 and that is frozen now. There several complete implementations already.

As well as nested-SELECT subqueries, SPARQL 1.1 has the EXISTS and NOT EXISTS functions for testing whether a pattern matches or not. It#'s a form of subquery. You can use it in a FILTER or if you really want to return true/false:

BIND(EXISTS{?video ex:hasTag "A"} AS ?a)

or even:

SELECT ?video (EXISTS{?video ex:hasTag "A"} AS ?a) (EXISTS{?video ex:hasTag "B"} AS ?b)
{           
  ?video a ex:Video .
}

Upvotes: 7

user205512
user205512

Reputation: 8898

Try starting with something like this:

SELECT ?video ?tagA ?tagB {
  ?video a ex:Video .
  OPTIONAL { ?video ex:hasTag ?tagA . FILTER (?tagA = "A") }
  OPTIONAL { ?video ex:hasTab ?tagB . FILTER (?tagB = "B") }
}

That will you roughly what you want. If you really must have boolean values rather than simple checking for unbound vals use:

SELECT ?video (bound(?tagA) as ?a) (bound(?tagB) as ?b) { ... }

P.S. Subqueries are (very nearly, proposed recommendation at time of writing) standardised in SPARQL 1.1.

Upvotes: 4

Related Questions