SPARQL query to get all class label with namespace prefix defined

前端 未结 2 1112
小蘑菇
小蘑菇 2020-12-01 23:13

I want to get all class that stored in sesame repository.

This is my query

SELECT ?class ?classLabel
WHERE {
?class rdf:type rdfs:Class.
?class rdfs         


        
2条回答
  •  [愿得一人]
    2020-12-01 23:21

    I agree with the other answers that say you're trying to do a strange thing, at least as it's stated in the question. Associating the prefix with the rdfs:label isn't all that useful, since the resulting string may or may not represent the actual URI of the class. Assuming that what you're trying to do is actually figure out a prefixed name for a URI given some set of prefix definitions, you can do this in SPARQL without needing lots of nested IFs; you can do it by using a VALUES and a FILTER.

    Given data like this, in which a number of classes are defined (I don't define any labels here, since they're not necessary for this example),

    @prefix rdfs:  .
    @prefix ex1:  .
    @prefix ex2:  .
    @prefix ex3:  .
    @prefix ex4:  .
    
    ex1:A a rdfs:Class .
    ex1:B1 a rdfs:Class .
    
    ex2:A a rdfs:Class .
    ex2:B2 a rdfs:Class .
    
    ex3:A a rdfs:Class .
    ex3:B3 a rdfs:Class .
    
    ex3:A a rdfs:Class .
    ex3:B4 a rdfs:Class .
    
    ex4:A a rdfs:Class .
    ex4:B4 a rdfs:Class .
    

    you can write a query like this that selects all classes, checks whether their URI begins with one of a number of defined namespaces, and if so, returns the class and the prefixed form:

    prefix rdfs:  
    
    select ?class (group_concat(?prefixedName ; separator = "") as ?prefName) where {
      values (?prefix ?ns) { 
        ( "ex1:"  )
        ( "ex2:"  )
        ( "ex3:"  )
      }
      ?class a rdfs:Class .
      bind( if( strStarts( str(?class), str(?ns) ),
                concat( ?prefix, strafter( str(?class), str(?ns) )),
                "" ) 
            as ?prefixedName )
    }
    group by ?class
    order by ?class
    

    which produces as results:

    $ arq --data data.n3 --query query.sparql
    ---------------------------------------
    | class                    | prefName |
    =======================================
    |   | "ex1:A"  |
    |  | "ex1:B1" |
    |   | "ex2:A"  |
    |  | "ex2:B2" |
    |   | "ex3:A"  |
    |  | "ex3:B3" |
    |  | "ex3:B4" |
    |   | ""       |
    |  | ""       |
    ---------------------------------------
    

提交回复
热议问题