Skip to content

Commit 5ced848

Browse files
committed
Cache exact count operation in CompositeDatasource
1 parent 63a55c3 commit 5ced848

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

lib/datasources/CompositeDatasource.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
/** A CompositeDatasource delegates queries to an consecutive list of datasources. */
44

5-
var Datasource = require('./Datasource');
5+
var Datasource = require('./Datasource'),
6+
LRU = require('lru-cache');
67

78
// Creates a new CompositeDatasource
89
function CompositeDatasource(options) {
@@ -28,6 +29,7 @@ function CompositeDatasource(options) {
2829
this._datasourceNames.push(datasourceName);
2930
}
3031
}
32+
this._countCache = LRU({ max: 1000, maxAge: 1000 * 60 * 60 * 3 });
3133
}
3234
Datasource.extend(CompositeDatasource);
3335

@@ -53,12 +55,21 @@ CompositeDatasource.prototype._getDatasourceById = function(datasourceIndex) {
5355

5456
// Count the amount of triple in the query result to get an exact count.
5557
CompositeDatasource.prototype._getExactCount = function(datasource, query, cb) {
58+
// Try to find a cache match
59+
var cacheKey = query.subject + "|" + query.predicate + "|" + query.object;
60+
var cache = this._countCache, count = cache.get(cacheKey);
61+
if (count) return setImmediate(cb, count);
62+
63+
// Otherwise, count all the triples manually
5664
var emptyQuery = { offset: 0, subject: query.subject, predicate: query.predicate, object: query.object };
5765
var exactCount = 0;
5866
var countingTripleStream = { push: function(triple) {
5967
if (triple) {
6068
exactCount++;
6169
} else {
70+
// Cache large values; small ones are calculated fast anyway
71+
if (exactCount > 1000)
72+
cache.set(cacheKey, exactCount);
6273
cb(exactCount);
6374
}
6475
}};

0 commit comments

Comments
 (0)