Optimizing query performance using bif functions Example
The following example describes how to optimize query performance using bif functions.
- Suppose there is the following query, which performs very well on Virtuoso db with default indexes::
SELECT DISTINCT ?r (bif:concat(bif:search_excerpt(bif:vector('lego'), ?v2))) as ?_n_f_t_m_ex_ WHERE { { ?r ?v1 ?v2 . ?v2 bif:contains 'lego' . } UNION { ?r ?v1 ?v3 . ?v3 ?v4 ?v2 . ?v4 rdfs:subPropertyOf rdfs:label . ?v2 bif:contains 'lego' . } . } LIMIT 10
- Suppose also there should be hidden certain types from the user.
For the purposes of this, to the end of the query is added nao:userVisible property:
SELECT DISTINCT ?r (bif:concat(bif:search_excerpt(bif:vector('lego'), ?v2))) as ?_n_f_t_m_ex_ WHERE { { ?r ?v1 ?v2 . ?v2 bif:contains 'lego' . } UNION { ?r ?v1 ?v3 . ?v3 ?v4 ?v2 . ?v4 rdfs:subPropertyOf rdfs:label . ?v2 bif:contains 'lego' . } . ?r nao:userVisible "1"^^xsd:int . } LIMIT 10
-
The optimization:
- Replacing "?r nao:userVisible 1" with a bif:exists filter makes the query performance significant fast.
- Add Limit to each UNION, because in this case no one side of union will needlessly generate data that does not fit LIMIT 10.
- Some triples should reside in one graph, if this is applicable to the task in question.
E.g.
if both ?r ?v1 ?v2 . and ?r nao:userVisible "1"^^xsd:int . are supposed to be in same graph, then:
?r ?v1 ?v2 . ?v2 bif:contains 'lego' . -- can be replaced with: graph ?g { ?r ?v1 ?v2 . ?r nao:userVisible "1"^^xsd:int . ?v2 bif:contains 'lego' . }
- Finally, here is the optimized query:
PREFIX nao: <http://www.semanticdesktop.org/ontologies/2007/08/15/nao#> SELECT DISTINCT ?r (bif:concat(bif:search_excerpt(bif:vector('lego'), ?v2))) as ?_n_f_t_m_ex_ WHERE { { { SELECT DISTINCT ?r ?v2 WHERE { ?r ?v1 ?v2 . ?v2 bif:contains 'lego' . ?r nao:userVisible "1"^^xsd:int . } LIMIT 10 } } UNION { { SELECT DISTINCT ?r ?v2 WHERE { ?r ?v1 ?v3 . ?v3 ?v4 ?v2 . ?v4 rdfs:subPropertyOf rdfs:label . ?v2 bif:contains 'lego' . ?r nao:userVisible "1"^^xsd:int . } LIMIT 10 } } } LIMIT 10