T3db0t
T3db0t

Reputation: 3551

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?

Upvotes: 3

Views: 2363

Answers (1)

Stanislav Kralin
Stanislav Kralin

Reputation: 11479

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".

Upvotes: 3

Related Questions