Product Documentation : Ehcache Developer Guide : Searching a Cache : Making a Cache Searchable
Making a Cache Searchable
Caches can be made searchable, on a per cache basis, either by configuration or programmatically.
By Configuration
Caches are made searchable by adding a <searchable/> tag to the cache definition in the ehcache.xml file.
<cache name="cache2" maxBytesLocalHeap="16M" eternal="true"
<persistence strategy="localRestartable"/>
This configuration will scan keys and values and, if they are of supported search types, add them as attributes called “key” and “value,” respectively. If you do not want automatic indexing of keys and values, you can disable it using:
<cache name="cacheName" ...>
<searchable keys="false" values="false">
You might want to do this if you have a mix of types for your keys or values. The automatic indexing will throw an exception if types are mixed.
If you think that you will want to add search attributes after the cache is initialized, you can explicitly indicate the dynamic search configuration. Set the allowDynamicIndexing attribute to “true” to enable use of the Dynamic Attributes extractor. For more information about the Dynamic Attributes extractor, see Defining Attributes.
<cache name="cacheName" ...>
<searchable allowDynamicIndexing="true">
Often keys or values will not be directly searchable and instead you will need to extract searchable attributes from the keys or values. The following example shows a more typical case. Attribute extractors are explained in more detail in Defining Attributes.
<cache name="cache3" maxEntriesLocalHeap="10000" eternal="true"
<persistence strategy="localRestartable"/>
<searchAttribute name="age" class="
<searchAttribute name="gender" expression="value.getGender()"/>
The following example shows how to programmatically create the cache configuration with search attributes.
Configuration cacheManagerConfig = new Configuration();
CacheConfiguration cacheConfig = new CacheConfiguration("myCache", 0).eternal(true);
Searchable searchable = new Searchable();
// Create attributes to use in queries.
searchable.addSearchAttribute(new SearchAttribute().name("age"));
// Use an expression for accessing values.
searchable.addSearchAttribute(new SearchAttribute()
searchable.addSearchAttribute(new SearchAttribute()
searchable.addSearchAttribute(new SearchAttribute()
cacheManager = new CacheManager(cacheManagerConfig);
cacheManager.addCache(new Cache(cacheConfig));
Ehcache myCache = cacheManager.getEhcache("myCache");
// Now create the attributes and queries, then execute.
To learn more about the Search API, see the* packages in the Ehcache Javadoc.
Copyright © 2010-2015 Software AG, Darmstadt, Germany.

Product Logo |   Feedback