query-00d8c38ccf7e73638eaf2e26c6ae2fd4

rq turtle/ttl

How to optimize nested OPTIONAL ?I'm learning Sparql query on wikidata but i have some issues about optimisation. I ask myself many questions to reduce the loading time. I gave myself a challenge to recover the administrative level subdivision of a country. My request works for some small countries but for others I have a "response limit" error. I imagine there are too many recusivities. I guess that's not the best way to go..

Use at

PREFIX wikibase: <http://wikiba.se/ontology#>
PREFIX wdt: <http://www.wikidata.org/prop/direct/>
PREFIX wd: <http://www.wikidata.org/entity/>
PREFIX bd: <http://www.bigdata.com/rdf#>
select distinct ?sub1 ?sub1Label ?sub2 ?sub2Label ?sub3 ?sub3Label ?sub4 ?sub4Label ?sub5 ?sub5Label where {
  ?sub1 wdt:P17 wd:Q142. filter exists { ?sub1 wdt:P31/wdt:P279* wd:Q10864048. }
  ?sub2 wdt:P131 ?sub1. filter exists { ?sub2 wdt:P31/wdt:P279* wd:Q13220204. }
  optional {
    ?sub3 wdt:P131 ?sub2. filter exists { ?sub3 wdt:P31/wdt:P279* wd:Q13221722. }
    optional {
      ?sub4 wdt:P131 ?sub3. filter exists { ?sub4 wdt:P31/wdt:P279* wd:Q14757767. }
      optional {
        ?sub5 wdt:P131 ?sub4. filter exists { ?sub5 wdt:P31/wdt:P279* wd:Q15640612. }
      }
    }
  }
 service wikibase:label { bd:serviceParam wikibase:language "en". }
}

Query found at

graph TD classDef projected fill:lightgreen; classDef literal fill:orange; classDef iri fill:yellow; v2("?sub1"):::projected v1("?sub2"):::projected v3("?sub3"):::projected v4("?sub4"):::projected v5("?sub5"):::projected a2((" ")) a1((" ")) a3((" ")) a4((" ")) a5((" ")) c14(["en"]):::literal c4(["wd:Q10864048"]):::iri c5(["wd:Q13221722"]):::iri c3(["wd:Q13220204"]):::iri c10(["wd:Q15640612"]):::iri c12(["bd:serviceParam"]):::iri c9(["wd:Q14757767"]):::iri c7(["wd:Q142"]):::iri f0[[" "]] subgraph f0e0["Exists Clause"] e0v1 --"wdt:P31"--> e0a1 e0a1 --"wdt:P279"--> e0c3 e0v1("?sub2"):::projected e0a1((" ")):::projected e0c3(["wd:Q13220204"]):::iri end f0--EXISTS--> f0e0 f0 --> v1 f0 --> c1 f0 --> a1 f0 --> c2 f0 --> c3 v1 --"wdt:P31"--> a1 a1 --"wdt:P279"--> c3 f1[[" "]] subgraph f1e1["Exists Clause"] e1v1 --"wdt:P31"--> e1a1 e1a1 --"wdt:P279"--> e1c3 e1v1("?sub1"):::projected e1a1((" ")):::projected e1c3(["wd:Q10864048"]):::iri end f1--EXISTS--> f1e1 f1 --> v2 f1 --> c1 f1 --> a2 f1 --> c2 f1 --> c4 v2 --"wdt:P31"--> a2 a2 --"wdt:P279"--> c4 v2 --"wdt:P17"--> c7 v1 --"wdt:P131"--> v2 subgraph optional0["(optional)"] style optional0 fill:#bbf,stroke-dasharray: 5 5; v3 -."wdt:P131".-> v1 subgraph optional1["(optional)"] style optional1 fill:#bbf,stroke-dasharray: 5 5; v4 -."wdt:P131".-> v3 subgraph optional2["(optional)"] style optional2 fill:#bbf,stroke-dasharray: 5 5; v5 -."wdt:P131".-> v4 end end end subgraph s1["http://wikiba.se/ontology#label"] style s1 stroke-width:4px; c12 --"wikibase:language"--> c14 end