sparqlrdfsemantic-webvirtuosonamed-graphs

Alternatives to SPARQL query with lots of UNIONs


I have some named graphs stored in Virtuoso, and I want to find the one that matches the highest number of terms from a provided list.

My query is constructed programatically and looks like this:

SELECT DISTINCT ?graph (count(DISTINCT ?match) as ?matches)
WHERE {
  GRAPH ?graph {
    {?match rdf:label "term 1"} 
     UNION {?match rdf:label "term 2"} 
     UNION {?match rdf:label "term 3"}
     ...
  }
}
ORDER BY DESC(?matches)

Each term becomes another UNION clause.

Is there a better way to do this? The query gets long and ugly fast, and Virtuoso complains when there are too many terms.


Solution

  • (it's rdfs:label)

    An alternative way to write it is:

    { ?match rdfs:label ?X . FILTER (?x in ("term 1", "term 2", "term 3")) }
    

    or (SPARQL 1.0)

    { ?match rdfs:label ?X . FILTER ( ?x = "term 1" || ?x = "term 2" || ?x = "term 3" )  }