Limit the result of a SPARQL query to the first level in the hierarchy

I use C # to execute a query in my N3 data files. How can I limit the result to the first level of node children. For instance:

project | |__ main | |__m1 | |__m2 | |__ SUB |__A | |__A1 | |__A2 | |__B |__C | |__C1 | |__D 

an example query, the result of which is the entire node level for SUB:

  select ?object where { :SUB rdfs:superClassOf* ?object } 

the result will be:

  |__A | |__A1 | |__A2 | |__B |__C | |__C1 | |__D 

But I want to limit the result to the first level of such children:

  |__A |__B |__C |__D 
+4
source share
1 answer

Choosing paths of length one

A property path using * finds paths of length or more. If you want to make the journey was exactly one, simply remove the length of * :

  select ?object where { :SUB rdfs:superClassOf ?object } 

I would notice that RDFS defines the rdfs:subClassOf , not the rdfs:superClassOf that you used in your request. I assume this is just a typo in the question. I think the actual query you want will be:

 select ?subclass where { ?subclass rdfs:subClassOf :SUB } 

Choosing arbitrary length paths

The solutions in this section are based on the answer to the question of finding the position of elements in the RDF list . Consider the following data:

 @prefix : <urn:ex:> . :a :p :b, :c . :b :p :d, :e . 

This query finds chains on p along with chain lengths:

 prefix : <urn:ex:> select ?sub ?sup (count(?mid)-1 as ?distance) where { ?sub :p* ?mid . ?mid :p* ?sup . } group by ?sub ?sup order by ?sub ?sup $ arq --data data.n3 --query query.sparql ------------------------ | sub | sup | distance | ======================== | :a | :a | 0 | | :a | :b | 1 | | :a | :c | 1 | | :a | :d | 2 | | :a | :e | 2 | | :b | :b | 0 | | :b | :d | 1 | | :b | :e | 1 | | :c | :c | 0 | | :d | :d | 0 | | :e | :e | 0 | ------------------------ 

Since we can get the length of the paths, we can filter on this length and get only the ones we want. For instance:

 prefix : <urn:ex:> select ?sub ?sup where { { select ?sub ?sup (count(?mid)-1 as ?distance) where { ?sub :p* ?mid . ?mid :p* ?sup . } group by ?sub ?sup order by ?sub ?sup } filter( ?distance = 2 ) # filter ( ?distance > 2 ) # alternative # filter ( ?distance < 10 ) # alternative } $ arq --data data.n3 --query query.sparql ------------- | sub | sup | ============= | :a | :d | | :a | :e | ------------- 

If you need only paths with a small, but a certain length, you can manually expand the path to the properties. For example, for paths of length two:

 prefix : <urn:ex:> select ?sub ?sup { ?sub :p/:p ?sup . } 

For a range of numbers, like 1-2, can you use ? that matches zero or one:

 prefix : <urn:ex:> select ?sub ?sup { ?sub :p/:p? ?sup . } 

For more information about property paths, be sure to check out Section 9 Property Paths in the SPARQL 1.1 Specification.

+6
source

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


All Articles