2.9.5 Expression Caching

Expression Caching is a powerful feature to create well-performing functionally rich applications. You can use it for query result caching (avoiding to compute the same query twice), as a mechanism to simulate cursors; allowing an expensive query that delivers large result to be evaluated once, allowing subsequent queries to show small parts of a result set, that eg fit on the screen.

The mechanism allows Caching of Arbitrary Subexpressions inside a so-called Multi-Query Session.

To profit from these, one should restructure the data access of applications to use the same database snapshot for multiple queries (with a long enough timeout to be sure the session stays alive in the cache).

As a second step, the XQuery queries should be analyzed and interesting expressions could be marked up. The marked up expressions are cached; if a query find them already cached, the result is available instantly.

One typical use of subexpression caching is skipping quickly paging back and forth through a large query result (what SQL users use "cursors" for), e.g. showing the elements in range [LO,HI], without having to recompute the entire result for each query:

(# pf:session my-own-id:30000 #) {
  subsequence((# pf:cache my-male-persons #) { doc("auctions.xml)//person[gender = "male"] }, LO, HI)
}

Note the entire query is wrapped in a pf:session XQuery pragma, which gives the session an ID (my-own-id). It also specifies a keep-alive time for the session of 30 seconds here. Then, inside the query body, the subexpression that retrieves all male persons is wrapped in a pf:cache pragma, identifying the expression by ID again (my-male_persons). The effect is that the first query will compute all male persons, but all subsequent invocations will have them already available; these queries will return instantly.

The in-session subexpression caching mechanism described in detail in see Session Expression Cache.