-->

SPARQL limiting the query result by a variable ins

2019-08-15 04:43发布

问题:

Lets say I have the following data set:

:a  rdf:type      :AClass
:a  :hasName      "a"^^xsd:string
:a  :hasProperty  :xa
:a  :hasProperty  :ya
:a  :hasProperty  :za

:b  rdf:type      :AClass
:b  :hasName      "b"^^xsd:string
:b  :hasProperty  :xb
:b  :hasProperty  :yb

:c  rdf:type      :AClass
:c  :hasName      "c"^^xsd:string
:c  :hasProperty  :xc

I want to query the data set to give me back everything of an instance of :AClass, but only for two instances. I know I have to use the LIMIT keyword, and I have tried a lot of queries but with no success.

In other words, I want to get back this:

:a  :hasName      "a"^^xsd:string
:a  :hasProperty  :xa
:a  :hasProperty  :ya
:a  :hasProperty  :za

:b  :hasName      "b"^^xsd:string
:b  :hasProperty  :xb
:b  :hasProperty  :yb

How can I limit the result to the number of 2 instances and NOT to number of 2 rows?

回答1:

Use a subquery to select the two things, and then get the rest of the data in an outer query. It always helps to show legal working data that we can test with. The data you've shown isn't actually legal RDF (since it's missing some periods at the ends of lines), but we can easily create a working example. Here's working data, a query, and the results:

@prefix : <urn:ex:>

:a a :AClass .
:a :hasName "a" .
:a :hasProperty :xa .
:a :hasProperty :ya .
:a :hasProperty :za .

:b a :AClass .
:b :hasName "b" .
:b :hasProperty :xb .
:b :hasProperty :yb .

:c a :AClass .
:c :hasName "c" .
:c :hasProperty :xc .
prefix : <urn:ex:>

select ?s ?p ?o {
  #-- first, select two instance of :AClass
  { select ?s { ?s a :AClass } limit 2 }

  #-- then, select all the triples of
  #-- which they are subjects
  ?s ?p ?o
}
--------------------------------------------------------------------
| s  | p                                                 | o       |
====================================================================
| :a | <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> | :AClass |
| :a | :hasName                                          | "a"     |
| :a | :hasProperty                                      | :xa     |
| :a | :hasProperty                                      | :ya     |
| :a | :hasProperty                                      | :za     |
| :b | <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> | :AClass |
| :b | :hasName                                          | "b"     |
| :b | :hasProperty                                      | :xb     |
| :b | :hasProperty                                      | :yb     |
--------------------------------------------------------------------