Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 409
heyitsbmo Avatar asked Feb 18 '23 10:02

heyitsbmo


2 Answers

In SPARQL 1.1, there's a values clause that can help out with this. It lets you write:

select ?match where {
  values ?label { "term 1" "term 2" "term 3" }
  ?match rdfs:label ?label
}
like image 131
Joshua Taylor Avatar answered Mar 07 '23 22:03

Joshua Taylor


(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" )  }
like image 38
AndyS Avatar answered Mar 07 '23 22:03

AndyS