Search code examples
query-optimizationsparql

How do I limit the number of results for a specific variable in a SPARQL query?


Let's say I have a SPARQL query like this, looking for resources that have some shared property with a focal resource, and also getting some other statements about the focal resource :

CONSTRUCT {
  ?focal pred:icate ?shared .
  ?other pred:icate ?shared .
}
WHERE {
  ?focal pred:icate ?shared ;
         more:info ?etc ;
         a "foobar" .
  ?other pred:icate ?shared .
}
LIMIT 500

If there are more than 500 other resources, that LIMIT might exclude that more:info statement and object. So, is there a way to say "I only want at most 500 of ?other", or do I have to break this query into multiple pieces?


Solution

  • You can use LIMIT in subqueries, i.e. something like the following:

    CONSTRUCT {
      ?focal pred:icate ?shared .
      ?other pred:icate ?shared .
    }
    WHERE {
        ?focal pred:icate ?shared ;
               more:info ?etc ;
               a "foobar" .
        { 
          SELECT ?shared {
            ?other pred:icate ?shared .
          }
          LIMIT 500
        }
    }