"if" in SPARQL query

my problem is very simple: I have a source my:g1

that contains:

my:a1 my:b "literal 1"

      

Then I have a second source my:g2

that contains:

my:a2 my:b my:c.
my:c rdfs:label "literal 2"

      

how can I set up a SPARQL query that creates something like:

| ?a    | ?b    | ?literal    |
|-------|-------|-------------|
| my:a1 | my:b  | "literal 1" |
| my:a2 | my:b  | "literal 2" |

      

i.e. how can I tell sparql to use the same variable for "literal 1"

and "literal 2"

: I am looking for something like

Select ?a ?b ?literal 
where {
 if (?g = my:g1) then
  GRAPH ?g { ?a ?b ?literal}
 else if (?g = my:g2) then
  GRAPH ?g { ?a ?b ?c. ?c rdfs:label ?literal}
}

      

NOTE. I know this request is terribly wrong, but just to clarify my intent.

EDIT:

in this particular case the "union" operator, for example

select ?a ?b ?literal 
where {
{
 GRAPH my:g1 { ?a ?b ?literal}
}
union
{
  GRAPH my:g2 { ?a ?b ?c. ?c rdfs:label ?literal}
}
}

      

will work, but this is not my "real" case. Are there any other solutions?

+3


source to share


1 answer


You can use property path and filter. The trick here is that a property path with a question mark means a path of length 0 or 1. If the path has length 0, then? Literal is the same as? C, which covers the case where α a is related directly to literal. If the path has length 1, then? Literal is rdfs: label meaning for? C.

Here's an example with real data:

@prefix : <urn:ex:>

:a :b "literal 1" .
:a :b :c .
:c :label "literal 2" .prefix : <urn:ex:>

      



select distinct ?a ?b ?literal where {
  ?a ?b ?c .
  ?c :label? ?literal
  filter isLiteral(?literal)
}

      

-----------------------------
| a  | b      | literal     |
=============================
| :a | :b     | "literal 1" |
| :a | :b     | "literal 2" |
| :c | :label | "literal 2" |
-----------------------------

      

You might not have expected the last line in the results, but what if? a and? b are variables, then it makes sense because it says nothing about what a variable is ? b must be associated with a specific property : b .

+2


source







All Articles