Search code examples
sparqlrdfturtle-rdf

Obtaining the rdf:type of the root node


I have the following data:

@prefix ex: <http://example.com/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix sch: <http://schema.org/> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<ex:a4fe06ac906b092870> a ex:XXXX ;
    ex:pA [ a ex:YYYY ;
            ex:bar "value" ;
            ex:foo "" ;
            ex:name "another_name" ] ;
    ex:pB "another_value" ;
    ex:pC [ a ex:ZZZZ ;
            ex:identifier "the id" ;
            ex:index "asdf" ] .

which can be visualized as this.

The root node is defined to be the node with no incoming edges.

The root node in this sample is ex:a4fe06ac906b092870 and the rdf:type is ex:XXXX.

What SPARQL query would return to me ex:XXXX?


Solution

  • Based on UninformedUser's comment, the SPARQL query that will return the rdf:type of the root node is:

            SELECT ?o 
            WHERE { 
                ?s a ?o . 
                FILTER NOT EXISTS {
                    ?s_in ?p_in ?s .
                } 
            }
    

    Since the rdf:type of the root node is desired, only those subjects with a rdf:type edge need to be considered ( ?s a ?o . ).

    ?s_in ?p_in ?s . in the filter will match all of the nodes with a rdf:type edge which have an incoming edge. These nodes are then filtered out of the results.

    What is left is the rdf:type of the root node.