pythonsparqlsemantic-webrdflibgeosparql

Printing the broader and narrower concepts against the captured URI REF


I am having difficulty in printing the SKOS broader and narrower concepts against my URIRef (i.e. the output of the SPAQRL query). I want to print the Broader and Narrowers concepts against the captured URI REF (i.e. Biomass). The file which i am parsing does not contains the Broader and Narrowers concepts. I dont know whether i need to manually add them in file before i run queries on them.

I have already seen the similar questions like skos broader and narrow inverse not working but couldnt find the solution.

import rdflib
g = rdflib.Graph()
result = g.parse("C://Users/support/Documents/Re.txt", format=("turtle"))
qres = g.query(
    """
    prefix skos: <http://www.w3.org/2004/02/skos/core#> 
    
    SELECT  *
    WHERE { ?s  skos:prefLabel  "Biomass"} 
                     
    """)
for row in qres: print(row)

The output of the query is

for row in qres: print(row)
(rdflib.term.URIRef('http://aims.fao.org/aos/agrovoc/c_926'),) 

I have tried by nesting the SELECT Queries but it is not working.

My Query

qres = g.query(
    """
    prefix skos: <http://www.w3.org/2004/02/skos/core#> 
        
    SELECT *
    WHERE { ?s  skos:broader  ?o . { 
           
     
    SELECT  ?s
    WHERE { ?s  skos:prefLabel  "Biomass" .}  
 
          }     
                     
    """)
             
for row in qres: print(row)

Solution

  • If you're just struggling with the query, then I think you're overcomplicating it. This should work

    qres = g.query(
        """
        prefix skos: <http://www.w3.org/2004/02/skos/core#> 
            
        SELECT * WHERE { 
            ?s  skos:broader  ?o ; skos:prefLabel  "Biomass" . }   
                         
        """)