DATAES-211 - updated to ES-2.2, test fixes round 1

This commit is contained in:
Artur Konczak 2016-02-10 13:40:14 +00:00 committed by Mohsin Husen
parent a853ca359a
commit 8963123ffe
70 changed files with 701 additions and 496 deletions

33
pom.xml
View File

@ -23,7 +23,7 @@
<commonscollections>3.2.1</commonscollections> <commonscollections>3.2.1</commonscollections>
<commonslang>2.6</commonslang> <commonslang>2.6</commonslang>
<elasticsearch>1.7.3</elasticsearch> <elasticsearch>2.2.0</elasticsearch>
<springdata.commons>1.12.0.BUILD-SNAPSHOT</springdata.commons> <springdata.commons>1.12.0.BUILD-SNAPSHOT</springdata.commons>
</properties> </properties>
@ -108,12 +108,12 @@
<version>${spring}</version> <version>${spring}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <!--<dependency>-->
<groupId>org.apache.openwebbeans.test</groupId> <!--<groupId>org.apache.openwebbeans.test</groupId>-->
<artifactId>cditest-owb</artifactId> <!--<artifactId>cditest-owb</artifactId>-->
<version>${webbeans}</version> <!--<version>${webbeans}</version>-->
<scope>test</scope> <!--<scope>test</scope>-->
</dependency> <!--</dependency>-->
<dependency> <dependency>
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId> <artifactId>servlet-api</artifactId>
@ -128,12 +128,19 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <!--<dependency>-->
<groupId>org.codehaus.groovy</groupId> <!--<groupId>org.codehaus.groovy</groupId>-->
<artifactId>groovy-all</artifactId> <!--<artifactId>groovy-all</artifactId>-->
<version>2.3.5</version> <!--<version>2.4.4</version>-->
<scope>test</scope> <!--<scope>test</scope>-->
</dependency> <!--</dependency>-->
<!--<dependency>-->
<!--<groupId>org.elasticsearch.module</groupId>-->
<!--<artifactId>lang-groovy</artifactId>-->
<!--<version>${elasticsearch}</version>-->
<!--&lt;!&ndash;<scope>test</scope>&ndash;&gt;-->
<!--</dependency>-->
</dependencies> </dependencies>

View File

@ -18,13 +18,11 @@ package org.springframework.data.elasticsearch.client;
import static org.elasticsearch.node.NodeBuilder.*; import static org.elasticsearch.node.NodeBuilder.*;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Paths;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.io.stream.InputStreamStreamInput;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -48,6 +46,7 @@ public class NodeClientFactoryBean implements FactoryBean<NodeClient>, Initializ
private String clusterName; private String clusterName;
private NodeClient nodeClient; private NodeClient nodeClient;
private String pathData; private String pathData;
private String pathHome;
private String pathConfiguration; private String pathConfiguration;
NodeClientFactoryBean() { NodeClientFactoryBean() {
@ -74,24 +73,23 @@ public class NodeClientFactoryBean implements FactoryBean<NodeClient>, Initializ
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder() nodeClient = (NodeClient) nodeBuilder().settings(Settings.builder().put(loadConfig())
.put(loadConfig())
.put("http.enabled", String.valueOf(this.enableHttp)) .put("http.enabled", String.valueOf(this.enableHttp))
.put("path.data", this.pathData); .put("path.home", this.pathHome)
.put("path.data", this.pathData))
nodeClient = (NodeClient) nodeBuilder().settings(settings).clusterName(this.clusterName).local(this.local).node() .clusterName(this.clusterName).local(this.local).node()
.client(); .client();
} }
private Settings loadConfig() { private Settings loadConfig() {
if (StringUtils.isNotBlank(pathConfiguration)) { if (StringUtils.isNotBlank(pathConfiguration)) {
try { try {
return ImmutableSettings.builder().loadFromUrl(new ClassPathResource(pathConfiguration).getURL()).build(); return Settings.builder().loadFromPath(Paths.get(new ClassPathResource(pathConfiguration).getURI())).build();
} catch (IOException e) { } catch (IOException e) {
logger.error(String.format("Unable to read node configuration from file [%s]", pathConfiguration), e); logger.error(String.format("Unable to read node configuration from file [%s]", pathConfiguration), e);
} }
} }
return ImmutableSettings.builder().build(); return Settings.builder().build();
} }
public void setLocal(boolean local) { public void setLocal(boolean local) {
@ -110,6 +108,10 @@ public class NodeClientFactoryBean implements FactoryBean<NodeClient>, Initializ
this.pathData = pathData; this.pathData = pathData;
} }
public void setPathHome(String pathHome) {
this.pathHome = pathHome;
}
public void setPathConfiguration(String configuration) { public void setPathConfiguration(String configuration) {
this.pathConfiguration = configuration; this.pathConfiguration = configuration;
} }

View File

@ -16,8 +16,8 @@
package org.springframework.data.elasticsearch.client; package org.springframework.data.elasticsearch.client;
import static org.apache.commons.lang.StringUtils.*; import static org.apache.commons.lang.StringUtils.*;
import static org.elasticsearch.common.settings.ImmutableSettings.*;
import java.net.InetAddress;
import java.util.Properties; import java.util.Properties;
import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.client.transport.TransportClient;
@ -86,7 +86,7 @@ public class TransportClientFactoryBean implements FactoryBean<TransportClient>,
} }
protected void buildClient() throws Exception { protected void buildClient() throws Exception {
client = new TransportClient(settings()); client = TransportClient.builder().settings(settings()).build();
Assert.hasText(clusterNodes, "[Assertion failed] clusterNodes settings missing."); Assert.hasText(clusterNodes, "[Assertion failed] clusterNodes settings missing.");
for (String clusterNode : split(clusterNodes, COMMA)) { for (String clusterNode : split(clusterNodes, COMMA)) {
String hostName = substringBefore(clusterNode, COLON); String hostName = substringBefore(clusterNode, COLON);
@ -94,16 +94,16 @@ public class TransportClientFactoryBean implements FactoryBean<TransportClient>,
Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'"); Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'");
Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'"); Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'");
logger.info("adding transport node : " + clusterNode); logger.info("adding transport node : " + clusterNode);
client.addTransportAddress(new InetSocketTransportAddress(hostName, Integer.valueOf(port))); client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(hostName), Integer.valueOf(port)));
} }
client.connectedNodes(); client.connectedNodes();
} }
private Settings settings() { private Settings settings() {
if (properties != null) { if (properties != null) {
return settingsBuilder().put(properties).build(); return Settings.builder().put(properties).build();
} }
return settingsBuilder() return Settings.builder()
.put("cluster.name", clusterName) .put("cluster.name", clusterName)
.put("client.transport.sniff", clientTransportSniff) .put("client.transport.sniff", clientTransportSniff)
.put("client.transport.ignore_cluster_name", clientIgnoreClusterName) .put("client.transport.ignore_cluster_name", clientIgnoreClusterName)

View File

@ -44,6 +44,7 @@ public class NodeClientBeanDefinitionParser extends AbstractBeanDefinitionParser
builder.addPropertyValue("clusterName", element.getAttribute("cluster-name")); builder.addPropertyValue("clusterName", element.getAttribute("cluster-name"));
builder.addPropertyValue("enableHttp", Boolean.valueOf(element.getAttribute("http-enabled"))); builder.addPropertyValue("enableHttp", Boolean.valueOf(element.getAttribute("http-enabled")));
builder.addPropertyValue("pathData", element.getAttribute("path-data")); builder.addPropertyValue("pathData", element.getAttribute("path-data"));
builder.addPropertyValue("pathHome", element.getAttribute("path-home"));
builder.addPropertyValue("pathConfiguration", element.getAttribute("path-configuration")); builder.addPropertyValue("pathConfiguration", element.getAttribute("path-configuration"));
} }

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.core; package org.springframework.data.elasticsearch.core;
import static org.elasticsearch.index.query.FilterBuilders.*;
import static org.springframework.data.elasticsearch.core.query.Criteria.*; import static org.springframework.data.elasticsearch.core.query.Criteria.*;
import java.util.Iterator; import java.util.Iterator;
@ -23,9 +22,8 @@ import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.index.query.GeoBoundingBoxFilterBuilder; import org.elasticsearch.index.query.*;
import org.elasticsearch.index.query.GeoDistanceFilterBuilder;
import org.springframework.data.elasticsearch.core.geo.GeoBox; import org.springframework.data.elasticsearch.core.geo.GeoBox;
import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.Criteria; import org.springframework.data.elasticsearch.core.query.Criteria;
@ -43,20 +41,23 @@ import org.springframework.util.Assert;
class CriteriaFilterProcessor { class CriteriaFilterProcessor {
FilterBuilder createFilterFromCriteria(Criteria criteria) { QueryBuilder createFilterFromCriteria(Criteria criteria) {
List<FilterBuilder> fbList = new LinkedList<FilterBuilder>(); List<QueryBuilder> fbList = new LinkedList<QueryBuilder>();
FilterBuilder filter = null; QueryBuilder filter = null;
ListIterator<Criteria> chainIterator = criteria.getCriteriaChain().listIterator(); ListIterator<Criteria> chainIterator = criteria.getCriteriaChain().listIterator();
while (chainIterator.hasNext()) { while (chainIterator.hasNext()) {
FilterBuilder fb = null; QueryBuilder fb = null;
Criteria chainedCriteria = chainIterator.next(); Criteria chainedCriteria = chainIterator.next();
if (chainedCriteria.isOr()) { if (chainedCriteria.isOr()) {
fb = orFilter(createFilterFragmentForCriteria(chainedCriteria).toArray(new FilterBuilder[]{})); fb = QueryBuilders.boolQuery();
for(QueryBuilder f: createFilterFragmentForCriteria(chainedCriteria)){
((BoolQueryBuilder)fb).should(f);
}
fbList.add(fb); fbList.add(fb);
} else if (chainedCriteria.isNegating()) { } else if (chainedCriteria.isNegating()) {
List<FilterBuilder> negationFilters = buildNegationFilter(criteria.getField().getName(), criteria.getFilterCriteriaEntries().iterator()); List<QueryBuilder> negationFilters = buildNegationFilter(criteria.getField().getName(), criteria.getFilterCriteriaEntries().iterator());
if (!negationFilters.isEmpty()) { if (!negationFilters.isEmpty()) {
fbList.addAll(negationFilters); fbList.addAll(negationFilters);
@ -70,21 +71,23 @@ class CriteriaFilterProcessor {
if (fbList.size() == 1) { if (fbList.size() == 1) {
filter = fbList.get(0); filter = fbList.get(0);
} else { } else {
filter = andFilter(fbList.toArray(new FilterBuilder[]{})); filter = QueryBuilders.boolQuery();
for(QueryBuilder f: fbList) {
((BoolQueryBuilder)filter).must(f);
}
} }
} }
return filter; return filter;
} }
private List<FilterBuilder> createFilterFragmentForCriteria(Criteria chainedCriteria) { private List<QueryBuilder> createFilterFragmentForCriteria(Criteria chainedCriteria) {
Iterator<Criteria.CriteriaEntry> it = chainedCriteria.getFilterCriteriaEntries().iterator(); Iterator<Criteria.CriteriaEntry> it = chainedCriteria.getFilterCriteriaEntries().iterator();
List<FilterBuilder> filterList = new LinkedList<FilterBuilder>(); List<QueryBuilder> filterList = new LinkedList<QueryBuilder>();
String fieldName = chainedCriteria.getField().getName(); String fieldName = chainedCriteria.getField().getName();
Assert.notNull(fieldName, "Unknown field"); Assert.notNull(fieldName, "Unknown field");
FilterBuilder filter = null; QueryBuilder filter = null;
while (it.hasNext()) { while (it.hasNext()) {
Criteria.CriteriaEntry entry = it.next(); Criteria.CriteriaEntry entry = it.next();
@ -96,15 +99,15 @@ class CriteriaFilterProcessor {
} }
private FilterBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) { private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) {
if (value == null) { if (value == null) {
return null; return null;
} }
FilterBuilder filter = null; QueryBuilder filter = null;
switch (key) { switch (key) {
case WITHIN: { case WITHIN: {
filter = geoDistanceFilter(fieldName); filter = QueryBuilders.geoDistanceRangeQuery(fieldName);
Assert.isTrue(value instanceof Object[], "Value of a geo distance filter should be an array of two values."); Assert.isTrue(value instanceof Object[], "Value of a geo distance filter should be an array of two values.");
Object[] valArray = (Object[]) value; Object[] valArray = (Object[]) value;
@ -123,17 +126,17 @@ class CriteriaFilterProcessor {
if (valArray[0] instanceof GeoPoint) { if (valArray[0] instanceof GeoPoint) {
GeoPoint loc = (GeoPoint) valArray[0]; GeoPoint loc = (GeoPoint) valArray[0];
((GeoDistanceFilterBuilder) filter).lat(loc.getLat()).lon(loc.getLon()).distance(dist.toString()); ((GeoDistanceRangeQueryBuilder) filter).lat(loc.getLat()).lon(loc.getLon()).geoDistance(GeoDistance.fromString(dist.toString()));
} else if (valArray[0] instanceof Point) { } else if (valArray[0] instanceof Point) {
GeoPoint loc = GeoPoint.fromPoint((Point) valArray[0]); GeoPoint loc = GeoPoint.fromPoint((Point) valArray[0]);
((GeoDistanceFilterBuilder) filter).lat(loc.getLat()).lon(loc.getLon()).distance(dist.toString()); ((GeoDistanceRangeQueryBuilder) filter).lat(loc.getLat()).lon(loc.getLon()).geoDistance(GeoDistance.fromString(dist.toString()));
} else { } else {
String loc = (String) valArray[0]; String loc = (String) valArray[0];
if (loc.contains(",")) { if (loc.contains(",")) {
String c[] = loc.split(","); String c[] = loc.split(",");
((GeoDistanceFilterBuilder) filter).lat(Double.parseDouble(c[0])).lon(Double.parseDouble(c[1])).distance(dist.toString()); ((GeoDistanceRangeQueryBuilder) filter).lat(Double.parseDouble(c[0])).lon(Double.parseDouble(c[1])).geoDistance(GeoDistance.fromString(dist.toString()));
} else { } else {
((GeoDistanceFilterBuilder) filter).geohash(loc).distance(dist.toString()); ((GeoDistanceRangeQueryBuilder) filter).geohash(loc).geoDistance(GeoDistance.fromString(dist.toString()));
} }
} }
@ -141,7 +144,7 @@ class CriteriaFilterProcessor {
} }
case BBOX: { case BBOX: {
filter = geoBoundingBoxFilter(fieldName); filter = QueryBuilders.geoBoundingBoxQuery(fieldName);
Assert.isTrue(value instanceof Object[], "Value of a boundedBy filter should be an array of one or two values."); Assert.isTrue(value instanceof Object[], "Value of a boundedBy filter should be an array of one or two values.");
Object[] valArray = (Object[]) value; Object[] valArray = (Object[]) value;
@ -149,11 +152,11 @@ class CriteriaFilterProcessor {
if (valArray.length == 1) { if (valArray.length == 1) {
//GeoEnvelop //GeoEnvelop
oneParameterBBox((GeoBoundingBoxFilterBuilder) filter, valArray[0]); oneParameterBBox((GeoBoundingBoxQueryBuilder) filter, valArray[0]);
} else if (valArray.length == 2) { } else if (valArray.length == 2) {
//2x GeoPoint //2x GeoPoint
//2x String //2x String
twoParameterBBox((GeoBoundingBoxFilterBuilder) filter, valArray); twoParameterBBox((GeoBoundingBoxQueryBuilder) filter, valArray);
} else { } else {
//error //error
Assert.isTrue(false, "Geo distance filter takes a 1-elements array(GeoBox) or 2-elements array(GeoPoints or Strings(format lat,lon or geohash))."); Assert.isTrue(false, "Geo distance filter takes a 1-elements array(GeoBox) or 2-elements array(GeoPoints or Strings(format lat,lon or geohash)).");
@ -188,7 +191,7 @@ class CriteriaFilterProcessor {
} }
} }
private void oneParameterBBox(GeoBoundingBoxFilterBuilder filter, Object value) { private void oneParameterBBox(GeoBoundingBoxQueryBuilder filter, Object value) {
Assert.isTrue(value instanceof GeoBox || value instanceof Box, "single-element of boundedBy filter must be type of GeoBox or Box"); Assert.isTrue(value instanceof GeoBox || value instanceof Box, "single-element of boundedBy filter must be type of GeoBox or Box");
GeoBox geoBBox; GeoBox geoBBox;
@ -212,7 +215,7 @@ class CriteriaFilterProcessor {
return true; return true;
} }
private void twoParameterBBox(GeoBoundingBoxFilterBuilder filter, Object[] values) { private void twoParameterBBox(GeoBoundingBoxQueryBuilder filter, Object[] values) {
Assert.isTrue(isType(values, GeoPoint.class) || isType(values, String.class), " both elements of boundedBy filter must be type of GeoPoint or String(format lat,lon or geohash)"); Assert.isTrue(isType(values, GeoPoint.class) || isType(values, String.class), " both elements of boundedBy filter must be type of GeoPoint or String(format lat,lon or geohash)");
if (values[0] instanceof GeoPoint) { if (values[0] instanceof GeoPoint) {
GeoPoint topLeft = (GeoPoint) values[0]; GeoPoint topLeft = (GeoPoint) values[0];
@ -227,12 +230,12 @@ class CriteriaFilterProcessor {
} }
} }
private List<FilterBuilder> buildNegationFilter(String fieldName, Iterator<Criteria.CriteriaEntry> it) { private List<QueryBuilder> buildNegationFilter(String fieldName, Iterator<Criteria.CriteriaEntry> it) {
List<FilterBuilder> notFilterList = new LinkedList<FilterBuilder>(); List<QueryBuilder> notFilterList = new LinkedList<QueryBuilder>();
while (it.hasNext()) { while (it.hasNext()) {
Criteria.CriteriaEntry criteriaEntry = it.next(); Criteria.CriteriaEntry criteriaEntry = it.next();
FilterBuilder notFilter = notFilter(processCriteriaEntry(criteriaEntry.getKey(), criteriaEntry.getValue(), fieldName)); QueryBuilder notFilter = QueryBuilders.boolQuery().mustNot(processCriteriaEntry(criteriaEntry.getKey(), criteriaEntry.getValue(), fieldName));
notFilterList.add(notFilter); notFilterList.add(notFilter);
} }

View File

@ -148,19 +148,19 @@ class CriteriaQueryProcessor {
switch (key) { switch (key) {
case EQUALS: case EQUALS:
query = queryString(searchText).field(fieldName).defaultOperator(QueryStringQueryBuilder.Operator.AND); query = queryStringQuery(searchText).field(fieldName).defaultOperator(QueryStringQueryBuilder.Operator.AND);
break; break;
case CONTAINS: case CONTAINS:
query = queryString("*" + searchText + "*").field(fieldName).analyzeWildcard(true); query = queryStringQuery("*" + searchText + "*").field(fieldName).analyzeWildcard(true);
break; break;
case STARTS_WITH: case STARTS_WITH:
query = queryString(searchText + "*").field(fieldName).analyzeWildcard(true); query = queryStringQuery(searchText + "*").field(fieldName).analyzeWildcard(true);
break; break;
case ENDS_WITH: case ENDS_WITH:
query = queryString("*" + searchText).field(fieldName).analyzeWildcard(true); query = queryStringQuery("*" + searchText).field(fieldName).analyzeWildcard(true);
break; break;
case EXPRESSION: case EXPRESSION:
query = queryString(searchText).field(fieldName); query = queryStringQuery(searchText).field(fieldName);
break; break;
case LESS_EQUAL: case LESS_EQUAL:
query = rangeQuery(fieldName).lte(value); query = rangeQuery(fieldName).lte(value);
@ -185,14 +185,14 @@ class CriteriaQueryProcessor {
query = boolQuery(); query = boolQuery();
collection = (Iterable<Object>) value; collection = (Iterable<Object>) value;
for (Object item : collection) { for (Object item : collection) {
((BoolQueryBuilder) query).should(queryString(item.toString()).field(fieldName)); ((BoolQueryBuilder) query).should(queryStringQuery(item.toString()).field(fieldName));
} }
break; break;
case NOT_IN: case NOT_IN:
query = boolQuery(); query = boolQuery();
collection = (Iterable<Object>) value; collection = (Iterable<Object>) value;
for (Object item : collection) { for (Object item : collection) {
((BoolQueryBuilder) query).mustNot(queryString(item.toString()).field(fieldName)); ((BoolQueryBuilder) query).mustNot(queryStringQuery(item.toString()).field(fieldName));
} }
break; break;
} }

View File

@ -25,23 +25,20 @@ import java.util.Collection;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.base.Strings; import com.fasterxml.jackson.core.JsonEncoding;
import org.elasticsearch.common.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonFactory;
import org.elasticsearch.common.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator;
import org.elasticsearch.common.jackson.core.JsonGenerator;
import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.facet.Facet;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.ScriptedField; import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.facet.DefaultFacetMapper;
import org.springframework.data.elasticsearch.core.facet.FacetResult;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.PersistentProperty;
@ -81,7 +78,7 @@ public class DefaultResultMapper extends AbstractResultMapper {
for (SearchHit hit : response.getHits()) { for (SearchHit hit : response.getHits()) {
if (hit != null) { if (hit != null) {
T result = null; T result = null;
if (!Strings.isNullOrEmpty(hit.sourceAsString())) { if (StringUtils.isNotBlank(hit.sourceAsString())) {
result = mapEntity(hit.sourceAsString(), clazz); result = mapEntity(hit.sourceAsString(), clazz);
} else { } else {
result = mapEntity(hit.getFields().values(), clazz); result = mapEntity(hit.getFields().values(), clazz);
@ -91,7 +88,8 @@ public class DefaultResultMapper extends AbstractResultMapper {
results.add(result); results.add(result);
} }
} }
List<FacetResult> facets = new ArrayList<FacetResult>(); //TODO: ako facets !!!
/* List<FacetResult> facets = new ArrayList<FacetResult>();
if (response.getFacets() != null) { if (response.getFacets() != null) {
for (Facet facet : response.getFacets()) { for (Facet facet : response.getFacets()) {
FacetResult facetResult = DefaultFacetMapper.parse(facet); FacetResult facetResult = DefaultFacetMapper.parse(facet);
@ -99,9 +97,8 @@ public class DefaultResultMapper extends AbstractResultMapper {
facets.add(facetResult); facets.add(facetResult);
} }
} }
} }*/
return new FacetedPageImpl<T>(results, pageable, totalHits, null );
return new FacetedPageImpl<T>(results, pageable, totalHits, facets);
} }
private <T> void populateScriptFields(T result, SearchHit hit) { private <T> void populateScriptFields(T result, SearchHit hit) {

View File

@ -437,7 +437,8 @@ public interface ElasticsearchOperations {
* @param index * @param index
* @param type * @param type
*/ */
void deleteType(String index, String type); //TODo: ako remove this
/*void deleteType(String index, String type);*/
/** /**
* check if index is exists * check if index is exists

View File

@ -20,8 +20,8 @@ import static org.apache.commons.lang.StringUtils.*;
import static org.elasticsearch.action.search.SearchType.*; import static org.elasticsearch.action.search.SearchType.*;
import static org.elasticsearch.client.Requests.*; import static org.elasticsearch.client.Requests.*;
import static org.elasticsearch.cluster.metadata.AliasAction.Type.*; import static org.elasticsearch.cluster.metadata.AliasAction.Type.*;
import static org.elasticsearch.common.collect.Sets.*;
import static org.elasticsearch.index.VersionType.*; import static org.elasticsearch.index.VersionType.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.springframework.data.elasticsearch.core.MappingBuilder.*; import static org.springframework.data.elasticsearch.core.MappingBuilder.*;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -35,7 +35,6 @@ import org.elasticsearch.action.ListenableActionFuture;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder; import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.mapping.delete.DeleteMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
@ -48,7 +47,6 @@ import org.elasticsearch.action.get.MultiGetRequest;
import org.elasticsearch.action.get.MultiGetRequestBuilder; import org.elasticsearch.action.get.MultiGetRequestBuilder;
import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.mlt.MoreLikeThisRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.search.SearchType;
@ -59,18 +57,15 @@ import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests; import org.elasticsearch.client.Requests;
import org.elasticsearch.cluster.metadata.AliasAction; import org.elasticsearch.cluster.metadata.AliasAction;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.collect.Maps;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.MoreLikeThisQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.script.Script;
import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.facet.FacetBuilder;
import org.elasticsearch.search.highlight.HighlightBuilder; import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder; import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.search.sort.SortOrder;
@ -82,6 +77,8 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
@ -89,7 +86,6 @@ import org.springframework.data.elasticsearch.annotations.Mapping;
import org.springframework.data.elasticsearch.annotations.Setting; import org.springframework.data.elasticsearch.annotations.Setting;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter; import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.core.query.*; import org.springframework.data.elasticsearch.core.query.*;
@ -307,7 +303,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override @Override
public <T> Page<T> queryForPage(CriteriaQuery criteriaQuery, Class<T> clazz) { public <T> Page<T> queryForPage(CriteriaQuery criteriaQuery, Class<T> clazz) {
QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria()); QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria());
FilterBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria()); QueryBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria());
SearchRequestBuilder searchRequestBuilder = prepareSearch(criteriaQuery, clazz); SearchRequestBuilder searchRequestBuilder = prepareSearch(criteriaQuery, clazz);
if (elasticsearchQuery != null) { if (elasticsearchQuery != null) {
@ -418,7 +414,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override @Override
public <T> long count(CriteriaQuery criteriaQuery, Class<T> clazz) { public <T> long count(CriteriaQuery criteriaQuery, Class<T> clazz) {
QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria()); QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria());
FilterBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria()); QueryBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria());
if (elasticsearchFilter == null) { if (elasticsearchFilter == null) {
return doCount(prepareCount(criteriaQuery, clazz), elasticsearchQuery); return doCount(prepareCount(criteriaQuery, clazz), elasticsearchQuery);
@ -431,7 +427,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override @Override
public <T> long count(SearchQuery searchQuery, Class<T> clazz) { public <T> long count(SearchQuery searchQuery, Class<T> clazz) {
QueryBuilder elasticsearchQuery = searchQuery.getQuery(); QueryBuilder elasticsearchQuery = searchQuery.getQuery();
FilterBuilder elasticsearchFilter = searchQuery.getFilter(); QueryBuilder elasticsearchFilter = searchQuery.getFilter();
if (elasticsearchFilter == null) { if (elasticsearchFilter == null) {
return doCount(prepareCount(searchQuery, clazz), elasticsearchQuery); return doCount(prepareCount(searchQuery, clazz), elasticsearchQuery);
@ -458,7 +454,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
return countRequestBuilder.execute().actionGet().getCount(); return countRequestBuilder.execute().actionGet().getCount();
} }
private long doCount(SearchRequestBuilder searchRequestBuilder, QueryBuilder elasticsearchQuery, FilterBuilder elasticsearchFilter) { private long doCount(SearchRequestBuilder searchRequestBuilder, QueryBuilder elasticsearchQuery, QueryBuilder elasticsearchFilter) {
if (elasticsearchQuery != null) { if (elasticsearchQuery != null) {
searchRequestBuilder.setQuery(elasticsearchQuery); searchRequestBuilder.setQuery(elasticsearchQuery);
} else { } else {
@ -556,10 +552,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
} }
} else { } else {
// or script // or script
updateRequestBuilder updateRequestBuilder.setScript(query.getUpdateRequest().script());
.setScript(query.getUpdateRequest().script(), query.getUpdateRequest().scriptType())
.setScriptParams(query.getUpdateRequest().scriptParams())
.setScriptLang(query.getUpdateRequest().scriptLang());
} }
return updateRequestBuilder; return updateRequestBuilder;
@ -618,7 +611,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override @Override
public boolean typeExists(String index, String type) { public boolean typeExists(String index, String type) {
return client.admin().cluster().prepareState().execute().actionGet() return client.admin().cluster().prepareState().execute().actionGet()
.getState().metaData().index(index).mappings().containsKey(type); .getState().metaData().index(index).getMappings().containsKey(type);
} }
@Override @Override
@ -635,15 +628,6 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
return false; return false;
} }
@Override
public void deleteType(String index, String type) {
ImmutableOpenMap<String, MappingMetaData> mappings = client.admin().cluster().prepareState().execute().actionGet()
.getState().metaData().index(index).mappings();
if (mappings.containsKey(type)) {
client.admin().indices().deleteMapping(new DeleteMappingRequest(index).types(type)).actionGet();
}
}
@Override @Override
public String delete(String indexName, String type, String id) { public String delete(String indexName, String type, String id) {
return client.prepareDelete(indexName, type, id).execute().actionGet().getId(); return client.prepareDelete(indexName, type, id).execute().actionGet().getId();
@ -657,17 +641,59 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override @Override
public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) { public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) {
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
client.prepareDeleteByQuery(persistentEntity.getIndexName()).setTypes(persistentEntity.getIndexType()) String iName = deleteQuery.getIndex();
.setQuery(deleteQuery.getQuery()).execute().actionGet(); String tName = deleteQuery.getType();
if(clazz!=null){
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
iName = persistentEntity.getIndexName();
tName =persistentEntity.getIndexType();
}
final String indexName = iName;
final String typeName = tName;
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(deleteQuery.getQuery())
.withIndices(indexName)
.withTypes(typeName)
//TOD: ako - check that id is all the time avaialable
//.withFields("_id")
.withPageable(new PageRequest(0, 1000))
.build();
final String scrollId = scan(searchQuery, 10000, true);
final BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
boolean hasMoreRecords = true;
while (hasMoreRecords) {
final Page<Object> scroll = scroll(scrollId, 10000L, new SearchResultMapper() {
@Override
public <T> FacetedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
boolean hasItems = false;
for (SearchHit searchHit : response.getHits()) {
hasItems = true;
bulkRequestBuilder.add(client.prepareDelete(indexName, typeName, searchHit.getId()));
}
if(hasItems){
return new FacetedPageImpl<T>((List<T>)Arrays.asList(new Object()));
}
return null;
}
});
if (scroll == null) {
hasMoreRecords = false;
}
}
if(bulkRequestBuilder.numberOfActions()>0) {
bulkRequestBuilder.execute().actionGet();
}
} }
@Override @Override
public void delete(DeleteQuery deleteQuery) { public void delete(DeleteQuery deleteQuery) {
Assert.notNull(deleteQuery.getIndex(), "No index defined for Query"); Assert.notNull(deleteQuery.getIndex(), "No index defined for Query");
Assert.notNull(deleteQuery.getType(), "No type define for Query"); Assert.notNull(deleteQuery.getType(), "No type define for Query");
client.prepareDeleteByQuery(deleteQuery.getIndex()).setTypes(deleteQuery.getType()) delete(deleteQuery, null);
.setQuery(deleteQuery.getQuery()).execute().actionGet();
} }
@Override @Override
@ -726,7 +752,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
Assert.notNull(criteriaQuery.getPageable(), "Query.pageable is required for scan & scroll"); Assert.notNull(criteriaQuery.getPageable(), "Query.pageable is required for scan & scroll");
QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria()); QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria());
FilterBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria()); QueryBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria());
if (elasticsearchQuery != null) { if (elasticsearchQuery != null) {
requestBuilder.setQuery(elasticsearchQuery); requestBuilder.setQuery(elasticsearchQuery);
@ -778,7 +804,12 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
Assert.notNull(type, "No 'type' defined for MoreLikeThisQuery"); Assert.notNull(type, "No 'type' defined for MoreLikeThisQuery");
Assert.notNull(query.getId(), "No document id defined for MoreLikeThisQuery"); Assert.notNull(query.getId(), "No document id defined for MoreLikeThisQuery");
MoreLikeThisRequestBuilder requestBuilder = client.prepareMoreLikeThis(indexName, type, query.getId()); final MoreLikeThisQueryBuilder.Item item = new MoreLikeThisQueryBuilder.Item(indexName, type, query.getId());
final NativeSearchQuery build = new NativeSearchQueryBuilder().withQuery(moreLikeThisQuery().addLikeItem(item)).build();
return queryForPage(build,clazz);
//TODO: Mohins - set all other params for moreLikeThis
/* MoreLikeThisRequestBuilder requestBuilder = client.prepareMoreLikeThis(indexName, type, query.getId());
if (query.getPageable() != null) { if (query.getPageable() != null) {
startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize(); startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
@ -827,7 +858,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
} }
SearchResponse response = getSearchResponse(requestBuilder.execute()); SearchResponse response = getSearchResponse(requestBuilder.execute());
return resultsMapper.mapResults(response, clazz, query.getPageable()); return resultsMapper.mapResults(response, clazz, query.getPageable());*/
} }
private SearchResponse doSearch(SearchRequestBuilder searchRequest, SearchQuery searchQuery) { private SearchResponse doSearch(SearchRequestBuilder searchRequest, SearchQuery searchQuery) {
@ -844,10 +875,11 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
if (!searchQuery.getScriptFields().isEmpty()) { if (!searchQuery.getScriptFields().isEmpty()) {
searchRequest.addField("_source"); searchRequest.addField("_source");
for (ScriptField scriptedField : searchQuery.getScriptFields()) { for (ScriptField scriptedField : searchQuery.getScriptFields()) {
searchRequest.addScriptField(scriptedField.fieldName(), scriptedField.script(), scriptedField.params()); searchRequest.addScriptField(scriptedField.fieldName(), scriptedField.script());
} }
} }
/*
if (CollectionUtils.isNotEmpty(searchQuery.getFacets())) { if (CollectionUtils.isNotEmpty(searchQuery.getFacets())) {
for (FacetRequest facetRequest : searchQuery.getFacets()) { for (FacetRequest facetRequest : searchQuery.getFacets()) {
FacetBuilder facet = facetRequest.getFacet(); FacetBuilder facet = facetRequest.getFacet();
@ -857,6 +889,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
searchRequest.addFacet(facet); searchRequest.addFacet(facet);
} }
} }
*/
if (searchQuery.getHighlightFields() != null) { if (searchQuery.getHighlightFields() != null) {
for (HighlightBuilder.Field highlightField : searchQuery.getHighlightFields()) { for (HighlightBuilder.Field highlightField : searchQuery.getHighlightFields()) {
@ -922,7 +955,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
private <T> Map getDefaultSettings(ElasticsearchPersistentEntity<T> persistentEntity) { private <T> Map getDefaultSettings(ElasticsearchPersistentEntity<T> persistentEntity) {
if (persistentEntity.isUseServerConfiguration()) if (persistentEntity.isUseServerConfiguration())
return Maps.newHashMap(); return new HashMap();
return new MapBuilder<String, String>().put("index.number_of_shards", String.valueOf(persistentEntity.getShards())) return new MapBuilder<String, String>().put("index.number_of_shards", String.valueOf(persistentEntity.getShards()))
.put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas())) .put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas()))
@ -1021,14 +1054,14 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override @Override
public void refresh(String indexName, boolean waitForOperation) { public void refresh(String indexName, boolean waitForOperation) {
client.admin().indices().refresh(refreshRequest(indexName).force(waitForOperation)).actionGet(); client.admin().indices().refresh(refreshRequest(indexName)).actionGet();
} }
@Override @Override
public <T> void refresh(Class<T> clazz, boolean waitForOperation) { public <T> void refresh(Class<T> clazz, boolean waitForOperation) {
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
client.admin().indices() client.admin().indices()
.refresh(refreshRequest(persistentEntity.getIndexName()).force(waitForOperation)).actionGet(); .refresh(refreshRequest(persistentEntity.getIndexName())).actionGet();
} }
@Override @Override
@ -1062,8 +1095,10 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
public Set<String> queryForAlias(String indexName) { public Set<String> queryForAlias(String indexName) {
ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest() ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest()
.routingTable(true).nodes(true).indices(indexName); .routingTable(true).nodes(true).indices(indexName);
Iterator<String> iterator = client.admin().cluster().state(clusterStateRequest).actionGet().getState().getMetaData().aliases().keysIt(); //TODO: ako check how to find aliases for index
return newHashSet(iterator); /* Iterator<String> iterator = client.admin().cluster().state(clusterStateRequest).actionGet().getState().getMetaData().aliases().keysIt();
return newHashSet(iterator);*/
return null;
} }
@Override @Override

View File

@ -48,8 +48,10 @@ public class FacetedPageImpl<T> extends PageImpl<T> implements FacetedPage<T> {
public FacetedPageImpl(List<T> content, Pageable pageable, long total, List<FacetResult> facets) { public FacetedPageImpl(List<T> content, Pageable pageable, long total, List<FacetResult> facets) {
super(content, pageable, total); super(content, pageable, total);
this.facets = facets; this.facets = facets;
for (FacetResult facet : facets) { if(facets!=null) {
mapOfFacets.put(facet.getName(), facet); for (FacetResult facet : facets) {
mapOfFacets.put(facet.getName(), facet);
}
} }
} }

View File

@ -25,8 +25,8 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang.math.NumberUtils;
import org.elasticsearch.common.lang3.StringUtils;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.springframework.core.GenericCollectionTypeResolver; import org.springframework.core.GenericCollectionTypeResolver;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
@ -152,9 +152,9 @@ class MappingBuilder {
if (isRootObject && singleField != null && isIdField(field, idFieldName)) { if (isRootObject && singleField != null && isIdField(field, idFieldName)) {
applyDefaultIdFieldMapping(xContentBuilder, field); applyDefaultIdFieldMapping(xContentBuilder, field);
} else if (multiField != null) { } else if (multiField != null) {
addMultiFieldMapping(xContentBuilder, field, multiField); addMultiFieldMapping(xContentBuilder, field, multiField, isNestedOrObjectField(field));
} else if (singleField != null) { } else if (singleField != null) {
addSingleFieldMapping(xContentBuilder, field, singleField); addSingleFieldMapping(xContentBuilder, field, singleField, isNestedOrObjectField(field));
} }
} }
@ -238,9 +238,11 @@ class MappingBuilder {
* @throws IOException * @throws IOException
*/ */
private static void addSingleFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field, private static void addSingleFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field,
Field fieldAnnotation) throws IOException { Field fieldAnnotation, boolean nestedOrObjectField) throws IOException {
xContentBuilder.startObject(field.getName()); xContentBuilder.startObject(field.getName());
xContentBuilder.field(FIELD_STORE, fieldAnnotation.store()); if(!nestedOrObjectField) {
xContentBuilder.field(FIELD_STORE, fieldAnnotation.store());
}
if (FieldType.Auto != fieldAnnotation.type()) { if (FieldType.Auto != fieldAnnotation.type()) {
xContentBuilder.field(FIELD_TYPE, fieldAnnotation.type().name().toLowerCase()); xContentBuilder.field(FIELD_TYPE, fieldAnnotation.type().name().toLowerCase());
if (FieldType.Date == fieldAnnotation.type() && DateFormat.none != fieldAnnotation.format()) { if (FieldType.Date == fieldAnnotation.type() && DateFormat.none != fieldAnnotation.format()) {
@ -268,7 +270,7 @@ class MappingBuilder {
private static void addNestedFieldMapping(XContentBuilder builder, java.lang.reflect.Field field, private static void addNestedFieldMapping(XContentBuilder builder, java.lang.reflect.Field field,
NestedField annotation) throws IOException { NestedField annotation) throws IOException {
builder.startObject(field.getName() + "." + annotation.dotSuffix()); builder.startObject(field.getName() + "." + annotation.dotSuffix());
builder.field(FIELD_STORE, annotation.store()); //builder.field(FIELD_STORE, annotation.store());
if (FieldType.Auto != annotation.type()) { if (FieldType.Auto != annotation.type()) {
builder.field(FIELD_TYPE, annotation.type().name().toLowerCase()); builder.field(FIELD_TYPE, annotation.type().name().toLowerCase());
} }
@ -290,12 +292,12 @@ class MappingBuilder {
* @throws IOException * @throws IOException
*/ */
private static void addMultiFieldMapping(XContentBuilder builder, java.lang.reflect.Field field, private static void addMultiFieldMapping(XContentBuilder builder, java.lang.reflect.Field field,
MultiField annotation) throws IOException { MultiField annotation, boolean nestedOrObjectField) throws IOException {
builder.startObject(field.getName()); builder.startObject(field.getName());
builder.field(FIELD_TYPE, "multi_field"); builder.field(FIELD_TYPE, "multi_field");
builder.startObject("fields"); builder.startObject("fields");
//add standard field //add standard field
addSingleFieldMapping(builder, field, annotation.mainField()); addSingleFieldMapping(builder, field, annotation.mainField(),nestedOrObjectField);
for (NestedField nestedField : annotation.otherFields()) { for (NestedField nestedField : annotation.otherFields()) {
addNestedFieldMapping(builder, field, nestedField); addNestedFieldMapping(builder, field, nestedField);
} }

View File

@ -12,14 +12,17 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet; package org.springframework.data.elasticsearch.core.facet;
import org.springframework.util.Assert; import org.springframework.util.Assert;
*/
/** /**
* @author Artur Konczak * @author Artur Konczak
*/ *//*
public abstract class AbstractFacetRequest implements FacetRequest { public abstract class AbstractFacetRequest implements FacetRequest {
private String name; private String name;
@ -43,3 +46,4 @@ public abstract class AbstractFacetRequest implements FacetRequest {
return applyQueryFilter; return applyQueryFilter;
} }
} }
*/

View File

@ -1,81 +1,81 @@
/* ///*
* Copyright 2014 the original author or authors. // * Copyright 2014 the original author or authors.
* // *
* Licensed under the Apache License, Version 2.0 (the "License"); // * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. // * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at // * You may obtain a copy of the License at
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
*/ // */
package org.springframework.data.elasticsearch.core.facet; //package org.springframework.data.elasticsearch.core.facet;
//
import java.util.ArrayList; //import java.util.ArrayList;
import java.util.List; //import java.util.List;
//
import org.elasticsearch.search.facet.Facet; //import org.elasticsearch.search.facet.Facet;
import org.elasticsearch.search.facet.histogram.HistogramFacet; //import org.elasticsearch.search.facet.histogram.HistogramFacet;
import org.elasticsearch.search.facet.range.RangeFacet; //import org.elasticsearch.search.facet.range.RangeFacet;
import org.elasticsearch.search.facet.statistical.StatisticalFacet; //import org.elasticsearch.search.facet.statistical.StatisticalFacet;
import org.elasticsearch.search.facet.terms.TermsFacet; //import org.elasticsearch.search.facet.terms.TermsFacet;
import org.springframework.data.elasticsearch.core.facet.result.*; //import org.springframework.data.elasticsearch.core.facet.result.*;
//
/** ///**
* @author Artur Konczak // * @author Artur Konczak
* @author Petar Tahchiev // * @author Petar Tahchiev
*/ // */
public class DefaultFacetMapper { //public class DefaultFacetMapper {
//
public static FacetResult parse(Facet facet) { // public static FacetResult parse(Facet facet) {
if (facet instanceof TermsFacet) { // if (facet instanceof TermsFacet) {
return parseTerm((TermsFacet) facet); // return parseTerm((TermsFacet) facet);
} // }
//
if (facet instanceof RangeFacet) { // if (facet instanceof RangeFacet) {
return parseRange((RangeFacet) facet); // return parseRange((RangeFacet) facet);
} // }
//
if (facet instanceof StatisticalFacet) { // if (facet instanceof StatisticalFacet) {
return parseStatistical((StatisticalFacet) facet); // return parseStatistical((StatisticalFacet) facet);
} // }
//
if (facet instanceof HistogramFacet) { // if (facet instanceof HistogramFacet) {
return parseHistogram((HistogramFacet) facet); // return parseHistogram((HistogramFacet) facet);
} // }
//
return null; // return null;
} // }
//
private static FacetResult parseTerm(TermsFacet facet) { // private static FacetResult parseTerm(TermsFacet facet) {
List<Term> entries = new ArrayList<Term>(); // List<Term> entries = new ArrayList<Term>();
for (TermsFacet.Entry entry : facet.getEntries()) { // for (TermsFacet.Entry entry : facet.getEntries()) {
entries.add(new Term(entry.getTerm().toString(), entry.getCount())); // entries.add(new Term(entry.getTerm().toString(), entry.getCount()));
} // }
return new TermResult(facet.getName(), entries, facet.getTotalCount(), facet.getOtherCount(), facet.getMissingCount()); // return new TermResult(facet.getName(), entries, facet.getTotalCount(), facet.getOtherCount(), facet.getMissingCount());
} // }
//
private static FacetResult parseRange(RangeFacet facet) { // private static FacetResult parseRange(RangeFacet facet) {
List<Range> entries = new ArrayList<Range>(); // List<Range> entries = new ArrayList<Range>();
for (RangeFacet.Entry entry : facet.getEntries()) { // for (RangeFacet.Entry entry : facet.getEntries()) {
entries.add(new Range(entry.getFrom() == Double.NEGATIVE_INFINITY ? null : entry.getFrom(), entry.getTo() == Double.POSITIVE_INFINITY ? null : entry.getTo(), entry.getCount(), entry.getTotal(), entry.getTotalCount(), entry.getMin(), entry.getMax())); // entries.add(new Range(entry.getFrom() == Double.NEGATIVE_INFINITY ? null : entry.getFrom(), entry.getTo() == Double.POSITIVE_INFINITY ? null : entry.getTo(), entry.getCount(), entry.getTotal(), entry.getTotalCount(), entry.getMin(), entry.getMax()));
} // }
return new RangeResult(facet.getName(), entries); // return new RangeResult(facet.getName(), entries);
} // }
//
private static FacetResult parseStatistical(StatisticalFacet facet) { // private static FacetResult parseStatistical(StatisticalFacet facet) {
return new StatisticalResult(facet.getName(), facet.getCount(), facet.getMax(), facet.getMin(), facet.getMean(), facet.getStdDeviation(), facet.getSumOfSquares(), facet.getTotal(), facet.getVariance()); // return new StatisticalResult(facet.getName(), facet.getCount(), facet.getMax(), facet.getMin(), facet.getMean(), facet.getStdDeviation(), facet.getSumOfSquares(), facet.getTotal(), facet.getVariance());
} // }
//
private static FacetResult parseHistogram(HistogramFacet facet) { // private static FacetResult parseHistogram(HistogramFacet facet) {
List<IntervalUnit> entries = new ArrayList<IntervalUnit>(); // List<IntervalUnit> entries = new ArrayList<IntervalUnit>();
for (HistogramFacet.Entry entry : facet.getEntries()) { // for (HistogramFacet.Entry entry : facet.getEntries()) {
entries.add(new IntervalUnit(entry.getKey(), entry.getCount(), entry.getTotalCount(), entry.getTotal(), entry.getMean(), entry.getMin(), entry.getMax())); // entries.add(new IntervalUnit(entry.getKey(), entry.getCount(), entry.getTotalCount(), entry.getTotal(), entry.getMean(), entry.getMin(), entry.getMax()));
} // }
return new HistogramResult(facet.getName(), entries); // return new HistogramResult(facet.getName(), entries);
} // }
} //}

View File

@ -12,14 +12,17 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet; package org.springframework.data.elasticsearch.core.facet;
import org.elasticsearch.search.facet.FacetBuilder; import org.elasticsearch.search.facet.FacetBuilder;
*/
/** /**
* @author Artur Koczak * @author Artur Koczak
*/ *//*
public interface FacetRequest { public interface FacetRequest {
public static final String FIELD_UNTOUCHED = "untouched"; public static final String FIELD_UNTOUCHED = "untouched";
@ -29,3 +32,4 @@ public interface FacetRequest {
boolean applyQueryFilter(); boolean applyQueryFilter();
} }
*/

View File

@ -12,7 +12,8 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet.request; package org.springframework.data.elasticsearch.core.facet.request;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -24,10 +25,12 @@ import org.elasticsearch.search.facet.histogram.HistogramFacetBuilder;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest; import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest;
import org.springframework.util.Assert; import org.springframework.util.Assert;
*/
/** /**
* @author Artur Konczak * @author Artur Konczak
* @author Mohsin Husen * @author Mohsin Husen
*/ *//*
public class HistogramFacetRequest extends AbstractFacetRequest { public class HistogramFacetRequest extends AbstractFacetRequest {
private String field; private String field;
@ -67,3 +70,4 @@ public class HistogramFacetRequest extends AbstractFacetRequest {
return builder; return builder;
} }
} }
*/

View File

@ -12,16 +12,19 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet.request; package org.springframework.data.elasticsearch.core.facet.request;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.springframework.data.elasticsearch.core.facet.FacetRequest; import org.springframework.data.elasticsearch.core.facet.FacetRequest;
*/
/** /**
* @author Artur Konczak * @author Artur Konczak
*/ *//*
public class HistogramFacetRequestBuilder { public class HistogramFacetRequestBuilder {
HistogramFacetRequest result; HistogramFacetRequest result;
@ -54,3 +57,4 @@ public class HistogramFacetRequestBuilder {
return this; return this;
} }
} }
*/

View File

@ -12,16 +12,19 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet.request; package org.springframework.data.elasticsearch.core.facet.request;
import org.elasticsearch.search.facet.FacetBuilder; import org.elasticsearch.search.facet.FacetBuilder;
import org.springframework.data.elasticsearch.core.facet.FacetRequest; import org.springframework.data.elasticsearch.core.facet.FacetRequest;
*/
/** /**
* @author Artur Konczak * @author Artur Konczak
* @author Mohsin Husen * @author Mohsin Husen
*/ *//*
public class NativeFacetRequest implements FacetRequest { public class NativeFacetRequest implements FacetRequest {
private FacetBuilder facet; private FacetBuilder facet;
@ -46,3 +49,4 @@ public class NativeFacetRequest implements FacetRequest {
return applyQueryFilter; return applyQueryFilter;
} }
} }
*/

View File

@ -12,7 +12,8 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet.request; package org.springframework.data.elasticsearch.core.facet.request;
import java.util.ArrayList; import java.util.ArrayList;
@ -25,12 +26,14 @@ import org.elasticsearch.search.facet.range.RangeFacetBuilder;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest; import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest;
import org.springframework.util.Assert; import org.springframework.util.Assert;
*/
/** /**
* Range facet for numeric fields * Range facet for numeric fields
* *
* @author Artur Konczak * @author Artur Konczak
* @author Akos Bordas * @author Akos Bordas
*/ *//*
public class RangeFacetRequest extends AbstractFacetRequest { public class RangeFacetRequest extends AbstractFacetRequest {
private String field; private String field;
@ -130,3 +133,4 @@ public class RangeFacetRequest extends AbstractFacetRequest {
} }
} }
} }
*/

View File

@ -12,16 +12,19 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet.request; package org.springframework.data.elasticsearch.core.facet.request;
import org.springframework.data.elasticsearch.core.facet.FacetRequest; import org.springframework.data.elasticsearch.core.facet.FacetRequest;
*/
/** /**
* Basic range facet * Basic range facet
* *
* @author Artur Konczak * @author Artur Konczak
*/ *//*
public class RangeFacetRequestBuilder { public class RangeFacetRequestBuilder {
RangeFacetRequest result; RangeFacetRequest result;
@ -80,3 +83,4 @@ public class RangeFacetRequestBuilder {
return result; return result;
} }
} }
*/

View File

@ -12,7 +12,8 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet.request; package org.springframework.data.elasticsearch.core.facet.request;
import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ArrayUtils;
@ -23,9 +24,11 @@ import org.elasticsearch.search.facet.statistical.StatisticalFacetBuilder;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest; import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest;
import org.springframework.util.Assert; import org.springframework.util.Assert;
*/
/** /**
* @author Petar Tahchiev * @author Petar Tahchiev
*/ *//*
public class StatisticalFacetRequest extends AbstractFacetRequest { public class StatisticalFacetRequest extends AbstractFacetRequest {
private String field; private String field;
@ -58,3 +61,4 @@ public class StatisticalFacetRequest extends AbstractFacetRequest {
return builder; return builder;
} }
} }
*/

View File

@ -12,14 +12,17 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet.request; package org.springframework.data.elasticsearch.core.facet.request;
import org.springframework.data.elasticsearch.core.facet.FacetRequest; import org.springframework.data.elasticsearch.core.facet.FacetRequest;
*/
/** /**
* @author Petar Tahchiev * @author Petar Tahchiev
*/ *//*
public class StatisticalFacetRequestBuilder { public class StatisticalFacetRequestBuilder {
StatisticalFacetRequest result; StatisticalFacetRequest result;
@ -47,3 +50,4 @@ public class StatisticalFacetRequestBuilder {
return result; return result;
} }
} }
*/

View File

@ -12,7 +12,8 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet.request; package org.springframework.data.elasticsearch.core.facet.request;
import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.ArrayUtils;
@ -24,11 +25,13 @@ import org.elasticsearch.search.facet.terms.TermsFacetBuilder;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest; import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest;
import org.springframework.util.Assert; import org.springframework.util.Assert;
*/
/** /**
* Term facet * Term facet
* *
* @author Artur Konczak * @author Artur Konczak
*/ *//*
public class TermFacetRequest extends AbstractFacetRequest { public class TermFacetRequest extends AbstractFacetRequest {
private String[] fields; private String[] fields;
@ -106,3 +109,4 @@ public class TermFacetRequest extends AbstractFacetRequest {
return builder; return builder;
} }
} }
*/

View File

@ -12,16 +12,19 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet.request; package org.springframework.data.elasticsearch.core.facet.request;
import org.springframework.data.elasticsearch.core.facet.FacetRequest; import org.springframework.data.elasticsearch.core.facet.FacetRequest;
*/
/** /**
* Basic term facet * Basic term facet
* *
* @author Artur Konczak * @author Artur Konczak
*/ *//*
public class TermFacetRequestBuilder { public class TermFacetRequestBuilder {
private TermFacetRequest result; private TermFacetRequest result;
@ -89,3 +92,4 @@ public class TermFacetRequestBuilder {
return result; return result;
} }
} }
*/

View File

@ -17,7 +17,7 @@ package org.springframework.data.elasticsearch.core.query;
import java.util.Map; import java.util.Map;
import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.QueryBuilder;
/** /**
* @author Mohsin Husen * @author Mohsin Husen
@ -26,7 +26,7 @@ public class AliasBuilder {
private String indexName; private String indexName;
private String aliasName; private String aliasName;
private FilterBuilder filterBuilder; private QueryBuilder filterBuilder;
private Map<String, Object> filter; private Map<String, Object> filter;
private String searchRouting; private String searchRouting;
private String indexRouting; private String indexRouting;
@ -42,7 +42,7 @@ public class AliasBuilder {
return this; return this;
} }
public AliasBuilder withFilterBuilder(FilterBuilder filterBuilder) { public AliasBuilder withFilterBuilder(QueryBuilder filterBuilder) {
this.filterBuilder = filterBuilder; this.filterBuilder = filterBuilder;
return this; return this;
} }

View File

@ -17,7 +17,7 @@ package org.springframework.data.elasticsearch.core.query;
import java.util.Map; import java.util.Map;
import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.QueryBuilder;
/** /**
* AliasQuery is useful for creating new alias or deleting existing ones * AliasQuery is useful for creating new alias or deleting existing ones
@ -28,7 +28,7 @@ public class AliasQuery {
private String indexName; private String indexName;
private String aliasName; private String aliasName;
private FilterBuilder filterBuilder; private QueryBuilder filterBuilder;
private Map<String, Object> filter; private Map<String, Object> filter;
private String searchRouting; private String searchRouting;
private String indexRouting; private String indexRouting;
@ -50,11 +50,11 @@ public class AliasQuery {
this.aliasName = aliasName; this.aliasName = aliasName;
} }
public FilterBuilder getFilterBuilder() { public QueryBuilder getFilterBuilder() {
return filterBuilder; return filterBuilder;
} }
public void setFilterBuilder(FilterBuilder filterBuilder) { public void setFilterBuilder(QueryBuilder filterBuilder) {
this.filterBuilder = filterBuilder; this.filterBuilder = filterBuilder;
} }

View File

@ -18,16 +18,12 @@ package org.springframework.data.elasticsearch.core.query;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.highlight.HighlightBuilder; import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder; import org.elasticsearch.search.sort.SortBuilder;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
/** /**
* NativeSearchQuery * NativeSearchQuery
@ -39,10 +35,10 @@ import java.util.List;
public class NativeSearchQuery extends AbstractQuery implements SearchQuery { public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
private QueryBuilder query; private QueryBuilder query;
private FilterBuilder filter; private QueryBuilder filter;
private List<SortBuilder> sorts; private List<SortBuilder> sorts;
private final List<ScriptField> scriptFields = new ArrayList<ScriptField>(); private final List<ScriptField> scriptFields = new ArrayList<ScriptField>();
private List<FacetRequest> facets; /*private List<FacetRequest> facets;*/
private List<AbstractAggregationBuilder> aggregations; private List<AbstractAggregationBuilder> aggregations;
private HighlightBuilder.Field[] highlightFields; private HighlightBuilder.Field[] highlightFields;
private List<IndexBoost> indicesBoost; private List<IndexBoost> indicesBoost;
@ -52,18 +48,18 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
this.query = query; this.query = query;
} }
public NativeSearchQuery(QueryBuilder query, FilterBuilder filter) { public NativeSearchQuery(QueryBuilder query, QueryBuilder filter) {
this.query = query; this.query = query;
this.filter = filter; this.filter = filter;
} }
public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, List<SortBuilder> sorts) { public NativeSearchQuery(QueryBuilder query, QueryBuilder filter, List<SortBuilder> sorts) {
this.query = query; this.query = query;
this.filter = filter; this.filter = filter;
this.sorts = sorts; this.sorts = sorts;
} }
public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, List<SortBuilder> sorts, HighlightBuilder.Field[] highlightFields) { public NativeSearchQuery(QueryBuilder query, QueryBuilder filter, List<SortBuilder> sorts, HighlightBuilder.Field[] highlightFields) {
this.query = query; this.query = query;
this.filter = filter; this.filter = filter;
this.sorts = sorts; this.sorts = sorts;
@ -74,7 +70,7 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
return query; return query;
} }
public FilterBuilder getFilter() { public QueryBuilder getFilter() {
return filter; return filter;
} }
@ -98,7 +94,7 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
scriptFields.addAll(Arrays.asList(scriptField)); scriptFields.addAll(Arrays.asList(scriptField));
} }
public void addFacet(FacetRequest facetRequest) { /* public void addFacet(FacetRequest facetRequest) {
if (facets == null) { if (facets == null) {
facets = new ArrayList<FacetRequest>(); facets = new ArrayList<FacetRequest>();
} }
@ -112,7 +108,7 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
@Override @Override
public List<FacetRequest> getFacets() { public List<FacetRequest> getFacets() {
return facets; return facets;
} }*/
@Override @Override
public List<AbstractAggregationBuilder> getAggregations() { public List<AbstractAggregationBuilder> getAggregations() {

View File

@ -21,13 +21,11 @@ import java.util.List;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.highlight.HighlightBuilder; import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder; import org.elasticsearch.search.sort.SortBuilder;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
/** /**
* NativeSearchQuery * NativeSearchQuery
@ -40,10 +38,10 @@ import org.springframework.data.elasticsearch.core.facet.FacetRequest;
public class NativeSearchQueryBuilder { public class NativeSearchQueryBuilder {
private QueryBuilder queryBuilder; private QueryBuilder queryBuilder;
private FilterBuilder filterBuilder; private QueryBuilder filterBuilder;
private List<ScriptField> scriptFields = new ArrayList<ScriptField>(); private List<ScriptField> scriptFields = new ArrayList<ScriptField>();
private List<SortBuilder> sortBuilders = new ArrayList<SortBuilder>(); private List<SortBuilder> sortBuilders = new ArrayList<SortBuilder>();
private List<FacetRequest> facetRequests = new ArrayList<FacetRequest>(); /*private List<FacetRequest> facetRequests = new ArrayList<FacetRequest>();*/
private List<AbstractAggregationBuilder> aggregationBuilders = new ArrayList<AbstractAggregationBuilder>(); private List<AbstractAggregationBuilder> aggregationBuilders = new ArrayList<AbstractAggregationBuilder>();
private HighlightBuilder.Field[] highlightFields; private HighlightBuilder.Field[] highlightFields;
private Pageable pageable; private Pageable pageable;
@ -61,7 +59,7 @@ public class NativeSearchQueryBuilder {
return this; return this;
} }
public NativeSearchQueryBuilder withFilter(FilterBuilder filterBuilder) { public NativeSearchQueryBuilder withFilter(QueryBuilder filterBuilder) {
this.filterBuilder = filterBuilder; this.filterBuilder = filterBuilder;
return this; return this;
} }
@ -81,10 +79,10 @@ public class NativeSearchQueryBuilder {
return this; return this;
} }
public NativeSearchQueryBuilder withFacet(FacetRequest facetRequest) { /* public NativeSearchQueryBuilder withFacet(FacetRequest facetRequest) {
facetRequests.add(facetRequest); facetRequests.add(facetRequest);
return this; return this;
} }*/
public NativeSearchQueryBuilder withHighlightFields(HighlightBuilder.Field... highlightFields) { public NativeSearchQueryBuilder withHighlightFields(HighlightBuilder.Field... highlightFields) {
this.highlightFields = highlightFields; this.highlightFields = highlightFields;
@ -162,9 +160,9 @@ public class NativeSearchQueryBuilder {
nativeSearchQuery.setScriptFields(scriptFields); nativeSearchQuery.setScriptFields(scriptFields);
} }
if (CollectionUtils.isNotEmpty(facetRequests)) { /* if (CollectionUtils.isNotEmpty(facetRequests)) {
nativeSearchQuery.setFacets(facetRequests); nativeSearchQuery.setFacets(facetRequests);
} }*/
if (CollectionUtils.isNotEmpty(aggregationBuilders)) { if (CollectionUtils.isNotEmpty(aggregationBuilders)) {
nativeSearchQuery.setAggregations(aggregationBuilders); nativeSearchQuery.setAggregations(aggregationBuilders);

View File

@ -1,31 +1,26 @@
package org.springframework.data.elasticsearch.core.query; package org.springframework.data.elasticsearch.core.query;
import java.util.Map; import org.elasticsearch.script.Script;
/** /**
* @author Ryan Murfitt * @author Ryan Murfitt
* @author Artur Konczak
*/ */
public class ScriptField { public class ScriptField {
private final String fieldName; private final String fieldName;
private final String script; private final Script script;
private final Map<String, Object> params;
public ScriptField(String fieldName, String script, Map<String, Object> params) { public ScriptField(String fieldName, Script script) {
this.fieldName = fieldName; this.fieldName = fieldName;
this.script = script; this.script = script;
this.params = params;
} }
public String fieldName() { public String fieldName() {
return fieldName; return fieldName;
} }
public String script() { public Script script() {
return script; return script;
} }
public Map<String, Object> params() {
return params;
}
} }

View File

@ -17,12 +17,10 @@ package org.springframework.data.elasticsearch.core.query;
import java.util.List; import java.util.List;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.highlight.HighlightBuilder; import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder; import org.elasticsearch.search.sort.SortBuilder;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
/** /**
* NativeSearchQuery * NativeSearchQuery
@ -35,11 +33,11 @@ public interface SearchQuery extends Query {
QueryBuilder getQuery(); QueryBuilder getQuery();
FilterBuilder getFilter(); QueryBuilder getFilter();
List<SortBuilder> getElasticsearchSorts(); List<SortBuilder> getElasticsearchSorts();
List<FacetRequest> getFacets(); /*List<FacetRequest> getFacets();*/
List<AbstractAggregationBuilder> getAggregations(); List<AbstractAggregationBuilder> getAggregations();

View File

@ -74,6 +74,13 @@
</xsd:documentation> </xsd:documentation>
</xsd:annotation> </xsd:annotation>
</xsd:attribute> </xsd:attribute>
<xsd:attribute name="path-home" type="xsd:string" default="">
<xsd:annotation>
<xsd:documentation>
<![CDATA[ path to the home folder for node client ]]>
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="path-configuration" type="xsd:string" default=""> <xsd:attribute name="path-configuration" type="xsd:string" default="">
<xsd:annotation> <xsd:annotation>
<xsd:documentation> <xsd:documentation>

View File

@ -26,7 +26,7 @@ import org.springframework.data.elasticsearch.annotations.ScriptedField;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = "test-index", type = "test-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-index", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleEntity { public class SampleEntity {
@Id @Id

View File

@ -15,12 +15,12 @@
*/ */
package org.springframework.data.elasticsearch; package org.springframework.data.elasticsearch;
import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import static org.elasticsearch.node.NodeBuilder.*;
import java.util.UUID; import java.util.UUID;
import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings;
/** /**
* @author Mohsin Husen * @author Mohsin Husen
@ -28,13 +28,11 @@ import org.elasticsearch.common.settings.ImmutableSettings;
public class Utils { public class Utils {
public static NodeClient getNodeClient() { public static NodeClient getNodeClient() {
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder() return (NodeClient) nodeBuilder().settings(Settings.builder()
.put("http.enabled", "false") .put("http.enabled", "false")
.put("path.data", "target/elasticsearchTestData"); .put("path.data", "target/elasticsearchTestData")
return (NodeClient) nodeBuilder().settings(settings).clusterName(UUID.randomUUID().toString()).local(true).node() .put("path.home", "test-home-dir"))
.clusterName(UUID.randomUUID().toString()).local(true).node()
.client(); .client();
} }
} }

View File

@ -52,7 +52,7 @@ public class AliasTests {
settings.put("index.refresh_interval", "-1"); settings.put("index.refresh_interval", "-1");
settings.put("index.number_of_replicas", "0"); settings.put("index.number_of_replicas", "0");
settings.put("index.number_of_shards", "2"); settings.put("index.number_of_shards", "2");
settings.put("index.store.type", "memory"); settings.put("index.store.type", "fs");
elasticsearchTemplate.deleteIndex(INDEX_NAME); elasticsearchTemplate.deleteIndex(INDEX_NAME);
elasticsearchTemplate.createIndex(INDEX_NAME, settings); elasticsearchTemplate.createIndex(INDEX_NAME, settings);

View File

@ -50,7 +50,6 @@ public class ElasticsearchTemplateParentChildTests {
clean(); clean();
elasticsearchTemplate.createIndex(ParentEntity.class); elasticsearchTemplate.createIndex(ParentEntity.class);
elasticsearchTemplate.createIndex(ChildEntity.class); elasticsearchTemplate.createIndex(ChildEntity.class);
elasticsearchTemplate.putMapping(ParentEntity.class);
elasticsearchTemplate.putMapping(ChildEntity.class); elasticsearchTemplate.putMapping(ChildEntity.class);
} }
@ -82,28 +81,6 @@ public class ElasticsearchTemplateParentChildTests {
assertThat("parents", parents, contains(hasProperty("id", is(parent1.getId())))); assertThat("parents", parents, contains(hasProperty("id", is(parent1.getId()))));
} }
@Test
public void shouldSearchTopChildrenForGivenParent() {
// index two parents
ParentEntity parent1 = index("parent1", "First Parent");
ParentEntity parent2 = index("parent2", "Second Parent");
// index a child for each parent
String child1name = "First";
index("child1", parent1.getId(), child1name);
index("child2", parent2.getId(), "Second");
elasticsearchTemplate.refresh(ParentEntity.class, true);
elasticsearchTemplate.refresh(ChildEntity.class, true);
// find all parents that have the first child using topChildren Query
QueryBuilder query = topChildrenQuery(ParentEntity.CHILD_TYPE, QueryBuilders.termQuery("name", child1name.toLowerCase()));
List<ParentEntity> parents = elasticsearchTemplate.queryForList(new NativeSearchQuery(query), ParentEntity.class);
// we're expecting only the first parent as result
assertThat("parents", parents, contains(hasProperty("id", is(parent1.getId()))));
}
private ParentEntity index(String parentId, String name) { private ParentEntity index(String parentId, String name) {
ParentEntity parent = new ParentEntity(parentId, name); ParentEntity parent = new ParentEntity(parentId, name);
IndexQuery index = new IndexQuery(); IndexQuery index = new IndexQuery();

View File

@ -16,7 +16,6 @@
package org.springframework.data.elasticsearch.core; package org.springframework.data.elasticsearch.core;
import static org.apache.commons.lang.RandomStringUtils.*; import static org.apache.commons.lang.RandomStringUtils.*;
import static org.elasticsearch.index.query.FilterBuilders.*;
import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@ -30,6 +29,8 @@ import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.engine.DocumentMissingException; import org.elasticsearch.index.engine.DocumentMissingException;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.highlight.HighlightBuilder; import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.FieldSortBuilder;
@ -48,7 +49,6 @@ import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.query.*; import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.data.elasticsearch.entities.*; import org.springframework.data.elasticsearch.entities.*;
import org.springframework.data.elasticsearch.repositories.existing.index.CreateIndexFalseEntity;
import org.springframework.data.util.CloseableIterator; import org.springframework.data.util.CloseableIterator;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -360,7 +360,7 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFilter(boolFilter().must(termFilter("id", documentId))).build(); .withFilter(boolQuery().filter(termQuery("id", documentId))).build();
// when // when
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
// then // then
@ -466,35 +466,35 @@ public class ElasticsearchTemplateTests {
assertThat(sampleEntities.getTotalElements(), equalTo(1L)); assertThat(sampleEntities.getTotalElements(), equalTo(1L));
} }
@Test @Test
public void shouldUseScriptedFields() { public void shouldUseScriptedFields() {
// given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setRate(2); sampleEntity.setRate(2);
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
IndexQuery indexQuery = new IndexQuery(); IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(documentId); indexQuery.setId(documentId);
indexQuery.setObject(sampleEntity); indexQuery.setObject(sampleEntity);
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
Map<String, Object> params = new HashMap<String, Object>(); Map<String, Object> params = new HashMap<String, Object>();
params.put("factor", 2); params.put("factor", 2);
// when // when
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery()) .withQuery(matchAllQuery())
.withScriptField(new ScriptField("scriptedRate", "doc['rate'].value * factor", params)) .withScriptField(new ScriptField("scriptedRate", new Script("doc['rate'].value * factor", ScriptService.ScriptType.INLINE, "groovy", params)))
.build(); .build();
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
// then // then
assertThat(sampleEntities.getTotalElements(), equalTo(1L)); assertThat(sampleEntities.getTotalElements(), equalTo(1L));
assertThat(sampleEntities.getContent().get(0).getScriptedRate(), equalTo(4L)); assertThat(sampleEntities.getContent().get(0).getScriptedRate(), equalTo(4L));
} }
@Test @Test
public void shouldReturnPageableResultsGivenStringQuery() { public void shouldReturnPageableResultsGivenStringQuery() {
@ -1229,27 +1229,6 @@ public class ElasticsearchTemplateTests {
assertThat(sampleEntities.getContent().get(0).getHighlightedMessage(), is(highlightedMessage)); assertThat(sampleEntities.getContent().get(0).getHighlightedMessage(), is(highlightedMessage));
} }
@Test
public void shouldDeleteSpecifiedTypeFromAnIndex() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = SampleEntity.builder().id(documentId)
.message("some message")
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = getIndexQuery(sampleEntity);
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class, true);
// when
elasticsearchTemplate.deleteType(INDEX_NAME, TYPE_NAME);
elasticsearchTemplate.refresh(SampleEntity.class, true);
//then
boolean typeExists = elasticsearchTemplate.typeExists(INDEX_NAME, TYPE_NAME);
assertThat(typeExists, is(false));
}
@Test @Test
public void shouldDeleteDocumentBySpecifiedTypeUsingDeleteQuery() { public void shouldDeleteDocumentBySpecifiedTypeUsingDeleteQuery() {
// given // given
@ -1882,7 +1861,7 @@ public class ElasticsearchTemplateTests {
assertThat((String) map.get("index.refresh_interval"), is("-1")); assertThat((String) map.get("index.refresh_interval"), is("-1"));
assertThat((String) map.get("index.number_of_replicas"), is("0")); assertThat((String) map.get("index.number_of_replicas"), is("0"));
assertThat((String) map.get("index.number_of_shards"), is("1")); assertThat((String) map.get("index.number_of_shards"), is("1"));
assertThat((String) map.get("index.store.type"), is("memory")); assertThat((String) map.get("index.store.type"), is("fs"));
} }
/* /*

View File

@ -7,7 +7,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
/** /**
* @author Mewes Kochheim * @author Mewes Kochheim
*/ */
@Document(indexName = "test-completion-index", type = "annotated-completion-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-completion-index", type = "annotated-completion-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class AnnotatedCompletionEntity { public class AnnotatedCompletionEntity {
@Id @Id

View File

@ -9,7 +9,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
* @author Mohsin Husen * @author Mohsin Husen
* @author Mewes Kochheim * @author Mewes Kochheim
*/ */
@Document(indexName = "test-completion-index", type = "completion-annotation-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-completion-index", type = "completion-annotation-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class CompletionAnnotatedEntity { public class CompletionAnnotatedEntity {
@Id @Id

View File

@ -6,7 +6,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
/** /**
* @author Mewes Kochheim * @author Mewes Kochheim
*/ */
@Document(indexName = "test-completion-index", type = "completion-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-completion-index", type = "completion-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class CompletionEntity { public class CompletionEntity {
@Id @Id

View File

@ -34,7 +34,7 @@ import org.springframework.data.elasticsearch.annotations.NestedField;
* @author Artur Konczak * @author Artur Konczak
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = "articles", type = "article", shards = 1, replicas = 0, refreshInterval = "-1", indexStoreType = "memory") @Document(indexName = "articles", type = "article", shards = 1, replicas = 0, refreshInterval = "-1")
public class ArticleEntity { public class ArticleEntity {
@Id @Id

View File

@ -12,7 +12,8 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet; package org.springframework.data.elasticsearch.core.facet;
import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.*;
@ -35,12 +36,14 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*/
/** /**
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
* @author Jonathan Yan * @author Jonathan Yan
* @author Artur Konczak * @author Artur Konczak
*/ *//*
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml") @ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class ElasticsearchTemplateFacetTests { public class ElasticsearchTemplateFacetTests {
@ -632,3 +635,4 @@ public class ElasticsearchTemplateFacetTests {
assertThat(unit.getCount(), is(1L)); assertThat(unit.getCount(), is(1L));
} }
} }
*/

View File

@ -12,7 +12,8 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ *//*
package org.springframework.data.elasticsearch.core.facet; package org.springframework.data.elasticsearch.core.facet;
import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.*;
@ -38,12 +39,14 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*/
/** /**
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
* @author Jonathan Yan * @author Jonathan Yan
* @author Artur Konczak * @author Artur Konczak
*/ *//*
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml") @ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class ElasticsearchTemplateHistogramFacetTests { public class ElasticsearchTemplateHistogramFacetTests {
@ -137,3 +140,4 @@ public class ElasticsearchTemplateHistogramFacetTests {
assertThat(unit.getCount(), is(1L)); assertThat(unit.getCount(), is(1L));
} }
} }
*/

View File

@ -32,7 +32,7 @@ import org.springframework.data.elasticsearch.annotations.Field;
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = "test-log-index", type = "test-log-type", shards = 1, replicas = 0, refreshInterval = "-1", indexStoreType = "memory") @Document(indexName = "test-log-index", type = "test-log-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class LogEntity { public class LogEntity {
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

View File

@ -22,7 +22,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
* @author Franck Marchand * @author Franck Marchand
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = "test-geo-index", type = "geo-class-point-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-geo-index", type = "geo-class-point-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class AuthorMarkerEntity { public class AuthorMarkerEntity {
@Id @Id

View File

@ -22,8 +22,8 @@ import static org.junit.Assert.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.elasticsearch.common.geo.GeoHashUtils; import com.spatial4j.core.io.GeohashUtils;
import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -192,7 +192,7 @@ public class ElasticsearchTemplateGeoTests {
public void shouldFindAllMarkersForNativeSearchQuery() { public void shouldFindAllMarkersForNativeSearchQuery() {
//Given //Given
loadAnnotationBaseEntities(); loadAnnotationBaseEntities();
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withFilter(FilterBuilders.geoBoundingBoxFilter("locationAsArray").topLeft(52, -1).bottomRight(50, 1)); NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsArray").topLeft(52, -1).bottomRight(50, 1));
//When //When
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(queryBuilder.build(), LocationMarkerEntity.class); List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(queryBuilder.build(), LocationMarkerEntity.class);
//Then //Then
@ -222,7 +222,7 @@ public class ElasticsearchTemplateGeoTests {
//given //given
loadClassBaseEntities(); loadClassBaseEntities();
CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery(
new Criteria("location").boundedBy(GeoHashUtils.encode(53.5171d, 0), GeoHashUtils.encode(49.5171d, 0.2062d))); new Criteria("location").boundedBy(GeohashUtils.encodeLatLon(53.5171d, 0), GeohashUtils.encodeLatLon(49.5171d, 0.2062d)));
//when //when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); List<AuthorMarkerEntity> geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class);
@ -273,13 +273,13 @@ public class ElasticsearchTemplateGeoTests {
//u1044k2bd6u - with precision = 5 -> u, u1, u10, u104, u1044 //u1044k2bd6u - with precision = 5 -> u, u1, u10, u104, u1044
loadAnnotationBaseEntities(); loadAnnotationBaseEntities();
NativeSearchQueryBuilder locationWithPrefixAsDistancePrecision3 = new NativeSearchQueryBuilder().withFilter(FilterBuilders.geoHashCellFilter("box-one").field("locationWithPrefixAsDistance").geohash("u1044k2bd6u").precision(3)); NativeSearchQueryBuilder locationWithPrefixAsDistancePrecision3 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoHashCellQuery("box-one").field("locationWithPrefixAsDistance").geohash("u1044k2bd6u").precision(3));
NativeSearchQueryBuilder locationWithPrefixAsDistancePrecision4 = new NativeSearchQueryBuilder().withFilter(FilterBuilders.geoHashCellFilter("box-one").field("locationWithPrefixAsDistance").geohash("u1044k2bd6u").precision(4)); NativeSearchQueryBuilder locationWithPrefixAsDistancePrecision4 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoHashCellQuery("box-one").field("locationWithPrefixAsDistance").geohash("u1044k2bd6u").precision(4));
NativeSearchQueryBuilder locationWithPrefixAsDistancePrecision5 = new NativeSearchQueryBuilder().withFilter(FilterBuilders.geoHashCellFilter("box-one").field("locationWithPrefixAsDistance").geohash("u1044k2bd6u").precision(5)); NativeSearchQueryBuilder locationWithPrefixAsDistancePrecision5 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoHashCellQuery("box-one").field("locationWithPrefixAsDistance").geohash("u1044k2bd6u").precision(5));
NativeSearchQueryBuilder locationWithPrefixAsLengthOfGeoHashPrecision4 = new NativeSearchQueryBuilder().withFilter(FilterBuilders.geoHashCellFilter("box-one").field("locationWithPrefixAsLengthOfGeoHash").geohash("u1044k2bd6u").precision(4)); NativeSearchQueryBuilder locationWithPrefixAsLengthOfGeoHashPrecision4 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoHashCellQuery("box-one").field("locationWithPrefixAsLengthOfGeoHash").geohash("u1044k2bd6u").precision(4));
NativeSearchQueryBuilder locationWithPrefixAsLengthOfGeoHashPrecision5 = new NativeSearchQueryBuilder().withFilter(FilterBuilders.geoHashCellFilter("box-one").field("locationWithPrefixAsLengthOfGeoHash").geohash("u1044k2bd6u").precision(5)); NativeSearchQueryBuilder locationWithPrefixAsLengthOfGeoHashPrecision5 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoHashCellQuery("box-one").field("locationWithPrefixAsLengthOfGeoHash").geohash("u1044k2bd6u").precision(5));
NativeSearchQueryBuilder locationWithPrefixAsLengthOfGeoHashPrecision6 = new NativeSearchQueryBuilder().withFilter(FilterBuilders.geoHashCellFilter("box-one").field("locationWithPrefixAsLengthOfGeoHash").geohash("u1044k2bd6u").precision(6)); NativeSearchQueryBuilder locationWithPrefixAsLengthOfGeoHashPrecision6 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoHashCellQuery("box-one").field("locationWithPrefixAsLengthOfGeoHash").geohash("u1044k2bd6u").precision(6));
//when //when
List<LocationMarkerEntity> resultDistancePrecision3 = elasticsearchTemplate.queryForList(locationWithPrefixAsDistancePrecision3.build(), LocationMarkerEntity.class); List<LocationMarkerEntity> resultDistancePrecision3 = elasticsearchTemplate.queryForList(locationWithPrefixAsDistancePrecision3.build(), LocationMarkerEntity.class);
List<LocationMarkerEntity> resultDistancePrecision4 = elasticsearchTemplate.queryForList(locationWithPrefixAsDistancePrecision4.build(), LocationMarkerEntity.class); List<LocationMarkerEntity> resultDistancePrecision4 = elasticsearchTemplate.queryForList(locationWithPrefixAsDistancePrecision4.build(), LocationMarkerEntity.class);

View File

@ -28,7 +28,7 @@ import org.springframework.data.elasticsearch.annotations.GeoPointField;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-geo-index", type = "geo-annotation-point-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-geo-index", type = "geo-annotation-point-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class LocationMarkerEntity { public class LocationMarkerEntity {
@Id @Id

View File

@ -34,7 +34,7 @@ import org.springframework.data.elasticsearch.annotations.FieldType;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "book", type = "book", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "book", type = "book", shards = 1, replicas = 0, refreshInterval = "-1")
public class Book { public class Book {
@Id @Id

View File

@ -24,7 +24,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = "double-keyed-entity", type = "double-keyed-entity", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "double-keyed-entity", type = "double-keyed-entity", shards = 1, replicas = 0, refreshInterval = "-1")
public class DoubleIDEntity { public class DoubleIDEntity {
@Id @Id

View File

@ -19,7 +19,7 @@ import org.springframework.data.geo.Polygon;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "geo-test-index", type = "geo-test-index", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "geo-test-index", type = "geo-test-index", shards = 1, replicas = 0, refreshInterval = "-1")
public class GeoEntity { public class GeoEntity {
@Id @Id

View File

@ -24,7 +24,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = "integer-keyed-entity", type = "integer-keyed-entity", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "integer-keyed-entity", type = "integer-keyed-entity", shards = 1, replicas = 0, refreshInterval = "-1")
public class IntegerIDEntity { public class IntegerIDEntity {
@Id @Id

View File

@ -25,7 +25,7 @@ import org.springframework.data.elasticsearch.annotations.*;
* @author Philipp Jardas * @author Philipp Jardas
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = ParentEntity.INDEX, type = ParentEntity.PARENT_TYPE, indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = ParentEntity.INDEX, type = ParentEntity.PARENT_TYPE, shards = 1, replicas = 0, refreshInterval = "-1")
public class ParentEntity { public class ParentEntity {
public static final String INDEX = "parent-child"; public static final String INDEX = "parent-child";
@ -58,7 +58,7 @@ public class ParentEntity {
return new ToStringCreator(this).append("id", id).append("name", name).toString(); return new ToStringCreator(this).append("id", id).append("name", name).toString();
} }
@Document(indexName = INDEX, type = CHILD_TYPE, indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = INDEX, type = CHILD_TYPE, shards = 1, replicas = 0, refreshInterval = "-1")
public static class ChildEntity { public static class ChildEntity {
@Id @Id

View File

@ -29,7 +29,7 @@ import org.springframework.data.elasticsearch.annotations.FieldType;
* @author Artur Konczak * @author Artur Konczak
*/ */
@Document(indexName = "person", type = "user", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "person", type = "user", shards = 1, replicas = 0, refreshInterval = "-1")
public class Person { public class Person {
@Id @Id

View File

@ -29,7 +29,7 @@ import org.springframework.data.elasticsearch.annotations.FieldType;
* @author Artur Konczak * @author Artur Konczak
*/ */
@Document(indexName = "person-multiple-level-nested", type = "user", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "person-multiple-level-nested", type = "user", shards = 1, replicas = 0, refreshInterval = "-1")
public class PersonMultipleLevelNested { public class PersonMultipleLevelNested {
@Id @Id

View File

@ -33,7 +33,7 @@ import org.springframework.data.elasticsearch.annotations.FieldType;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-product-index", type = "test-product-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-product-index", type = "test-product-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class Product { public class Product {
@Id @Id

View File

@ -14,7 +14,7 @@ import org.springframework.data.elasticsearch.annotations.Field;
/** /**
* @author Jakub Vavrik * @author Jakub Vavrik
*/ */
@Document(indexName = "test-datemapping", type = "mapping", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-datemapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleDateMappingEntity { public class SampleDateMappingEntity {
@Id @Id

View File

@ -32,7 +32,7 @@ import org.springframework.data.elasticsearch.core.geo.GeoPoint;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index", type = "test-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-index", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleEntity { public class SampleEntity {
@Id @Id

View File

@ -24,7 +24,7 @@ import org.springframework.data.elasticsearch.annotations.Field;
/** /**
* @author Kevin Leturc * @author Kevin Leturc
*/ */
@Document(indexName = "test-inherited-mapping", type = "mapping", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-inherited-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleInheritedEntity extends AbstractInheritedEntity { public class SampleInheritedEntity extends AbstractInheritedEntity {
@Field(type = String, index = not_analyzed, store = true, searchAnalyzer = "standard", indexAnalyzer = "standard") @Field(type = String, index = not_analyzed, store = true, searchAnalyzer = "standard", indexAnalyzer = "standard")

View File

@ -26,7 +26,7 @@ import org.springframework.data.elasticsearch.annotations.Field;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = "test-mapping", type = "mapping", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleMappingEntity { public class SampleMappingEntity {
@Id @Id

View File

@ -26,7 +26,7 @@ import org.springframework.data.elasticsearch.annotations.Field;
/** /**
* @author Jakub Vavrik * @author Jakub Vavrik
*/ */
@Document(indexName = "test-recursive-mapping", type = "mapping", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-recursive-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleTransientEntity { public class SampleTransientEntity {
@Id @Id

View File

@ -24,7 +24,7 @@ import org.springframework.data.elasticsearch.annotations.FieldType;
* @author Stuart Stevenson * @author Stuart Stevenson
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = "circular-objects", type = "circular-object", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "circular-objects", type = "circular-object", shards = 1, replicas = 0, refreshInterval = "-1")
public class SimpleRecursiveEntity { public class SimpleRecursiveEntity {
@Id @Id

View File

@ -23,7 +23,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
* *
* @author Artur Konczak * @author Artur Konczak
*/ */
@Document(indexName = "#{'abz'+'-'+'entity'}", type = "#{'my'+'Type'}", indexStoreType = "memory", shards = 1, @Document(indexName = "#{'abz'+'-'+'entity'}", type = "#{'my'+'Type'}", shards = 1,
replicas = 0, refreshInterval = "-1") replicas = 0, refreshInterval = "-1")
public class SpELEntity { public class SpELEntity {

View File

@ -32,7 +32,7 @@ import org.springframework.data.elasticsearch.annotations.FieldType;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "stock", type = "price", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "stock", type = "price", shards = 1, replicas = 0, refreshInterval = "-1")
public class StockPrice { public class StockPrice {
@Id @Id

View File

@ -12,7 +12,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-server-configuration", type = "test-type", useServerConfiguration = true, indexStoreType = "memory", shards = 10, replicas = 10, refreshInterval = "-1") @Document(indexName = "test-index-server-configuration", type = "test-type", useServerConfiguration = true, shards = 10, replicas = 10, refreshInterval = "-1")
public class UseServerConfigurationEntity { public class UseServerConfigurationEntity {
@Id @Id

View File

@ -1,95 +1,95 @@
/* ///*
* Copyright 2014 the original author or authors. // * Copyright 2014 the original author or authors.
* // *
* Licensed under the Apache License, Version 2.0 (the "License"); // * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. // * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at // * You may obtain a copy of the License at
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
*/ // */
package org.springframework.data.elasticsearch.repositories.cdi; //package org.springframework.data.elasticsearch.repositories.cdi;
//
import static org.hamcrest.CoreMatchers.is; //import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*; //import static org.junit.Assert.*;
//
import org.apache.webbeans.cditest.CdiTestContainer; //import org.apache.webbeans.cditest.CdiTestContainer;
import org.apache.webbeans.cditest.CdiTestContainerLoader; //import org.apache.webbeans.cditest.CdiTestContainerLoader;
import org.junit.AfterClass; //import org.junit.AfterClass;
import org.junit.Before; //import org.junit.Before;
import org.junit.BeforeClass; //import org.junit.BeforeClass;
import org.junit.Test; //import org.junit.Test;
import org.springframework.data.elasticsearch.entities.Product; //import org.springframework.data.elasticsearch.entities.Product;
//
/** ///**
* @author Mohsin Husen // * @author Mohsin Husen
*/ // */
//TODO: ako cdi - jar hell
public class CdiRepositoryTests { //public class CdiRepositoryTests {
//
private static CdiTestContainer cdiContainer; // private static CdiTestContainer cdiContainer;
private CdiProductRepository repository; // private CdiProductRepository repository;
private SamplePersonRepository personRepository; // private SamplePersonRepository personRepository;
//
@BeforeClass // @BeforeClass
public static void init() throws Exception { // public static void init() throws Exception {
cdiContainer = CdiTestContainerLoader.getCdiContainer(); // cdiContainer = CdiTestContainerLoader.getCdiContainer();
cdiContainer.startApplicationScope(); // cdiContainer.startApplicationScope();
cdiContainer.bootContainer(); // cdiContainer.bootContainer();
} // }
//
@AfterClass // @AfterClass
public static void shutdown() throws Exception { // public static void shutdown() throws Exception {
cdiContainer.stopContexts(); // cdiContainer.stopContexts();
cdiContainer.shutdownContainer(); // cdiContainer.shutdownContainer();
} // }
//
@Before // @Before
public void setUp() { // public void setUp() {
CdiRepositoryClient client = cdiContainer.getInstance(CdiRepositoryClient.class); // CdiRepositoryClient client = cdiContainer.getInstance(CdiRepositoryClient.class);
repository = client.getRepository(); // repository = client.getRepository();
personRepository = client.getSamplePersonRepository(); // personRepository = client.getSamplePersonRepository();
} // }
//
@Test // @Test
public void testCdiRepository() { // public void testCdiRepository() {
assertNotNull(repository); // assertNotNull(repository);
//
Product bean = new Product(); // Product bean = new Product();
bean.setId("id-1"); // bean.setId("id-1");
bean.setName("cidContainerTest-1"); // bean.setName("cidContainerTest-1");
//
repository.save(bean); // repository.save(bean);
//
assertTrue(repository.exists(bean.getId())); // assertTrue(repository.exists(bean.getId()));
//
Product retrieved = repository.findOne(bean.getId()); // Product retrieved = repository.findOne(bean.getId());
assertNotNull(retrieved); // assertNotNull(retrieved);
assertEquals(bean.getId(), retrieved.getId()); // assertEquals(bean.getId(), retrieved.getId());
assertEquals(bean.getName(), retrieved.getName()); // assertEquals(bean.getName(), retrieved.getName());
//
assertEquals(1, repository.count()); // assertEquals(1, repository.count());
//
assertTrue(repository.exists(bean.getId())); // assertTrue(repository.exists(bean.getId()));
//
repository.delete(bean); // repository.delete(bean);
//
assertEquals(0, repository.count()); // assertEquals(0, repository.count());
retrieved = repository.findOne(bean.getId()); // retrieved = repository.findOne(bean.getId());
assertNull(retrieved); // assertNull(retrieved);
} // }
//
/** // /**
* @see DATAES-113 // * @see DATAES-113
*/ // */
@Test // @Test
public void returnOneFromCustomImpl() { // public void returnOneFromCustomImpl() {
//
assertThat(personRepository.returnOne(), is(1)); // assertThat(personRepository.returnOne(), is(1));
} // }
} //}

View File

@ -24,7 +24,8 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.elasticsearch.common.collect.Lists; import com.google.common.collect.Lists;
import org.apache.lucene.util.CollectionUtil;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;

View File

@ -6,7 +6,7 @@
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<elasticsearch:node-client id="client" local="true" cluster-name="#{T(java.util.UUID).randomUUID().toString()}" <elasticsearch:node-client id="client" local="true" cluster-name="#{T(java.util.UUID).randomUUID().toString()}"
http-enabled="false" path-data="target/elasticsearchTestData" http-enabled="false" path-data="target/elasticsearchTestData" path-home="test-home-dir"
path-configuration="node-client-configuration.yml"/> path-configuration="node-client-configuration.yml"/>
<!--<elasticsearch:transport-client id="client" cluster-name="elasticsearch" cluster-nodes="127.0.0.1:9300" />--> <!--<elasticsearch:transport-client id="client" cluster-name="elasticsearch" cluster-nodes="127.0.0.1:9300" />-->

View File

@ -1,3 +1,20 @@
#enabled scripts - this require groovy #enabled scripts - this require groovy
script.inline: on script.inline: true
script.indexed: on script.indexed: true
#script.groovy.sandbox.enabled: true
#script.groovy.sandbox.enabled: true
#script.engine.groovy.file.aggs: true
#script.engine.groovy.file.mapping: true
#script.engine.groovy.file.search: true
#script.engine.groovy.file.update: true
#script.engine.groovy.file.plugin: true
#script.engine.groovy.indexed.aggs: true
#script.engine.groovy.indexed.mapping: true
#script.engine.groovy.indexed.search: true
#script.engine.groovy.indexed.update: true
#script.engine.groovy.indexed.plugin: true
#script.engine.groovy.inline.aggs: true
#script.engine.groovy.inline.mapping: true
#script.engine.groovy.inline.search: true
#script.engine.groovy.inline.update: true
#script.engine.groovy.inline.plugin: true

View File

@ -0,0 +1,80 @@
# Elasticsearch plugin descriptor file
# This file must exist as 'plugin-descriptor.properties' at
# the root directory of all plugins.
#
# A plugin can be 'site', 'jvm', or both.
#
### example site plugin for "foo":
#
# foo.zip <-- zip file for the plugin, with this structure:
# _site/ <-- the contents that will be served
# plugin-descriptor.properties <-- example contents below:
#
# site=true
# description=My cool plugin
# version=1.0
#
### example jvm plugin for "foo"
#
# foo.zip <-- zip file for the plugin, with this structure:
# <arbitrary name1>.jar <-- classes, resources, dependencies
# <arbitrary nameN>.jar <-- any number of jars
# plugin-descriptor.properties <-- example contents below:
#
# jvm=true
# classname=foo.bar.BazPlugin
# description=My cool plugin
# version=2.0.0-rc1
# elasticsearch.version=2.0
# java.version=1.7
#
### mandatory elements for all plugins:
#
# 'description': simple summary of the plugin
description=Groovy scripting integration for Elasticsearch
#
# 'version': plugin's version
version=2.2.0
#
# 'name': the plugin name
name=lang-groovy
### mandatory elements for site plugins:
#
# 'site': set to true to indicate contents of the _site/
# directory in the root of the plugin should be served.
site=false
#
### mandatory elements for jvm plugins :
#
# 'jvm': true if the 'classname' class should be loaded
# from jar files in the root directory of the plugin.
# Note that only jar files in the root directory are
# added to the classpath for the plugin! If you need
# other resources, package them into a resources jar.
jvm=true
#
# 'classname': the name of the class to load, fully-qualified.
classname=org.elasticsearch.script.groovy.GroovyPlugin
#
# 'java.version' version of java the code is built against
# use the system property java.specification.version
# version string must be a sequence of nonnegative decimal integers
# separated by "."'s and may have leading zeros
java.version=1.7
#
# 'elasticsearch.version' version of elasticsearch compiled against
# You will have to release a new version of the plugin for each new
# elasticsearch release. This version is checked when the plugin
# is loaded so Elasticsearch will refuse to start in the presence of
# plugins with the incorrect elasticsearch.version.
elasticsearch.version=2.2.0
#
### deprecated elements for jvm plugins :
#
# 'isolated': true if the plugin should have its own classloader.
# passing false is deprecated, and only intended to support plugins
# that have hard dependencies against each other. If this is
# not specified, then the plugin is isolated by default.
isolated=true
#

View File

@ -0,0 +1,57 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
grant {
// needed to generate runtime classes
permission java.lang.RuntimePermission "createClassLoader";
// needed by IndyInterface
permission java.lang.RuntimePermission "getClassLoader";
// needed by groovy engine
permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect";
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
// needed by GroovyScriptEngineService to close its classloader (why?)
permission java.lang.RuntimePermission "closeClassLoader";
// Allow executing groovy scripts with codesource of /untrusted
permission groovy.security.GroovyCodeSourcePermission "/untrusted";
// Standard set of classes
permission org.elasticsearch.script.ClassPermission "<<STANDARD>>";
// groovy runtime (TODO: clean these up if possible)
permission org.elasticsearch.script.ClassPermission "groovy.grape.GrabAnnotationTransformation";
permission org.elasticsearch.script.ClassPermission "groovy.json.JsonOutput";
permission org.elasticsearch.script.ClassPermission "groovy.lang.Binding";
permission org.elasticsearch.script.ClassPermission "groovy.lang.GroovyObject";
permission org.elasticsearch.script.ClassPermission "groovy.lang.GString";
permission org.elasticsearch.script.ClassPermission "groovy.lang.Script";
permission org.elasticsearch.script.ClassPermission "groovy.util.GroovyCollections";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.ast.builder.AstBuilderTransformation";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.reflection.ClassInfo";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.GStringImpl";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.powerassert.ValueRecorder";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.powerassert.AssertionRenderer";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.ScriptBytecodeAdapter";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.vmplugin.v7.IndyInterface";
permission org.elasticsearch.script.ClassPermission "sun.reflect.ConstructorAccessorImpl";
permission org.elasticsearch.script.ClassPermission "groovy.lang.Closure";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.GeneratedClosure";
permission org.elasticsearch.script.ClassPermission "groovy.lang.MetaClass";
permission org.elasticsearch.script.ClassPermission "groovy.lang.Range";
};