开发者

How to bind a variable to a queried item in SPARQL

In this simple sparql query I get a list of subjects whose object is 42

SELECT ?v WHERE { ?v ?p 42 }

If I add ?p as开发者_StackOverflow中文版 a variable

SELECT ?v ?p WHERE { ?v ?p 42 }

I will get two entities per row, the subject and the predicate. What if I wanted three entities, so including the 42? Something like:

SELECT ?v ?p ?m WHERE { ?v ?p (42 as m) }


Another variant is to use BIND, e.g.:

SELECT ?v ?p ?m
WHERE {
  BIND(42 AS ?m)
  ?v ?p ?m
}

The BIND statement simply adds a binding for ?m, which can then be selected for the result set.


In SPARQL 1.1, you can use VALUES for this. You would write

SELECT ?v ?p ?m WHERE {
  values ?m { 42 }
  ?v ?p ?m
}


Standard SPARQL 1.0 does not really allow that. There may be some implementation-specific extensions for doing it, though.

As a workaround, if the data contains a triple with 42 as an object literal, you can do it e.g. like this:

SELECT ?v ?p ?m { ?v ?p 42, ?m FILTER(?m=42)}

which is equivalent with

 SELECT ?v ?p ?m WHERE { ?v ?p 42 . ?v ?p ?m FILTER(?m=42)}

as you can write graph patterns sharing the same subject and predicate with the comma object list notation, and the WHERE keyword is optional.

For efficiency, you want to use basic graph patterns to reduce the working triple to a smaller set and only then apply FILTER expressions to further prune the results.


You can accomplish in two ways using BINDINGS keyword as well as FILTER

Using BINDINGS

SELECT ?v ?p ?m 
WHERE { ?v ?p ?m}
BINDINGS ?m {(42)}

Using FILTER

SELECT ?v ?p ?m
WHERE {
?v ?p ?m
FILTER (?m = 42)
}


select ?v ?p ?m where { ?v ?p ?m . FILTER( ?m = 42 ) }


I know this is round-about, but I believe this is doable with a subquery.

This is a useful pattern to help you work on the query in the narrow, before you let it loose on your entire dataset:

SELECT ?v ?p ?m WHERE {
   { SELECT 42 as ?m WHERE { } }
   ?v ?p ?m .
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜