Search code examples
sparql

Conditional construct in SPARQL


I was wondering if it is possible to conditionally create some part of the construct clause. For instance assume we have the following construct query:

Construct {-:a a <smth:classtype>.
           -:a <smth:attr> ?b} WHERE
          {?c a <smth:anotherCalss>.
           Optional{?c <smth:anotherAttr> ?b}}

In this case ?b is not always bounded to smth. I want to only create a blank node -:a if ?b is bounded. Is there a way to add such conditions in the construct clause of sparql?


Solution

  • You can create the bnode conditionally in the WHERE clause by putting it inside the OPTIONAL:

    CONSTRUCT {?BN a <smth:classtype>.
               ?BN <smth:attr> ?b}
    WHERE
              {?c a <smth:anotherCalss>.
                Optional
                  {?c <smth:anotherAttr> ?b
                   BIND(BNODE()AS ?BN)
                  }
               }