Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of two selects in a SPARQL query

Tags:

sparql

dbpedia

I'd like to do something like

{
    SELECT ?page, "A" AS ?type WHERE 
    {
         ?s rdfs:label "Microsoft"@en;
            foaf:page ?page
    }
}
UNION
{
    SELECT ?page, "B" AS ?type WHERE 
    {
         ?s rdfs:label "Apple"@en;
            foaf:page ?page
    }
}

But this gives a syntax error. How can I union two select queries in SPARQL?

like image 811
Timm Avatar asked May 29 '12 10:05

Timm


2 Answers

You can union them like this:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT * WHERE
{ 
{
    SELECT ?page ("A" AS ?type) WHERE 
    {
         ?s rdfs:label "Microsoft"@en;
            foaf:page ?page
    }
}
UNION
{
    SELECT ?page ("B" AS ?type) WHERE 
    {
         ?s rdfs:label "Apple"@en;
            foaf:page ?page
    }
}
}

(check with the SPARQL validator)

However I don't think you need sub queries at all for this case. For example:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT ?page ?type WHERE
{
    ?s foaf:page ?page .
    { ?s rdfs:label "Microsoft"@en . BIND ("A" as ?type) }
    UNION
    { ?s rdfs:label "Apple"@en . BIND ("B" as ?type) }
}
like image 116
user205512 Avatar answered Oct 06 '22 00:10

user205512


Based on @user205512's answer, here's one that works on Virtuoso:

SELECT * {
    ?s foaf:page ?page .
    {
        SELECT ?page ("A" AS ?type) {
            ?s rdfs:label "Microsoft"@en;
               foaf:page ?page
        }
    } UNION {
        SELECT ?page ("B" AS ?type) {
            ?s rdfs:label "Apple"@en;
               foaf:page ?page
        }
    }
}

The trick was just do add an additional ?s foaf:page ?page triple outside of the UNION. This is obviously redundant, but it seems to avoid the Virtuoso bug, which is apparently caused when you have a “naked” UNION with subqueries.

like image 27
cygri Avatar answered Oct 05 '22 22:10

cygri