CacheHelper

interface CacheHelper

A utility class that gives hooks in order to help build a cache based on the data that is contained in this index.

Example: cache the number of documents that match a query per reader.

public class QueryCountCache {

private final Query query;
private final Map<IndexReader.CacheKey, Integer> counts = new ConcurrentHashMap<>();

// Create a cache of query counts for the given query
public QueryCountCache(Query query) {
this.query = query;
}

// Count the number of matches of the query on the given IndexSearcher
public int count(IndexSearcher searcher) throws IOException {
IndexReader.CacheHelper cacheHelper = searcher.getIndexReader().getReaderCacheHelper();
if (cacheHelper == null) {
// reader doesn't support caching
return searcher.count(query);
} else {
// make sure the cache entry is cleared when the reader is closed
cacheHelper.addClosedListener(counts::remove);
return counts.computeIfAbsent(cacheHelper.getKey(), cacheKey -> {
try {
return searcher.count(query);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
}

}
*

Properties

Link copied to clipboard

Get a key that the resource can be cached on. The given entry can be compared using identity, ie. Object.equals is implemented as == and Object.hashCode is implemented as System.identityHashCode.

Functions

Link copied to clipboard
abstract suspend fun addClosedListener(listener: IndexReader.ClosedListener)

Add a ClosedListener which will be called when the resource guarded by .getKey is closed.