"or" in a SPARQL query

I do not quite understand why they did not implement the basic logical operators in SPARQL. However, in most cases, you can get the same result in several ways.

The purpose of this question is a brief reference to possible deflection paths that the "or" operator can replace.

Here is what I can think of:

1) UNION

eg:

 SELECT * WHERE { { ?s :propA ?o } UNION { ?s :propB ?o } } 

- not often suitable, because it can become very verbose, because

 SELECT * WHERE { { GRAPH ?g {?s ?p ?o. ?o ?pp ?data1}} UNION { GRAPH ?g {?s ?p ?o. ?o ?pp ?data2}} } 

doesn't work like

 SELECT * WHERE { GRAPH ?g { ?s ?p ?o. {?o ?pp ?data1} UNION {?o ?pp ?data2} } } 

(at least not with Stardog)

2) FILTER

eg:

 SELECT * WHERE { ?s ?p ?o. FILTER (?p = :propA || ?p = :propB ) } 

Any other ideas?

+6
source share
2 answers

I'm not quite sure why you say that SPARQL does not provide "basic logical operators" because your own examples clearly show what it does: it provides logical-OR ( || ) and logical-AND ( && ) as part of the conditions FILTER and disjunctive graphical patterns using UNION (of course, conjunctive graph patterns do not need special syntax).

Other OR design options are possible. For form queries โ€œthis particular value must be one of these featuresโ€ you can use the element set operator, IN :

 SELECT * WHERE { ?s ?p ?o. FILTER (?p IN (:propA, :propB, :propC ) ) } 

You can also use the VALUES clause for this type of template:

 SELECT * WHERE { VALUES ?p { :propA :propB :propC } ?s ?p ?o. } 

Update I forgot one, perhaps the easiest. For queries like yours, where you are looking for several alternatives for a property name, you can also use a property path expression, for example:

 SELECT * WHERE { ?s :propA|:propB|:propC ?o. } 
+11
source

If you want to track which predicate leadership relates to an object, then this is a universal solution for OR:

 SELECT DISTINCT ?s ?o1 ?o2 WHERE { { ?s p1 ?o1 . OPTIONAL { ?s p2 ?o2 . } } UNION { ?s p2 ?o2 . OPTIONAL { ?s p1 ?o1 . } } } 
+2
source

Source: https://habr.com/ru/post/988074/


All Articles