Sesame caching common queries

86 views Asked by At

I use Sesame in a JSP web based application and I would like to know if there is any way to cache some queries that are used consistently.

1

There are 1 answers

0
Jeen Broekstra On

I assume that what you want to "cache" is the query result for a given query with specific value. You can very easily build such a cache yourself. Just create a class for the general query that internally keeps a reference to a HashMap that maps from a value key (e.g. the placeid for your example query) to a query result:

HashMap<URI, TupleQueryResult> cache = new HashMap<>();

Then all you do is check, for a given place id, if it is present in the cache. If it is not, you execute the query, get the result back and materialize it as a MutableTupleQueryResult which you can then put in that cache:

if (!cache.contains(placeId)) {
       // reuse the prepared query with the specific binding for which we want a result
       preparedQuery.setBinding("placeid", placeId);

       // execute the query and add the result to a result object we can reuse multiple times
       TupleQueryResult result = new MutableTupleQueryResult(preparedQuery.evaluate());

       // put the result in the cache.
       cache.put(placeId, result);
}
return cache.get(placeId);

If you want something a bit more sophisticated (e.g. something that throws out cached items after a certain time, or sets a size limit on your cache), I would have a look at using something like a Guava Cache instead of a simple HashMap, but the basic setup would remain the same.