Changes

Jump to navigation Jump to search
5,523 bytes added ,  10:39, 25 April 2022
This article is part of the [[XQuery|XQuery Portal]]. Optimizations are presented that speed up the execution time and reduce memory consumption.
The article text will be further regularly extended with each version of BaseXfurther examples.
=Introduction=
# At parse time, the query string – an XQuery main module – is transformed to a tree representation, the ''abstract syntax tree'' (AST).
# At compile time, the syntax tree is decorated with additional information (type information, expression properties); expressions are relocated, simplified, or pre-evaluated:## Logical optimizations are ''context-independent''. They can be applied no matter which data will be processed later on.## Physical optimizations rely on context information, such as database statistics or available indexes.
# At evaluation time, the resulting expression tree is processed.
# The results are returned to the user. Some expression (such as simple loops) can be evaluated in iterative manner, whereas others (such as sort operations) need to be fully evaluated before the first result is available.
If you run a query on [[Command-Line_Options#Standalone|command-line]], you can use {{Code|-V}} to output detailed query information. In the [[GUI]], you can enable the Info View panel.
=Compile-Time Logical Optimizations=
==Pre-Evaluation==
Subsequent rewritings might result in query plans that differ a lot from the original query. As this might complicate debugging, you can disable function inling during development by setting {{Option|INLINELIMIT}} to {{Code|0}}.
==Static TypingLoop Unrolling== Loops with few iterations are ''unrolled'' by the XQuery compiler to enable further optimizations: <syntaxhighlight lang="xquery">(1 to 2) ! (. * 2) (: rewritten to :)1 ! (. * 2), 2 ! (. * 2) (: further rewritten to :)1 * 2, 2 * 2 (: further rewritten to :)2, 4</syntaxhighlight> Folds are unrolled, too: <syntaxhighlight lang="xquery">let $f := function($a, $b) { $a * $b }return fold-left(2 to 5, 1, $f) (: rewritten to :)let $f := function($a, $b) { $a * $b }return $f($f($f($f(1, 2), 3), 4), 5)</syntaxhighlight> The standard unroll limit is <code>5</code>. It can be adjusted with the {{Option|UNROLLLIMIT}} option, e.g. via a pragma: <syntaxhighlight lang="xquery">(# db:unrolllimit 10 #) { for $i in 1 to 10 return db:open('db' || $i)//*[text() = 'abc']} (: rewritten to :)db:open('db1')//*[text() = 'abc'],db:open('db2')//*[text() = 'abc'],...db:open('db10')//*[text() = 'abc'],</syntaxhighlight> The last example indicates that index rewritings might be triggered by unrolling loops with paths on database nodes. The following expressions can be unrolled: * Simple map expressions* Simple FLWOR expressions* Filter expressions* [[Higher-Order Functions#fn:fold-left|fn:fold-left]], [[Higher-Order Functions#fn:fold-right|fn:fold-right]], {{Function|Higher-Order Functions|fn:fold-left1}} Care should be taken if a higher value is selected, as memory consumption and compile time will increase. ==Paths== Due to the compact syntax of XPath, it can make a big difference if a slash is added or omitted in a path expression. A classical example is the double slash {{Code|//}}, which is a shortcut for {{Code|descendant-or-node()/}}. If the query is evaluated without optimizations, all nodes of a document are gathered, and for each of them, the next step is evaluated. This leads to a potentially huge number of duplicate node tree traversals, most of which are redundant, as all duplicate nodes will be removed at the end anyway. In most cases, paths with a double slash can be rewritten to descendant steps… <syntaxhighlight lang="xquery">(: equivalent queries, with identical syntax trees :)doc('addressbook.xml')//city,doc('addressbook.xml')/descendant-or-self::node()/child::city (: rewritten to :)doc('addressbook.xml')/descendant::city</syntaxhighlight> …unless the last step does not contain a positional predicate: <syntaxhighlight lang="xquery">doc('addressbook.xml')//city[1]</syntaxhighlight> As the positional test refers to the city child step, a rewritten query would yield different steps. Paths may contain predicates that will be evaluated again by a later axis step. Such predicates are either shifted down or discarded: <syntaxhighlight lang="xquery">(: equivalent query :)a[b]/b[c/d]/c (: rewritten to :)a/b/c[d]</syntaxhighlight>
If the type Names of a value is known at compile time, type checks nodes can be removedspecified via name tests or predicates. In the example belowIf names are e.g. supplied via external variables, the static information that {{Code|$i}} will always reference items of type {{Code|xs:integer}} predicates can often be utilized to simplify the expressiondissolved:
<syntaxhighlight lang="xquery">
for declare variable $i in 1 to 5return typeswitch($i) case xsname external :numeric return = 'numbercity'; default return db:open('stringaddressbook')/descendant::*[name() = $name]
(: rewritten to :)
for $i in 1 to 5return db:open('numberaddressbook')/descendant::city
</syntaxhighlight>
* {{Code|where}} clauses are rewritten to predicates.
* {{Code|if}} expressions in the return clause are rewritten to {{Code|where}} clauses.
 Since {{Version|9.4}}, the * The last {{Code|for}} clause is merged into the {{Code|return}} clause and rewritten to a [[XQuery_3.0|Simple_Map_Operator|simple map]] expression.
Various of these rewriting are demonstrated in the following example:
</syntaxhighlight>
==Static Typing== If the type of a value is known at compile time, type checks can be removed. In the example below, the static information that {{Code|$i}} will always reference items of type {{Code|xs:integer}} can be utilized to simplify the expression: <syntaxhighlight lang="xquery">for $i in 1 to 5return typeswitch($i) case xs:numeric return 'number' default return 'string' (: rewritten to :)for $i in 1 to 5return 'number'</syntaxhighlight> ==Pure Logic== If expressions can often be simplified: <syntaxhighlight lang="xquery">for $a in ('a', '')return $a[boolean(if(.) then true() else false())] (: rewritten to :)for $a in ('a', '')return $a[boolean(.)] (: rewritten to :)for $a in ('a', '')return $a[.] (: rewritten to :)('a', '')[.]</syntaxhighlight>
Boolean algebra (and set theory) comes with a set of laws that can all be applied to XQuery expressions.
| Distributivity
|- valign="top"
| <code>$a and or not($a)</code>
| <code>true()</code>
| Tertium non datur
* <code>true#0 and true#0</code> must raise an error; it cannot be simplified to <code>true#0</code>
==Paths=Physical Optimizations=
Due to the compact syntax of XPath, it can make a big difference if a slash is added or omitted Some physical optimizations are also presented in a path expression. A classical example is the double slash {{Codearticle on [[Indexes|//}}, which is a shortcut for {{Code|descendant-or-node()/}}. If the query is evaluated without optimizations, all nodes of a document are gathered, and for each of them, the next step is evaluated. This leads to a potentially huge number of duplicate node tree traversals, most of which are redundant, as all duplicate nodes will be removed at the end anywayindex structures]].
In most cases, paths with a double slash can be rewritten to descendant steps…==Database Statistics==
<syntaxhighlight lang="xquery">(: equivalent queries, with identical syntax trees :)doc('addressbook.xml')//cityIn each database,doc('addressbook.xml')/descendant-metadata is stored that can be utilized by the query optimizer to speed up or-node()/child:even skip query evaluation:city
(: rewritten to :)doc('addressbook.xml')/descendant::city</syntaxhighlight>;Count element nodes
…unless The number of elements that are found for a specific path need not be evaluated sequentially. Instead, the last step does not contain a positional predicatecount can directly be retrieved from the database statistics:
<syntaxhighlight lang="xquery">
doccount('addressbook.xml')/mondial/city[1]country) (: rewritten to :)231
</syntaxhighlight>
As the positional test refers to the city child step, a rewritten query would yield different steps.;Return distinct values
Paths may contain predicates The distinct values for specific names and paths can also be fetched from the database metadata, provided that will be evaluated again by a later axis step. Such predicates are either shifted down or discardedthe number does not exceed the maximum number of distinct values (see {{Option|MAXCATS}} for more information):
<syntaxhighlight lang="xquery">
distinct-values(: equivalent query :)a[b]/b[c/d]/creligions)
(: rewritten to :)
a/b/c[d]('Muslim', 'Roman Catholic', 'Albanian Orthodox', ...)
</syntaxhighlight>
Names of nodes can be specified via name tests or predicates. If names are e.g. supplied via external variables, the predicates can often be dissolved:==Index Rewritings==
<syntaxhighlight lang="xquery">declare variable $name external := 'city';db:open('addressbook')//*[name() = $name]A major feature of BaseX is the ability to rewrite all kinds of query patterns for index access.
(: rewritten to :)db:open('addressbook')//city</syntaxhighlight> =Index Rewritings= A major feature of BaseX is the ability to rewrite all kinds of query patterns for [[Indexes|database index access]]. The following queries are all equivalent. They will all be rewritten to exactly the same query that will eventually access the text index of a <code>factbook.xml</code> database instance (the file included in our full distributions):
<syntaxhighlight lang="xquery">
//name[. = 'Shenzhen'],
//name[data() = 'Shenzhen'],
//name[./text() = 'Shenzhen'],
//name[datatext() [. = 'Shenzhen']],
//name[string() = 'Shenzhen'],
//name[string() = 'Shen' || 'zhen'],
//name[text() ! data() ! string() = 'Shenzhen'],
.//name[. = 'Shenzhen'],db:open//*[local-name($DB)//= 'name'][. data() = 'Shenzhen'], 
db:open('factbook')//name[. = 'Shenzhen'],
db:open($DB)//name[. = 'Shenzhen'],
for $name in //name[text() = 'Shenzhen']
db:text('factbook', 'Shenzhen')/parent::name
</syntaxhighlight>
 
Multiple element names and query strings can be supplied in a path:
 
<syntaxhighlight lang="xquery">
//*[(ethnicgroups, religions)/text() = ('Jewish', 'Muslim')]
 
(: rewritten to :)
db:text('factbook', ('Jewish', 'Muslim'))/(parent::*:ethnicgroups | parent::*:religions)/parent::*
</syntaxhighlight>
 
If multiple candidates for index access are found, the database statistics (if available) are consulted to choose the cheapest candidate:
 
<syntaxhighlight lang="xquery">
/mondial/country
[religions = 'Muslim'] (: yields 77 results :)
[ethnicgroups = 'Greeks'] (: yields 2 results :)
 
(: rewritten to :)
db:text('factbook', 'Greeks')/parent::ethnicgroups/parent::country[religions = 'Muslim']
</syntaxhighlight>
 
If index access is possible within more complex FLWOR expressions, only the paths will be rewritten:
 
<syntaxhighlight lang="xquery">
for $country in //country
where $country/ethnicgroups = 'German'
order by $country/name[1]
return element { replace($country/@name, ' ', '') } {},
 
(: rewritten to :)
for $country in db:text('factbook', 'German')/parent::ethnicgroups/parent::country
order by $country/name[1]
return element { replace($country/@name, ' ', '') } {}
</syntaxhighlight>
 
The [https://projects.cwi.nl/xmark/ XMark XML Benchmark] comes with sample auction data and a bunch of queries, some of which are suitable for index rewritings:
 
;XMark Query 1
 
<syntaxhighlight lang="xquery">
let $auction := doc('xmark')
return for $b in $auction/site/people/person[@id = 'person0']
return $b/name/text()
 
(: rewritten to :)
db:attribute('xmark', 'person0')/self::attribute(id)/parent::person/name/text()
</syntaxhighlight>
 
;XMark Query 8
 
<syntaxhighlight lang="xquery">
let $auction := doc('xmark')
return
for $p in $auction/site/people/person
let $a :=
for $t in $auction/site/closed_auctions/closed_auction
where $t/buyer/@person = $p/@id
return $t
return <item person="{ $p/name/text() }">{ count($a) }</item>,
 
(: rewritten to :)
db:open('xmark')/site/people/person !
<item person='{ name/text() }'>{ count(
db:attribute('xmark', @id)/self::attribute(person)/parent::buyer/parent::closed_auction
)
}</item>
</syntaxhighlight>
 
If the accessed database is not known at compile time, or if you want to give a predicate preference to another one, you can [[Indexes#Enforce Rewritings|enforce index rewritings]].
=Evaluation-Time Optimizations=
==Comparisons==
In many cases, the amount of data to be processed is only known after the query has been compiled. Moreover, the data that is looped through expressions may change. In those cases, the best optimizations needs to be chosen at runtime.
If sequences of items are compared against each other, a dynamic hash index will be generated, and the total number of comparisons can be significantly reduced. In the following example, <code>count($input1) * count($input2)</code> comparisons would need to be made without the intermediate index structure:
</syntaxhighlight>
==Pre-Evaluation=Changelog=
=Changelog=;Version 9.6* Added: {{Option|UNROLLLIMIT}}
Introduced with Version 9.4.
Bureaucrats, editor, reviewer, Administrators
13,550

edits

Navigation menu