sparqlshacl

How to construct a SHACL shape using SPARQL


I have a ttl file with this information:

ex:Shape1
    a sh:NodeShape ;
    sh:property ex:Property-1
    rdfs:label "Shape 1"

ex:Property-1
    a sh:PropertyShape ;
    sh:path ex:property1
    sh:name "Property 1"

ex:property1
    a owl:DatatypeProperty

After loading the above data into my triple store (which contains many shapes already), what query can I use to retrieve the same data back?

I have tried a few things, the closest I got is the below query which returns every shape in my triple store (but not ex:property1):

PREFIX sh: <http://www.w3.org/ns/shacl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>
PREFIX ex: <http://example.com/#>

CONSTRUCT {
  ?subject ?predicate ?object
}
WHERE {
  ex:Shape1 sh:property ?propertyShape .
  { ex:Shape1 ?predicate ?object } UNION {  ?propertyShape ?predicate ?object }
  ?subject ?predicate ?object .
}

Solution

  • This query seems to do what I need:

    PREFIX sh: <http://www.w3.org/ns/shacl#>
    PREFIX ex: <http://example.com/#>
    
    CONSTRUCT {
      ?subject ?predicate ?object
    }
    WHERE {
      {
        bind(ex:Shape1 as ?subject)
        ex:Shape1 ?predicate ?object
      }
      UNION
      {
        ex:Shape1 sh:property ?subject .
        ?subject ?predicate ?object
      }
      UNION
      {
        ex:Shape1 sh:property/sh:path ?subject .
        ?subject ?predicate ?object
      }
    }