SPARQL limiting the query result by a variable instead of the number of rows

白昼怎懂夜的黑 提交于 2019-12-13 02:12:48

问题


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     |
--------------------------------------------------------------------


来源:https://stackoverflow.com/questions/32309813/sparql-limiting-the-query-result-by-a-variable-instead-of-the-number-of-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!