Search code examples
concatenationsparqlwikidata

SPARQL how to use concatenated strings for a subject of a subquery?


I created a SPARQL query like below. I get ?year and ?month from SERVICE query in Wikidata, and would like to use them as a part of a subject of a subquery (i.e. ?uri ?p ?o part). I managed to concatenate ?year and ?month and generate a URI, but somehow the the query does not return a result.

I tested both the subquery part (e.g. only using <https://example.com/date/10-1> ?p ?o) and the SERVICE query individually. They both return results properly (13 and 5 results respectively, so the size is not an issue). My guess is it is concatenated variable is a string not URI, which cannot be a subject. But I am not sure. As I am not sure what is wrong, I tried similar queries, but they get time-out, due to the subquery I think. Can you spot the problem and let me know how to fix it? Many thanks in advance!

SELECT DISTINCT ?event ?eventLabel ?d1 ?d2 ?d3 ?date ?year ?month ?uri ?p ?o
WHERE {

 SERVICE <https://query.wikidata.org/sparql> {
    select DISTINCT ?event ?eventLabel ?d1 ?d2 ?d3 ?date ?year ?month
    where{
      ?event wdt:P31/wdt:P279* wd:Q13418847  .
      ?event wdt:P276 wd:Q1741  .
      OPTIONAL {?event wdt:P580 ?d1}
      OPTIONAL {?event wdt:P585 ?d2}
      OPTIONAL {?event wdt:P582 ?d3}
      BIND(IF(!BOUND(?d1),(IF(!BOUND(?d2),?d3,?d2)),?d1) as ?date)
      BIND(year(?date) AS ?year)
      BIND(month(?date) AS ?month)
      SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE], en". }
   }
   ORDER BY ?date
   LIMIT 100
 }
 BIND(CONCAT("<https://example.com/date/", str(?year), "-", str(?month), ">") AS ?uri) .
  
 {
  SELECT ?uri ?p ?o 
    WHERE {?uri ?p ?o .}
  LIMIT 10
 }
}

Solution

  • You can use the IRI function to make the string (without the </>) into a URI:

    BIND(IRI(CONCAT("https://example.com/date/", str(?year), "-", str(?month))) AS ?uri) .