Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
EhCache Json document search extractor
import net.sf.ehcache.Element;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* Given a json document like the one below
* <pre>
* {"id":"0","terms":"cube,brown","products":"soccer ball","updateTime":"20140901"}
* </pre>
* & a cache like the one below, JsonExtractor will <strong>extract the json attributes </strong> and provide them to EhCache for indexing
* <pre> {@code
* <cache name="jsonCache" maxEntriesLocalHeap="1000" maxBytesLocalOffHeap="50m">
* <searchable keys="false" values="false">
* <searchAttribute name="terms" class=""/>
* <searchAttribute name="updateTime" class=""/>
* <searchAttribute name="products" class=""/>
* </searchable>
* </cache>
* }
* <br/>
* TODO: configurable data type through properties ( right now it returns string), test with path expression such as node.subnode.subnode
* </pre>
* Created by vinay on 10/8/14.
public class JsonExtractor implements AttributeExtractor {
private static final Logger LOG = LoggerFactory.getLogger(JsonExtractor.class);
private static final long serialVersionUID = 1L;
transient ObjectMapper mapper = new ObjectMapper();
public Object attributeFor(Element element, String attribute) throws AttributeExtractorException {
LOG.debug("Extracting attributes for element with key[{}] value[{}] and attribute[{}]",
element.getObjectKey(), element.getObjectValue(), attribute);
String json = (String) element.getObjectValue();
ObjectNode root = null;
try {
root = (ObjectNode) mapper.readTree(json);
} catch (IOException e) {
throw new AttributeExtractorException(e.getMessage());
JsonNode keyNode = root.get(attribute);
if (keyNode != null) {
LOG.debug("added index for {} for attribute {}", keyNode.asText(), attribute);
return keyNode.asText();
} else
return null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment