com.scaleset.search.es.AbstractSearchMapping Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of scaleset-search Show documentation
Show all versions of scaleset-search Show documentation
Java object model for representing query requests in REST protocols.
package com.scaleset.search.es;
import java.util.List;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.scaleset.geo.geojson.GeoJsonModule;
import com.scaleset.search.Query;
public abstract class AbstractSearchMapping implements SearchMapping {
private ObjectMapper objectMapper = new ObjectMapper().registerModule(new GeoJsonModule());
private JavaType javaType;
private String[] indices;
private String[] defaultTypes;
private JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
public AbstractSearchMapping(Class extends T> type, String defaultIndex, String... defaultTypes) {
this.javaType = objectMapper.getTypeFactory().constructType(type);
this.defaultTypes = defaultTypes;
this.indices = new String[] { defaultIndex };
}
public AbstractSearchMapping(Class extends T> type, String[] indices, String... defaultTypes) {
this.javaType = objectMapper.getTypeFactory().constructType(type);
this.defaultTypes = defaultTypes;
this.indices = indices;
}
public AbstractSearchMapping(TypeReference typeReference, String defaultIndex, String... defaultTypes) {
this.javaType = objectMapper.getTypeFactory().constructType(typeReference);
this.defaultTypes = defaultTypes;
this.indices = new String[] { defaultIndex };
}
public AbstractSearchMapping(TypeReference typeReference, String[] indices, String... defaultTypes) {
this.javaType = objectMapper.getTypeFactory().constructType(typeReference);
this.defaultTypes = defaultTypes;
this.indices = indices;
}
public T fromDocument(String id, String doc) throws Exception {
T obj = objectMapper.readValue(doc, javaType);
return obj;
}
public T fromSearchHit(SearchHit searchHit) {
ObjectNode json = nodeFactory.objectNode();
for (SearchHitField field : searchHit.fields().values()) {
putField(json, field);
}
T result = objectMapper.convertValue(json, javaType);
return result;
}
void putField(ObjectNode json, SearchHitField field) {
String fieldName = field.getName();
String[] nameParts = fieldName.split("\\.");
String property = nameParts[nameParts.length - 1];
ObjectNode obj = json;
for (int i = 0; i < nameParts.length - 1; ++i) {
String part = nameParts[i];
obj = obj.with(part);
}
List