Sparql - Conditional Output

525 views Asked by At

I am very new to the semantic web and sparql. I have an internal ontology that uses SmartLogic in order to manage the data.

I am writing some simple queries to get started.


PREFIX skos: <http://www.w3.org/2004/02/skos/core#> # Simple Knowledge Organization System - https://www.w3.org/2004/02/skos/
PREFIX skosxl: <http://www.w3.org/2008/05/skos-xl#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <https://www.w3.org/TR/rdf-schema/>
prefix owl: <http://www.w3.org/2002/07/owl#> 
prefix ap: <http://cv.ap.org/ns>

SELECT DISTINCT
           ?subjectPrefLabel  ?p ?o ?oL

         WHERE {

           {
             ?subject skosxl:prefLabel ?subjectLabel .
             ?subjectLabel skosxl:literalForm ?subjectPrefLabel .
             ?subject ?p ?o .
             OPTIONAL {?o skos:prefLabel ?oL} 

           }

           FILTER regex(?subjectPrefLabel, "Trump", 'i')


         } order by ?subjectPrefLabel

This query returns results that look like :

enter image description here

I am trying to merge the ?o and ?oL fields, so that it will replace the ?o field, if and only if there is a valid ?oL Field

I haven't been able to figure it out quite yet. If there is any suggestions please let me know.

1

There are 1 answers

1
UninformedUser On BEST ANSWER

A bit difficult without data for testing the query, but in SPARQL 1.1 you can use BIND(IF(condition,then,else) as ?result ):

PREFIX  skosxl: <http://www.w3.org/2008/05/skos-xl#>
PREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX  owl:  <http://www.w3.org/2002/07/owl#>
PREFIX  skos: <http://www.w3.org/2004/02/skos/core#>
PREFIX  rdfs: <https://www.w3.org/TR/rdf-schema/>
PREFIX  ap:   <http://cv.ap.org/ns>

SELECT DISTINCT  ?subjectPrefLabel ?p ?o
WHERE
  { ?subject  skosxl:prefLabel    ?subjectLabel .
    ?subjectLabel
              skosxl:literalForm  ?subjectPrefLabel .
    ?subject  ?p                  ?o_tmp
    OPTIONAL
      { ?o_tmp  skos:prefLabel  ?oL }
    BIND(if(bound(?oL), ?oL, ?o_tmp) AS ?o)
    FILTER regex(?subjectPrefLabel, "Trump", "i")
  }
ORDER BY ?subjectPrefLabel