Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
EhCache Json document search extractor
package org.terracotta.demo.search;
import net.sf.ehcache.Element;
import net.sf.ehcache.search.attribute.AttributeExtractor;
import net.sf.ehcache.search.attribute.AttributeExtractorException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* 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="org.terracotta.demo.search.JsonExtractor"/>
* <searchAttribute name="updateTime" class="org.terracotta.demo.search.JsonExtractor"/>
* <searchAttribute name="products" class="org.terracotta.demo.search.JsonExtractor"/>
* </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();
@Override
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) {
e.printStackTrace();
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