Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SPARQL: How do you pass a variable into a subquery?

This works:

SELECT ?propLabel ?val WHERE {
    BIND("incoming"@en AS ?propLabel)
    {
      SELECT (COUNT(?s) AS ?val) WHERE {
        ?s ?p wd:Q8740.
        _:b72 wikibase:directClaim ?p.
      }
    }
}

But this does not, I assume because the sub-query is evaluated first, and therefore ?entity is not bound yet:

SELECT ?propLabel ?val WHERE {
  BIND(wd:Q8740 as ?entity)
    BIND("incoming"@en AS ?propLabel)
    {
      SELECT (COUNT(?s) AS ?val) WHERE {
        ?s ?p ?entity.
        _:b72 wikibase:directClaim ?p.
      }
    }
}

If so, how do we "pass" a variable into a subquery?

like image 513
T3db0t Avatar asked Dec 06 '25 22:12

T3db0t


1 Answers

Read the Optimizations in Blazegraph section in the SPARQL Bottom Up Semantics article, then help the optimizer slightly:

SELECT ?propLabel ?val WHERE {
  BIND (wd:Q8740 AS ?entity)
  BIND("incoming"@en AS ?propLabel)
  { 
    SELECT (COUNT(?s) AS ?val) ?entity WHERE {
      ?s ?p ?entity .
      [] wikibase:directClaim ?p 
    } GROUP BY ?entity
  } 
}

Try it!

Just add the ?entity variable to the projection (and then you should GROUP BY ?entity explicitely).
As a result, you will have additional joinVars=[entity] in the query plan.

It's interesting that such optimization can not be disabled using hint:Query hint:optimizer "None".

like image 170
Stanislav Kralin Avatar answered Dec 10 '25 00:12

Stanislav Kralin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!