DATAES-579 - Polishing.

Use Lombok's Data where possible. Extract duplicate code into ResourceUtil and StreamQueries. Generalize multiGet to return List instead of LinkedList. Reorder methods.

Reduce properties usage by removing unused properties from test entities.

Remove final keyword usage in methods. Formatting.

Original pull request: #283.
This commit is contained in:
Mark Paluch 2019-05-31 11:45:00 +02:00
parent 4c206f7de5
commit 198ad0e02b
62 changed files with 723 additions and 1972 deletions

View File

@ -15,41 +15,81 @@
*/
package org.springframework.data.elasticsearch.annotations;
import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.elasticsearch.index.VersionType;
import org.springframework.data.annotation.Persistent;
/**
* Document
* Identifies a domain object to be persisted to Elasticsearch.
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mason Chan
* @author Ivan Greene
* @author Mark Paluch
*/
@Persistent
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Target({ ElementType.TYPE })
public @interface Document {
/**
* Name of the Elasticsearch index.
* <ul>
* <li>Lowercase only</li>
* <li><Cannot include \, /, *, ?, ", <, >, |, ` ` (space character), ,, #/li>
* <li>Cannot start with -, _, +</li>
* <li>Cannot be . or ..</li>
* <li>Cannot be longer than 255 bytes (note it is bytes, so multi-byte characters will count towards the 255 limit
* faster)</li>
* </ul>
*/
String indexName();
/**
* Mapping type name.
*/
String type() default "";
/**
* Use server-side settings when creating the index.
*/
boolean useServerConfiguration() default false;
/**
* Number of shards for the index {@link #indexName()}. Used for index creation.
*/
short shards() default 5;
/**
* Number of replicas for the index {@link #indexName()}. Used for index creation.
*/
short replicas() default 1;
/**
* Refresh interval for the index {@link #indexName()}. Used for index creation.
*/
String refreshInterval() default "1s";
/**
* Index storage type for the index {@link #indexName()}. Used for index creation.
*/
String indexStoreType() default "fs";
/**
* Configuration whether to create an index on repository bootstrapping.
*/
boolean createIndex() default true;
/**
* Configuration of version management.
*/
VersionType versionType() default VersionType.EXTERNAL;
}

View File

@ -20,7 +20,6 @@ import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.elasticsearch.action.get.GetResponse;
@ -29,6 +28,7 @@ import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.search.SearchHit;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.data.domain.Pageable;
@ -189,8 +189,8 @@ public class DefaultResultMapper extends AbstractResultMapper {
}
@Override
public <T> LinkedList<T> mapResults(MultiGetResponse responses, Class<T> clazz) {
LinkedList<T> list = new LinkedList<>();
public <T> List<T> mapResults(MultiGetResponse responses, Class<T> clazz) {
List<T> list = new ArrayList<>();
for (MultiGetItemResponse response : responses.getResponses()) {
if (!response.isFailed() && response.getResponse().isExists()) {
T result = mapEntity(response.getResponse().getSourceAsString(), clazz);

View File

@ -15,20 +15,28 @@
*/
package org.springframework.data.elasticsearch.core;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.common.Nullable;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.data.util.CloseableIterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.common.Nullable;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.DeleteQuery;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.MoreLikeThisQuery;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.util.CloseableIterator;
/**
* ElasticsearchOperations
*
@ -42,9 +50,20 @@ import java.util.stream.Collectors;
public interface ElasticsearchOperations {
/**
* @return Converter in use
* adding new alias
*
* @param query
* @return
*/
ElasticsearchConverter getElasticsearchConverter();
boolean addAlias(AliasQuery query);
/**
* removing previously created alias
*
* @param query
* @return
*/
boolean removeAlias(AliasQuery query);
/**
* Create an index for a class
@ -102,7 +121,6 @@ public interface ElasticsearchOperations {
*/
<T> boolean putMapping(Class<T> clazz, Object mappings);
/**
* Get mapping for a class
*
@ -133,6 +151,15 @@ public interface ElasticsearchOperations {
*/
<T> Map<String, Object> getSetting(Class<T> clazz);
/**
* get all the alias pointing to specified index
*
* @param indexName
* @return
*/
List<AliasMetaData> queryForAlias(String indexName);
<T> T query(SearchQuery query, ResultsExtractor<T> resultsExtractor);
/**
* Execute the query against elasticsearch and return the first returned object
@ -199,7 +226,8 @@ public interface ElasticsearchOperations {
<T> List<Page<T>> queryForPage(List<SearchQuery> queries, Class<T> clazz);
/**
* Execute the multi-search against elasticsearch and return result as {@link List} of {@link Page} using custom mapper
* Execute the multi-search against elasticsearch and return result as {@link List} of {@link Page} using custom
* mapper
*
* @param queries
* @param clazz
@ -217,7 +245,8 @@ public interface ElasticsearchOperations {
List<Page<?>> queryForPage(List<SearchQuery> queries, List<Class<?>> classes);
/**
* Execute the multi-search against elasticsearch and return result as {@link List} of {@link Page} using custom mapper
* Execute the multi-search against elasticsearch and return result as {@link List} of {@link Page} using custom
* mapper
*
* @param queries
* @param classes
@ -255,7 +284,8 @@ public interface ElasticsearchOperations {
/**
* Executes the given {@link CriteriaQuery} against elasticsearch and return result as {@link CloseableIterator}.
* <p>
* Returns a {@link CloseableIterator} that wraps an Elasticsearch scroll context that needs to be closed in case of error.
* Returns a {@link CloseableIterator} that wraps an Elasticsearch scroll context that needs to be closed in case of
* error.
*
* @param <T> element return type
* @param query
@ -268,7 +298,8 @@ public interface ElasticsearchOperations {
/**
* Executes the given {@link SearchQuery} against elasticsearch and return result as {@link CloseableIterator}.
* <p>
* Returns a {@link CloseableIterator} that wraps an Elasticsearch scroll context that needs to be closed in case of error.
* Returns a {@link CloseableIterator} that wraps an Elasticsearch scroll context that needs to be closed in case of
* error.
*
* @param <T> element return type
* @param query
@ -279,9 +310,11 @@ public interface ElasticsearchOperations {
<T> CloseableIterator<T> stream(SearchQuery query, Class<T> clazz);
/**
* Executes the given {@link SearchQuery} against elasticsearch and return result as {@link CloseableIterator} using custom mapper.
* Executes the given {@link SearchQuery} against elasticsearch and return result as {@link CloseableIterator} using
* custom mapper.
* <p>
* Returns a {@link CloseableIterator} that wraps an Elasticsearch scroll context that needs to be closed in case of error.
* Returns a {@link CloseableIterator} that wraps an Elasticsearch scroll context that needs to be closed in case of
* error.
*
* @param <T> element return type
* @param query
@ -394,7 +427,7 @@ public interface ElasticsearchOperations {
* @param clazz
* @return
*/
<T> LinkedList<T> multiGet(SearchQuery searchQuery, Class<T> clazz);
<T> List<T> multiGet(SearchQuery searchQuery, Class<T> clazz);
/**
* Execute a multiGet against elasticsearch for the given ids with MultiGetResultMapper
@ -404,7 +437,7 @@ public interface ElasticsearchOperations {
* @param multiGetResultMapper
* @return
*/
<T> LinkedList<T> multiGet(SearchQuery searchQuery, Class<T> clazz, MultiGetResultMapper multiGetResultMapper);
<T> List<T> multiGet(SearchQuery searchQuery, Class<T> clazz, MultiGetResultMapper multiGetResultMapper);
/**
* Index an object. Will do save or update
@ -446,7 +479,6 @@ public interface ElasticsearchOperations {
*/
String delete(String indexName, String type, String id);
/**
* Delete all records matching the criteria
*
@ -454,6 +486,7 @@ public interface ElasticsearchOperations {
* @param criteriaQuery
*/
<T> void delete(CriteriaQuery criteriaQuery, Class<T> clazz);
/**
* Delete the one object with provided id
*
@ -525,7 +558,6 @@ public interface ElasticsearchOperations {
* refresh the index
*
* @param indexName
*
*/
void refresh(String indexName);
@ -533,7 +565,6 @@ public interface ElasticsearchOperations {
* refresh the index
*
* @param clazz
*
*/
<T> void refresh(Class<T> clazz);
@ -542,7 +573,7 @@ public interface ElasticsearchOperations {
*
* @param query The search query.
* @param scrollTimeInMillis The time in millisecond for scroll feature
* {@link org.elasticsearch.action.search.SearchRequestBuilder#setScroll(org.elasticsearch.common.unit.TimeValue)}.
* {@link org.elasticsearch.action.search.SearchRequestBuilder#setScroll(org.elasticsearch.common.unit.TimeValue)}.
* @param clazz The class of entity to retrieve.
* @return The scan id for input query.
*/
@ -553,18 +584,19 @@ public interface ElasticsearchOperations {
*
* @param query The search query.
* @param scrollTimeInMillis The time in millisecond for scroll feature
* {@link org.elasticsearch.action.search.SearchRequestBuilder#setScroll(org.elasticsearch.common.unit.TimeValue)}.
* {@link org.elasticsearch.action.search.SearchRequestBuilder#setScroll(org.elasticsearch.common.unit.TimeValue)}.
* @param mapper Custom impl to map result to entities
* @return The scan id for input query.
*/
<T> ScrolledPage<T> startScroll(long scrollTimeInMillis, SearchQuery query, Class<T> clazz, SearchResultMapper mapper);
<T> ScrolledPage<T> startScroll(long scrollTimeInMillis, SearchQuery query, Class<T> clazz,
SearchResultMapper mapper);
/**
* Returns scrolled page for given query
*
* @param criteriaQuery The search query.
* @param scrollTimeInMillis The time in millisecond for scroll feature
* {@link org.elasticsearch.action.search.SearchRequestBuilder#setScroll(org.elasticsearch.common.unit.TimeValue)}.
* {@link org.elasticsearch.action.search.SearchRequestBuilder#setScroll(org.elasticsearch.common.unit.TimeValue)}.
* @param clazz The class of entity to retrieve.
* @return The scan id for input query.
*/
@ -575,20 +607,22 @@ public interface ElasticsearchOperations {
*
* @param criteriaQuery The search query.
* @param scrollTimeInMillis The time in millisecond for scroll feature
* {@link org.elasticsearch.action.search.SearchRequestBuilder#setScroll(org.elasticsearch.common.unit.TimeValue)}.
* {@link org.elasticsearch.action.search.SearchRequestBuilder#setScroll(org.elasticsearch.common.unit.TimeValue)}.
* @param mapper Custom impl to map result to entities
* @return The scan id for input query.
*/
<T> ScrolledPage<T> startScroll(long scrollTimeInMillis, CriteriaQuery criteriaQuery, Class<T> clazz, SearchResultMapper mapper);
<T> ScrolledPage<T> startScroll(long scrollTimeInMillis, CriteriaQuery criteriaQuery, Class<T> clazz,
SearchResultMapper mapper);
<T> ScrolledPage<T> continueScroll(@Nullable String scrollId, long scrollTimeInMillis, Class<T> clazz);
<T> ScrolledPage<T> continueScroll(@Nullable String scrollId, long scrollTimeInMillis, Class<T> clazz, SearchResultMapper mapper);
<T> ScrolledPage<T> continueScroll(@Nullable String scrollId, long scrollTimeInMillis, Class<T> clazz,
SearchResultMapper mapper);
/**
* Clears the search contexts associated with specified scroll ids.
*
* @param scrollId
*
*/
<T> void clearScroll(String scrollId);
@ -602,33 +636,10 @@ public interface ElasticsearchOperations {
*/
<T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz);
/**
* adding new alias
*
* @param query
* @return
*/
Boolean addAlias(AliasQuery query);
/**
* removing previously created alias
*
* @param query
* @return
*/
Boolean removeAlias(AliasQuery query);
/**
* get all the alias pointing to specified index
*
* @param indexName
* @return
*/
List<AliasMetaData> queryForAlias(String indexName);
<T> T query(SearchQuery query, ResultsExtractor<T> resultsExtractor);
ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz);
/**
* @return Converter in use
*/
ElasticsearchConverter getElasticsearchConverter();
}

View File

@ -20,16 +20,12 @@ import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.springframework.util.CollectionUtils.isEmpty;
import static org.springframework.util.StringUtils.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Set;
@ -93,7 +89,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@ -195,6 +190,48 @@ public class ElasticsearchRestTemplate
this.searchTimeout = searchTimeout;
}
@Override
public boolean addAlias(AliasQuery query) {
Assert.notNull(query.getIndexName(), "No index defined for Alias");
Assert.notNull(query.getAliasName(), "No alias defined");
IndicesAliasesRequest.AliasActions aliasAction = IndicesAliasesRequest.AliasActions.add()
.alias(query.getAliasName()).index(query.getIndexName());
if (query.getFilterBuilder() != null) {
aliasAction.filter(query.getFilterBuilder());
} else if (query.getFilter() != null) {
aliasAction.filter(query.getFilter());
} else if (hasText(query.getRouting())) {
aliasAction.routing(query.getRouting());
} else if (hasText(query.getSearchRouting())) {
aliasAction.searchRouting(query.getSearchRouting());
} else if (hasText(query.getIndexRouting())) {
aliasAction.indexRouting(query.getIndexRouting());
}
IndicesAliasesRequest request = new IndicesAliasesRequest();
request.addAliasAction(aliasAction);
try {
return client.indices().updateAliases(request).isAcknowledged();
} catch (IOException e) {
throw new ElasticsearchException("failed to update aliases with request: " + request, e);
}
}
@Override
public boolean removeAlias(AliasQuery query) {
Assert.notNull(query.getIndexName(), "No index defined for Alias");
Assert.notNull(query.getAliasName(), "No alias defined");
IndicesAliasesRequest request = new IndicesAliasesRequest();
AliasActions aliasAction = new AliasActions(AliasActions.Type.REMOVE);
request.addAliasAction(aliasAction);
try {
return client.indices().updateAliases(request).isAcknowledged();
} catch (IOException e) {
throw new ElasticsearchException("failed to update aliases with request: " + request, e);
}
}
@Override
public <T> boolean createIndex(Class<T> clazz) {
return createIndexIfNotCreated(clazz);
@ -215,7 +252,7 @@ public class ElasticsearchRestTemplate
if (clazz.isAnnotationPresent(Mapping.class)) {
String mappingPath = clazz.getAnnotation(Mapping.class).mappingPath();
if (hasText(mappingPath)) {
String mappings = readFileFromClasspath(mappingPath);
String mappings = ResourceUtil.readFileFromClasspath(mappingPath);
if (hasText(mappings)) {
return putMapping(clazz, mappings);
}
@ -257,10 +294,10 @@ public class ElasticsearchRestTemplate
}
@Override
public Map getMapping(String indexName, String type) {
public Map<String, Object> getMapping(String indexName, String type) {
Assert.notNull(indexName, "No index defined for getMapping()");
Assert.notNull(type, "No type defined for getMapping()");
Map mappings = null;
Map<String, Object> mappings = null;
RestClient restClient = client.getLowLevelClient();
try {
Response response = restClient.performRequest("GET", "/" + indexName + "/_mapping/" + type);
@ -273,7 +310,7 @@ public class ElasticsearchRestTemplate
}
@Override
public <T> Map getMapping(Class<T> clazz) {
public <T> Map<String, Object> getMapping(Class<T> clazz) {
return getMapping(getPersistentEntityFor(clazz).getIndexName(), getPersistentEntityFor(clazz).getIndexType());
}
@ -281,7 +318,7 @@ public class ElasticsearchRestTemplate
ObjectMapper mapper = new ObjectMapper();
try {
Map result = null;
Map<String, Object> result = null;
JsonNode node = mapper.readTree(mappingResponse);
node = node.findValue("mappings").findValue(type);
@ -312,8 +349,7 @@ public class ElasticsearchRestTemplate
GetResponse response;
try {
response = client.get(request);
T entity = mapper.mapResult(response, clazz);
return entity;
return mapper.mapResult(response, clazz);
} catch (IOException e) {
throw new ElasticsearchException("Error while getting for request: " + request.toString(), e);
}
@ -497,7 +533,7 @@ public class ElasticsearchRestTemplate
@Override
public <T> CloseableIterator<T> stream(CriteriaQuery query, Class<T> clazz) {
final long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis();
long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis();
return doStream(scrollTimeInMillis, startScroll(scrollTimeInMillis, query, clazz), clazz, resultsMapper);
}
@ -507,68 +543,15 @@ public class ElasticsearchRestTemplate
}
@Override
public <T> CloseableIterator<T> stream(SearchQuery query, final Class<T> clazz, final SearchResultMapper mapper) {
final long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis();
public <T> CloseableIterator<T> stream(SearchQuery query, Class<T> clazz, SearchResultMapper mapper) {
long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis();
return doStream(scrollTimeInMillis, startScroll(scrollTimeInMillis, query, clazz, mapper), clazz, mapper);
}
private <T> CloseableIterator<T> doStream(final long scrollTimeInMillis, final ScrolledPage<T> page,
final Class<T> clazz, final SearchResultMapper mapper) {
return new CloseableIterator<T>() {
/** As we couldn't retrieve single result with scroll, store current hits. */
private volatile Iterator<T> currentHits = page.iterator();
/** The scroll id. */
private volatile String scrollId = page.getScrollId();
/** If stream is finished (ie: cluster returns no results. */
private volatile boolean finished = !currentHits.hasNext();
@Override
public void close() {
try {
// Clear scroll on cluster only in case of error (cause elasticsearch auto clear scroll when it's done)
if (!finished && scrollId != null && currentHits != null && currentHits.hasNext()) {
clearScroll(scrollId);
}
} finally {
currentHits = null;
scrollId = null;
}
}
@Override
public boolean hasNext() {
// Test if stream is finished
if (finished) {
return false;
}
// Test if it remains hits
if (currentHits == null || !currentHits.hasNext()) {
// Do a new request
final ScrolledPage<T> scroll = continueScroll(scrollId, scrollTimeInMillis, clazz, mapper);
// Save hits and scroll id
currentHits = scroll.iterator();
finished = !currentHits.hasNext();
scrollId = scroll.getScrollId();
}
return currentHits.hasNext();
}
@Override
public T next() {
if (hasNext()) {
return currentHits.next();
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
private <T> CloseableIterator<T> doStream(long scrollTimeInMillis, ScrolledPage<T> page, Class<T> clazz,
SearchResultMapper mapper) {
return StreamQueries.streamResults(page, scrollId -> continueScroll(scrollId, scrollTimeInMillis, clazz, mapper),
this::clearScroll);
}
@Override
@ -658,7 +641,7 @@ public class ElasticsearchRestTemplate
}
@Override
public <T> LinkedList<T> multiGet(SearchQuery searchQuery, Class<T> clazz) {
public <T> List<T> multiGet(SearchQuery searchQuery, Class<T> clazz) {
return resultsMapper.mapResults(getMultiResponse(searchQuery, clazz), clazz);
}
@ -697,7 +680,7 @@ public class ElasticsearchRestTemplate
}
@Override
public <T> LinkedList<T> multiGet(SearchQuery searchQuery, Class<T> clazz, MultiGetResultMapper getResultMapper) {
public <T> List<T> multiGet(SearchQuery searchQuery, Class<T> clazz, MultiGetResultMapper getResultMapper) {
return getResultMapper.mapResults(getMultiResponse(searchQuery, clazz), clazz);
}
@ -1162,7 +1145,7 @@ public class ElasticsearchRestTemplate
if (clazz.isAnnotationPresent(Setting.class)) {
String settingPath = clazz.getAnnotation(Setting.class).settingPath();
if (hasText(settingPath)) {
String settings = readFileFromClasspath(settingPath);
String settings = ResourceUtil.readFileFromClasspath(settingPath);
if (hasText(settings)) {
return createIndex(getPersistentEntityFor(clazz).getIndexName(), settings);
}
@ -1375,48 +1358,6 @@ public class ElasticsearchRestTemplate
refresh(getPersistentEntityFor(clazz).getIndexName());
}
@Override
public Boolean addAlias(AliasQuery query) {
Assert.notNull(query.getIndexName(), "No index defined for Alias");
Assert.notNull(query.getAliasName(), "No alias defined");
final IndicesAliasesRequest.AliasActions aliasAction = IndicesAliasesRequest.AliasActions.add()
.alias(query.getAliasName()).index(query.getIndexName());
if (query.getFilterBuilder() != null) {
aliasAction.filter(query.getFilterBuilder());
} else if (query.getFilter() != null) {
aliasAction.filter(query.getFilter());
} else if (hasText(query.getRouting())) {
aliasAction.routing(query.getRouting());
} else if (hasText(query.getSearchRouting())) {
aliasAction.searchRouting(query.getSearchRouting());
} else if (hasText(query.getIndexRouting())) {
aliasAction.indexRouting(query.getIndexRouting());
}
IndicesAliasesRequest request = new IndicesAliasesRequest();
request.addAliasAction(aliasAction);
try {
return client.indices().updateAliases(request).isAcknowledged();
} catch (IOException e) {
throw new ElasticsearchException("failed to update aliases with request: " + request, e);
}
}
@Override
public Boolean removeAlias(AliasQuery query) {
Assert.notNull(query.getIndexName(), "No index defined for Alias");
Assert.notNull(query.getAliasName(), "No alias defined");
IndicesAliasesRequest request = new IndicesAliasesRequest();
AliasActions aliasAction = new AliasActions(AliasActions.Type.REMOVE);
request.addAliasAction(aliasAction);
try {
return client.indices().updateAliases(request).isAcknowledged();
} catch (IOException e) {
throw new ElasticsearchException("failed to update aliases with request: " + request, e);
}
}
@Override
public List<AliasMetaData> queryForAlias(String indexName) {
List<AliasMetaData> aliases = null;
@ -1441,7 +1382,7 @@ public class ElasticsearchRestTemplate
* @param aliasResponse
* @return
*/
List<AliasMetaData> convertAliasResponse(String aliasResponse) {
private List<AliasMetaData> convertAliasResponse(String aliasResponse) {
ObjectMapper mapper = new ObjectMapper();
try {
@ -1560,34 +1501,9 @@ public class ElasticsearchRestTemplate
return resultsMapper;
}
@Deprecated
public static String readFileFromClasspath(String url) {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
ClassPathResource classPathResource = new ClassPathResource(url);
InputStreamReader inputStreamReader = new InputStreamReader(classPathResource.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
String line;
String lineSeparator = System.getProperty("line.separator");
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append(lineSeparator);
}
} catch (Exception e) {
logger.debug(String.format("Failed to load file from url: %s: %s", url, e.getMessage()));
return null;
} finally {
if (bufferedReader != null)
try {
bufferedReader.close();
} catch (IOException e) {
logger.debug(String.format("Unable to close buffered reader.. %s", e.getMessage()));
}
}
return stringBuilder.toString();
return ResourceUtil.readFileFromClasspath(url);
}
public SearchResponse suggest(SuggestBuilder suggestion, String... indices) {

View File

@ -19,16 +19,12 @@ import static org.elasticsearch.client.Requests.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.springframework.util.CollectionUtils.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;
import org.elasticsearch.action.ActionFuture;
@ -79,10 +75,10 @@ import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@ -181,6 +177,35 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
this.searchTimeout = searchTimeout;
}
@Override
public boolean addAlias(AliasQuery query) {
Assert.notNull(query.getIndexName(), "No index defined for Alias");
Assert.notNull(query.getAliasName(), "No alias defined");
IndicesAliasesRequest.AliasActions aliasAction = IndicesAliasesRequest.AliasActions.add()
.alias(query.getAliasName()).index(query.getIndexName());
if (query.getFilterBuilder() != null) {
aliasAction.filter(query.getFilterBuilder());
} else if (query.getFilter() != null) {
aliasAction.filter(query.getFilter());
} else if (!StringUtils.isEmpty(query.getRouting())) {
aliasAction.routing(query.getRouting());
} else if (!StringUtils.isEmpty(query.getSearchRouting())) {
aliasAction.searchRouting(query.getSearchRouting());
} else if (!StringUtils.isEmpty(query.getIndexRouting())) {
aliasAction.indexRouting(query.getIndexRouting());
}
return client.admin().indices().prepareAliases().addAliasAction(aliasAction).execute().actionGet().isAcknowledged();
}
@Override
public boolean removeAlias(AliasQuery query) {
Assert.notNull(query.getIndexName(), "No index defined for Alias");
Assert.notNull(query.getAliasName(), "No alias defined");
return client.admin().indices().prepareAliases().removeAlias(query.getIndexName(), query.getAliasName()).execute()
.actionGet().isAcknowledged();
}
@Override
public <T> boolean createIndex(Class<T> clazz) {
return createIndexIfNotCreated(clazz);
@ -197,7 +222,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
if (clazz.isAnnotationPresent(Mapping.class)) {
String mappingPath = clazz.getAnnotation(Mapping.class).mappingPath();
if (!StringUtils.isEmpty(mappingPath)) {
String mappings = readFileFromClasspath(mappingPath);
String mappings = ResourceUtil.readFileFromClasspath(mappingPath);
if (!StringUtils.isEmpty(mappings)) {
return putMapping(clazz, mappings);
}
@ -429,9 +454,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
@Override
public <T> CloseableIterator<T> stream(CriteriaQuery query, Class<T> clazz) {
final long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis();
return doStream(scrollTimeInMillis, startScroll(scrollTimeInMillis, query, clazz), clazz,
resultsMapper);
long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis();
return doStream(scrollTimeInMillis, startScroll(scrollTimeInMillis, query, clazz), clazz, resultsMapper);
}
@Override
@ -440,69 +464,15 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
}
@Override
public <T> CloseableIterator<T> stream(SearchQuery query, final Class<T> clazz, final SearchResultMapper mapper) {
final long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis();
return doStream(scrollTimeInMillis, startScroll(scrollTimeInMillis, query, clazz, mapper), clazz,
mapper);
public <T> CloseableIterator<T> stream(SearchQuery query, Class<T> clazz, SearchResultMapper mapper) {
long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis();
return doStream(scrollTimeInMillis, startScroll(scrollTimeInMillis, query, clazz, mapper), clazz, mapper);
}
private <T> CloseableIterator<T> doStream(final long scrollTimeInMillis, final ScrolledPage<T> page,
final Class<T> clazz, final SearchResultMapper mapper) {
return new CloseableIterator<T>() {
/** As we couldn't retrieve single result with scroll, store current hits. */
private volatile Iterator<T> currentHits = page.iterator();
/** The scroll id. */
private volatile String scrollId = page.getScrollId();
/** If stream is finished (ie: cluster returns no results. */
private volatile boolean finished = !currentHits.hasNext();
@Override
public void close() {
try {
// Clear scroll on cluster only in case of error (cause elasticsearch auto clear scroll when it's done)
if (!finished && scrollId != null && currentHits != null && currentHits.hasNext()) {
clearScroll(scrollId);
}
} finally {
currentHits = null;
scrollId = null;
}
}
@Override
public boolean hasNext() {
// Test if stream is finished
if (finished) {
return false;
}
// Test if it remains hits
if (currentHits == null || !currentHits.hasNext()) {
// Do a new request
final ScrolledPage<T> scroll = continueScroll(scrollId, scrollTimeInMillis, clazz, mapper);
// Save hits and scroll id
currentHits = scroll.iterator();
finished = !currentHits.hasNext();
scrollId = scroll.getScrollId();
}
return currentHits.hasNext();
}
@Override
public T next() {
if (hasNext()) {
return currentHits.next();
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
private <T> CloseableIterator<T> doStream(long scrollTimeInMillis, ScrolledPage<T> page, Class<T> clazz,
SearchResultMapper mapper) {
return StreamQueries.streamResults(page, scrollId -> continueScroll(scrollId, scrollTimeInMillis, clazz, mapper),
this::clearScroll);
}
@Override
@ -582,7 +552,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
}
@Override
public <T> LinkedList<T> multiGet(SearchQuery searchQuery, Class<T> clazz) {
public <T> List<T> multiGet(SearchQuery searchQuery, Class<T> clazz) {
return resultsMapper.mapResults(getMultiResponse(searchQuery, clazz), clazz);
}
@ -617,7 +587,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
}
@Override
public <T> LinkedList<T> multiGet(SearchQuery searchQuery, Class<T> clazz, MultiGetResultMapper getResultMapper) {
public <T> List<T> multiGet(SearchQuery searchQuery, Class<T> clazz, MultiGetResultMapper getResultMapper) {
return getResultMapper.mapResults(getMultiResponse(searchQuery, clazz), clazz);
}
@ -1006,7 +976,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
if (clazz.isAnnotationPresent(Setting.class)) {
String settingPath = clazz.getAnnotation(Setting.class).settingPath();
if (!StringUtils.isEmpty(settingPath)) {
String settings = readFileFromClasspath(settingPath);
String settings = ResourceUtil.readFileFromClasspath(settingPath);
if (!StringUtils.isEmpty(settings)) {
return createIndex(getPersistentEntityFor(clazz).getIndexName(), settings);
}
@ -1183,35 +1153,6 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
refresh(getPersistentEntityFor(clazz).getIndexName());
}
@Override
public Boolean addAlias(AliasQuery query) {
Assert.notNull(query.getIndexName(), "No index defined for Alias");
Assert.notNull(query.getAliasName(), "No alias defined");
final IndicesAliasesRequest.AliasActions aliasAction = IndicesAliasesRequest.AliasActions.add()
.alias(query.getAliasName()).index(query.getIndexName());
if (query.getFilterBuilder() != null) {
aliasAction.filter(query.getFilterBuilder());
} else if (query.getFilter() != null) {
aliasAction.filter(query.getFilter());
} else if (!StringUtils.isEmpty(query.getRouting())) {
aliasAction.routing(query.getRouting());
} else if (!StringUtils.isEmpty(query.getSearchRouting())) {
aliasAction.searchRouting(query.getSearchRouting());
} else if (!StringUtils.isEmpty(query.getIndexRouting())) {
aliasAction.indexRouting(query.getIndexRouting());
}
return client.admin().indices().prepareAliases().addAliasAction(aliasAction).execute().actionGet().isAcknowledged();
}
@Override
public Boolean removeAlias(AliasQuery query) {
Assert.notNull(query.getIndexName(), "No index defined for Alias");
Assert.notNull(query.getAliasName(), "No alias defined");
return client.admin().indices().prepareAliases().removeAlias(query.getIndexName(), query.getAliasName()).execute()
.actionGet().isAcknowledged();
}
@Override
public List<AliasMetaData> queryForAlias(String indexName) {
return client.admin().indices().getAliases(new GetAliasesRequest().indices(indexName)).actionGet().getAliases()
@ -1309,34 +1250,9 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
return resultsMapper;
}
@Deprecated
public static String readFileFromClasspath(String url) {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
ClassPathResource classPathResource = new ClassPathResource(url);
InputStreamReader inputStreamReader = new InputStreamReader(classPathResource.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
String line;
String lineSeparator = System.getProperty("line.separator");
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append(lineSeparator);
}
} catch (Exception e) {
LOGGER.debug(String.format("Failed to load file from url: %s: %s", url, e.getMessage()));
return null;
} finally {
if (bufferedReader != null)
try {
bufferedReader.close();
} catch (IOException e) {
LOGGER.debug(String.format("Unable to close buffered reader.. %s", e.getMessage()));
}
}
return stringBuilder.toString();
return ResourceUtil.readFileFromClasspath(url);
}
public SearchResponse suggest(SuggestBuilder suggestion, String... indices) {

View File

@ -418,7 +418,7 @@ class MappingBuilder {
String mappingPath = entity.getRequiredAnnotation(DynamicTemplates.class).mappingPath();
if (hasText(mappingPath)) {
String jsonString = ElasticsearchTemplate.readFileFromClasspath(mappingPath);
String jsonString = ResourceUtil.readFileFromClasspath(mappingPath);
if (hasText(jsonString)) {
ObjectMapper objectMapper = new ObjectMapper();

View File

@ -16,7 +16,7 @@
package org.springframework.data.elasticsearch.core;
import java.util.LinkedList;
import java.util.List;
import org.elasticsearch.action.get.MultiGetResponse;
@ -25,5 +25,5 @@ import org.elasticsearch.action.get.MultiGetResponse;
*/
public interface MultiGetResultMapper {
<T> LinkedList<T> mapResults(MultiGetResponse responses, Class<T> clazz);
<T> List<T> mapResults(MultiGetResponse responses, Class<T> clazz);
}

View File

@ -0,0 +1,56 @@
/*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.
*/
package org.springframework.data.elasticsearch.core;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
/**
* Utility to read {@link org.springframework.core.io.Resource}s.
*
* @author Mark Paluch
* @since 3.2
*/
abstract class ResourceUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ResourceUtil.class);
/**
* Read a {@link ClassPathResource} into a {@link String}.
*
* @param url
* @return
*/
public static String readFileFromClasspath(String url) {
ClassPathResource classPathResource = new ClassPathResource(url);
try (InputStream is = classPathResource.getInputStream()) {
return StreamUtils.copyToString(is, Charset.defaultCharset());
} catch (Exception e) {
LOGGER.debug(String.format("Failed to load file from url: %s: %s", url, e.getMessage()));
return null;
}
}
// Utility constructor
private ResourceUtil() {}
}

View File

@ -0,0 +1,104 @@
/*
* Copyright 2019 the original author or authors.
*
* Licensed 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
*
* https://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.
*/
package org.springframework.data.elasticsearch.core;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
import java.util.function.Function;
import org.springframework.data.util.CloseableIterator;
/**
* Utility to support streaming queries.
*
* @author Mark Paluch
* @since 3.2
*/
abstract class StreamQueries {
/**
* Stream query results using {@link ScrolledPage}.
*
* @param page the initial page.
* @param continueFunction continuation function accepting the current scrollId.
* @param clearScroll cleanup function accepting the current scrollId.
* @param <T>
* @return the {@link CloseableIterator}.
*/
static <T> CloseableIterator<T> streamResults(ScrolledPage<T> page,
Function<String, ScrolledPage<T>> continueFunction, Consumer<String> clearScroll) {
return new CloseableIterator<T>() {
/** As we couldn't retrieve single result with scroll, store current hits. */
private volatile Iterator<T> currentHits = page.iterator();
/** The scroll id. */
private volatile String scrollId = page.getScrollId();
/** If stream is finished (ie: cluster returns no results. */
private volatile boolean finished = !currentHits.hasNext();
@Override
public void close() {
try {
// Clear scroll on cluster only in case of error (cause elasticsearch auto clear scroll when it's done)
if (!finished && scrollId != null && currentHits != null && currentHits.hasNext()) {
clearScroll.accept(scrollId);
}
} finally {
currentHits = null;
scrollId = null;
}
}
@Override
public boolean hasNext() {
// Test if stream is finished
if (finished) {
return false;
}
// Test if it remains hits
if (currentHits == null || !currentHits.hasNext()) {
// Do a new request
ScrolledPage<T> scroll = continueFunction.apply(scrollId);
// Save hits and scroll id
currentHits = scroll.iterator();
finished = !currentHits.hasNext();
scrollId = scroll.getScrollId();
}
return currentHits.hasNext();
}
@Override
public T next() {
if (hasNext()) {
return currentHits.next();
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
// utility constructor
private StreamQueries() {}
}

View File

@ -39,7 +39,7 @@ public class SimpleElasticsearchMappingContext
@Override
protected <T> SimpleElasticsearchPersistentEntity<?> createPersistentEntity(TypeInformation<T> typeInformation) {
final SimpleElasticsearchPersistentEntity<T> persistentEntity = new SimpleElasticsearchPersistentEntity<>(
SimpleElasticsearchPersistentEntity<T> persistentEntity = new SimpleElasticsearchPersistentEntity<>(
typeInformation);
if (context != null) {
persistentEntity.setApplicationContext(context);

View File

@ -59,7 +59,7 @@ public class ElasticsearchVersionRule implements TestRule {
}
@Override
public Statement apply(final Statement base, Description description) {
public Statement apply(Statement base, Description description) {
return new Statement() {

View File

@ -19,6 +19,7 @@ import static org.apache.commons.lang.RandomStringUtils.*;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@ -58,6 +59,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Mohsin Husen
* @author Artur Konczak
* @author Peter-Josef Meisch
* @author Mark Paluch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/elasticsearch-template-test.xml")
@ -76,17 +78,17 @@ public class NestedObjectTests {
@Test
public void shouldIndexInitialLevelNestedObject() {
final List<Car> cars = new ArrayList<>();
List<Car> cars = new ArrayList<>();
final Car saturn = new Car();
Car saturn = new Car();
saturn.setName("Saturn");
saturn.setModel("SL");
final Car subaru = new Car();
Car subaru = new Car();
subaru.setName("Subaru");
subaru.setModel("Imprezza");
final Car ford = new Car();
Car ford = new Car();
ford.setName("Ford");
ford.setModel("Focus");
@ -94,26 +96,26 @@ public class NestedObjectTests {
cars.add(subaru);
cars.add(ford);
final Person foo = new Person();
Person foo = new Person();
foo.setName("Foo");
foo.setId("1");
foo.setCar(cars);
final Car car = new Car();
Car car = new Car();
car.setName("Saturn");
car.setModel("Imprezza");
final Person bar = new Person();
Person bar = new Person();
bar.setId("2");
bar.setName("Bar");
bar.setCar(Arrays.asList(car));
bar.setCar(Collections.singletonList(car));
final List<IndexQuery> indexQueries = new ArrayList<>();
final IndexQuery indexQuery1 = new IndexQuery();
List<IndexQuery> indexQueries = new ArrayList<>();
IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(foo.getId());
indexQuery1.setObject(foo);
final IndexQuery indexQuery2 = new IndexQuery();
IndexQuery indexQuery2 = new IndexQuery();
indexQuery2.setId(bar.getId());
indexQuery2.setObject(bar);
@ -123,11 +125,11 @@ public class NestedObjectTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(Person.class);
final QueryBuilder builder = nestedQuery("car",
QueryBuilder builder = nestedQuery("car",
boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None);
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
final List<Person> persons = elasticsearchTemplate.queryForList(searchQuery, Person.class);
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
List<Person> persons = elasticsearchTemplate.queryForList(searchQuery, Person.class);
assertThat(persons).hasSize(1);
}
@ -136,16 +138,16 @@ public class NestedObjectTests {
public void shouldIndexMultipleLevelNestedObject() {
// given
final List<IndexQuery> indexQueries = createPerson();
List<IndexQuery> indexQueries = createPerson();
// when
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(PersonMultipleLevelNested.class);
// then
final GetQuery getQuery = new GetQuery();
GetQuery getQuery = new GetQuery();
getQuery.setId("1");
final PersonMultipleLevelNested personIndexed = elasticsearchTemplate.queryForObject(getQuery,
PersonMultipleLevelNested personIndexed = elasticsearchTemplate.queryForObject(getQuery,
PersonMultipleLevelNested.class);
assertThat(personIndexed).isNotNull();
}
@ -154,18 +156,18 @@ public class NestedObjectTests {
public void shouldIndexMultipleLevelNestedObjectWithIncludeInParent() {
// given
final List<IndexQuery> indexQueries = createPerson();
List<IndexQuery> indexQueries = createPerson();
// when
elasticsearchTemplate.bulkIndex(indexQueries);
// then
final Map<String, Object> mapping = elasticsearchTemplate.getMapping(PersonMultipleLevelNested.class);
Map<String, Object> mapping = elasticsearchTemplate.getMapping(PersonMultipleLevelNested.class);
assertThat(mapping).isNotNull();
final Map<String, Object> propertyMap = (Map<String, Object>) mapping.get("properties");
Map<String, Object> propertyMap = (Map<String, Object>) mapping.get("properties");
assertThat(propertyMap).isNotNull();
final Map bestCarsAttributes = (Map) propertyMap.get("bestCars");
Map bestCarsAttributes = (Map) propertyMap.get("bestCars");
assertThat(bestCarsAttributes.get("include_in_parent")).isNotNull();
}
@ -173,20 +175,20 @@ public class NestedObjectTests {
public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject() {
// given
final List<IndexQuery> indexQueries = createPerson();
List<IndexQuery> indexQueries = createPerson();
// when
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(PersonMultipleLevelNested.class);
// then
final BoolQueryBuilder builder = boolQuery();
BoolQueryBuilder builder = boolQuery();
builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"), ScoreMode.None)).must(
nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()), ScoreMode.None));
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
final Page<PersonMultipleLevelNested> personIndexed = elasticsearchTemplate.queryForPage(searchQuery,
Page<PersonMultipleLevelNested> personIndexed = elasticsearchTemplate.queryForPage(searchQuery,
PersonMultipleLevelNested.class);
assertThat(personIndexed).isNotNull();
assertThat(personIndexed.getTotalElements()).isEqualTo(1);
@ -195,55 +197,55 @@ public class NestedObjectTests {
private List<IndexQuery> createPerson() {
final PersonMultipleLevelNested person1 = new PersonMultipleLevelNested();
PersonMultipleLevelNested person1 = new PersonMultipleLevelNested();
person1.setId("1");
person1.setName("name");
final Car saturn = new Car();
Car saturn = new Car();
saturn.setName("Saturn");
saturn.setModel("SL");
final Car subaru = new Car();
Car subaru = new Car();
subaru.setName("Subaru");
subaru.setModel("Imprezza");
final Car car = new Car();
Car car = new Car();
car.setName("Saturn");
car.setModel("Imprezza");
final Car ford = new Car();
Car ford = new Car();
ford.setName("Ford");
ford.setModel("Focus");
final GirlFriend permanent = new GirlFriend();
GirlFriend permanent = new GirlFriend();
permanent.setName("permanent");
permanent.setType("permanent");
permanent.setCars(Arrays.asList(saturn, subaru));
final GirlFriend temp = new GirlFriend();
GirlFriend temp = new GirlFriend();
temp.setName("temp");
temp.setType("temp");
temp.setCars(Arrays.asList(car, ford));
person1.setGirlFriends(Arrays.asList(permanent, temp));
final IndexQuery indexQuery1 = new IndexQuery();
IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(person1.getId());
indexQuery1.setObject(person1);
final PersonMultipleLevelNested person2 = new PersonMultipleLevelNested();
PersonMultipleLevelNested person2 = new PersonMultipleLevelNested();
person2.setId("2");
person2.setName("name");
person2.setGirlFriends(Collections.singletonList(permanent));
final IndexQuery indexQuery2 = new IndexQuery();
IndexQuery indexQuery2 = new IndexQuery();
indexQuery2.setId(person2.getId());
indexQuery2.setObject(person2);
final List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<>();
indexQueries.add(indexQuery1);
indexQueries.add(indexQuery2);
@ -254,17 +256,17 @@ public class NestedObjectTests {
public void shouldSearchBooksForPersonInitialLevelNestedType() {
// given
final List<Car> cars = new ArrayList<>();
List<Car> cars = new ArrayList<>();
final Car saturn = new Car();
Car saturn = new Car();
saturn.setName("Saturn");
saturn.setModel("SL");
final Car subaru = new Car();
Car subaru = new Car();
subaru.setName("Subaru");
subaru.setModel("Imprezza");
final Car ford = new Car();
Car ford = new Car();
ford.setName("Ford");
ford.setModel("Focus");
@ -272,43 +274,43 @@ public class NestedObjectTests {
cars.add(subaru);
cars.add(ford);
final Book java = new Book();
Book java = new Book();
java.setId("1");
java.setName("java");
final Author javaAuthor = new Author();
Author javaAuthor = new Author();
javaAuthor.setId("1");
javaAuthor.setName("javaAuthor");
java.setAuthor(javaAuthor);
final Book spring = new Book();
Book spring = new Book();
spring.setId("2");
spring.setName("spring");
final Author springAuthor = new Author();
Author springAuthor = new Author();
springAuthor.setId("2");
springAuthor.setName("springAuthor");
spring.setAuthor(springAuthor);
final Person foo = new Person();
Person foo = new Person();
foo.setName("Foo");
foo.setId("1");
foo.setCar(cars);
foo.setBooks(Arrays.asList(java, spring));
final Car car = new Car();
Car car = new Car();
car.setName("Saturn");
car.setModel("Imprezza");
final Person bar = new Person();
Person bar = new Person();
bar.setId("2");
bar.setName("Bar");
bar.setCar(Arrays.asList(car));
bar.setCar(Collections.singletonList(car));
final List<IndexQuery> indexQueries = new ArrayList<>();
final IndexQuery indexQuery1 = new IndexQuery();
List<IndexQuery> indexQueries = new ArrayList<>();
IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(foo.getId());
indexQuery1.setObject(foo);
final IndexQuery indexQuery2 = new IndexQuery();
IndexQuery indexQuery2 = new IndexQuery();
indexQuery2.setId(bar.getId());
indexQuery2.setObject(bar);
@ -319,11 +321,10 @@ public class NestedObjectTests {
elasticsearchTemplate.refresh(Person.class);
// when
final QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")),
ScoreMode.None);
QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")), ScoreMode.None);
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
final List<Person> persons = elasticsearchTemplate.queryForList(searchQuery, Person.class);
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
List<Person> persons = elasticsearchTemplate.queryForList(searchQuery, Person.class);
// then
assertThat(persons).hasSize(1);
@ -333,8 +334,8 @@ public class NestedObjectTests {
public void shouldIndexAndSearchMapAsNestedType() {
// given
final Book book1 = new Book();
final Book book2 = new Book();
Book book1 = new Book();
Book book2 = new Book();
book1.setId(randomNumeric(5));
book1.setName("testBook1");
@ -342,21 +343,21 @@ public class NestedObjectTests {
book2.setId(randomNumeric(5));
book2.setName("testBook2");
final Map<Integer, Collection<String>> map1 = new HashMap<>();
Map<Integer, Collection<String>> map1 = new HashMap<>();
map1.put(1, Arrays.asList("test1", "test2"));
final Map<Integer, Collection<String>> map2 = new HashMap<>();
Map<Integer, Collection<String>> map2 = new HashMap<>();
map2.put(1, Arrays.asList("test3", "test4"));
book1.setBuckets(map1);
book2.setBuckets(map2);
final List<IndexQuery> indexQueries = new ArrayList<>();
final IndexQuery indexQuery1 = new IndexQuery();
List<IndexQuery> indexQueries = new ArrayList<>();
IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(book1.getId());
indexQuery1.setObject(book1);
final IndexQuery indexQuery2 = new IndexQuery();
IndexQuery indexQuery2 = new IndexQuery();
indexQuery2.setId(book2.getId());
indexQuery2.setObject(book2);
@ -368,9 +369,9 @@ public class NestedObjectTests {
elasticsearchTemplate.refresh(Book.class);
// then
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.None)).build();
final Page<Book> books = elasticsearchTemplate.queryForPage(searchQuery, Book.class);
Page<Book> books = elasticsearchTemplate.queryForPage(searchQuery, Book.class);
assertThat(books.getContent()).hasSize(1);
assertThat(books.getContent().get(0).getId()).isEqualTo(book2.getId());
@ -378,7 +379,8 @@ public class NestedObjectTests {
@Setter
@Getter
@Document(indexName = "test-index-book-nested-objects", type = "book", shards = 1, replicas = 0, refreshInterval = "-1")
@Document(indexName = "test-index-book-nested-objects", type = "book", shards = 1, replicas = 0,
refreshInterval = "-1")
static class Book {
@Id private String id;
@ -390,6 +392,7 @@ public class NestedObjectTests {
searchAnalyzer = "standard") }) private String description;
}
@Data
@Document(indexName = "test-index-person", type = "user", shards = 1, replicas = 0, refreshInterval = "-1")
static class Person {
@ -400,60 +403,13 @@ public class NestedObjectTests {
@Field(type = FieldType.Nested) private List<Car> car;
@Field(type = FieldType.Nested, includeInParent = true) private List<Book> books;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Car> getCar() {
return car;
}
public void setCar(List<Car> car) {
this.car = car;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
@Data
static class Car {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
/**
@ -461,6 +417,7 @@ public class NestedObjectTests {
* @author Mohsin Husen
* @author Artur Konczak
*/
@Data
@Document(indexName = "test-index-person-multiple-level-nested", type = "user", shards = 1, replicas = 0,
refreshInterval = "-1")
static class PersonMultipleLevelNested {
@ -474,52 +431,12 @@ public class NestedObjectTests {
@Field(type = FieldType.Nested) private List<Car> cars;
@Field(type = FieldType.Nested, includeInParent = true) private List<Car> bestCars;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<GirlFriend> getGirlFriends() {
return girlFriends;
}
public void setGirlFriends(List<GirlFriend> girlFriends) {
this.girlFriends = girlFriends;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public List<Car> getBestCars() {
return bestCars;
}
public void setBestCars(List<Car> bestCars) {
this.bestCars = bestCars;
}
}
/**
* @author Mohsin Husen
*/
@Data
static class GirlFriend {
private String name;
@ -527,56 +444,17 @@ public class NestedObjectTests {
private String type;
@Field(type = FieldType.Nested) private List<Car> cars;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Data
static class Author {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@ -18,12 +18,8 @@ package org.springframework.data.elasticsearch.config.nested;
import static org.junit.Assert.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.Data;
import java.lang.Double;
import java.lang.Long;
@ -31,6 +27,7 @@ import java.lang.Long;
import org.elasticsearch.node.NodeValidationException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -71,22 +68,12 @@ public class EnableNestedElasticsearchRepositoriesTests {
@Autowired(required = false) private SampleRepository nestedRepository;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Test
public void hasNestedRepository() {
assertNotNull(nestedRepository);
}
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Data
@Builder
@Document(indexName = "test-index-sample-config-nested", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {

View File

@ -18,12 +18,7 @@ package org.springframework.data.elasticsearch.config.notnested;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.Data;
import java.lang.Double;
import java.lang.Long;
@ -33,6 +28,7 @@ import org.elasticsearch.node.NodeValidationException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
@ -97,7 +93,6 @@ public class EnableElasticsearchRepositoriesTests implements ApplicationContextA
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
}
@ -126,18 +121,7 @@ public class EnableElasticsearchRepositoriesTests implements ApplicationContextA
assertThat(nestedRepository).isNull();
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Data
@Document(indexName = "test-index-sample-config-not-nested", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntity {
@ -152,20 +136,9 @@ public class EnableElasticsearchRepositoriesTests implements ApplicationContextA
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
/**
* @author Gad Akuka
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
@Document(indexName = "test-index-uuid-keyed-config-not-nested", type = "test-type-uuid-keyed", shards = 1,
replicas = 0, refreshInterval = "-1")
static class SampleEntityUUIDKeyed {
@ -177,10 +150,7 @@ public class EnableElasticsearchRepositoriesTests implements ApplicationContextA
@ScriptedField private Long scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
}
}

View File

@ -22,11 +22,9 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import java.util.HashMap;
@ -37,14 +35,12 @@ import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.AliasBuilder;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
@ -89,7 +85,7 @@ public class AliasTests {
elasticsearchTemplate.createIndex(INDEX_NAME_2, settings);
elasticsearchTemplate.refresh(INDEX_NAME_2);
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
IndexInitializer.init(elasticsearchTemplate, AliasedEntity.class);
}
@Test
@ -141,11 +137,11 @@ public class AliasTests {
elasticsearchTemplate.addAlias(aliasQuery);
String documentId = randomNumeric(5);
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message")
AliasedEntity aliasedEntity = AliasedEntity.builder().id(documentId).message("some message")
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = new IndexQueryBuilder().withIndexName(alias).withId(sampleEntity.getId())
.withType(TYPE_NAME).withObject(sampleEntity).build();
IndexQuery indexQuery = new IndexQueryBuilder().withIndexName(alias).withId(aliasedEntity.getId())
.withType(TYPE_NAME).withObject(aliasedEntity).build();
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(INDEX_NAME_1);
@ -157,7 +153,7 @@ public class AliasTests {
// then
List<AliasMetaData> aliases = elasticsearchTemplate.queryForAlias(INDEX_NAME_1);
assertThat(aliases).isNotNull();
final AliasMetaData aliasMetaData = aliases.get(0);
AliasMetaData aliasMetaData = aliases.get(0);
assertThat(aliasMetaData.alias()).isEqualTo(alias);
assertThat(aliasMetaData.searchRouting()).isEqualTo("0");
assertThat(aliasMetaData.indexRouting()).isEqualTo("0");
@ -185,24 +181,24 @@ public class AliasTests {
elasticsearchTemplate.addAlias(aliasQuery2);
String documentId = randomNumeric(5);
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message")
AliasedEntity aliasedEntity = AliasedEntity.builder().id(documentId).message("some message")
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = new IndexQueryBuilder().withIndexName(alias1).withType(TYPE_NAME)
.withId(sampleEntity.getId()).withObject(sampleEntity).build();
.withId(aliasedEntity.getId()).withObject(aliasedEntity).build();
elasticsearchTemplate.index(indexQuery);
// then
List<AliasMetaData> responseAlias1 = elasticsearchTemplate.queryForAlias(INDEX_NAME_1);
assertThat(responseAlias1).isNotNull();
final AliasMetaData aliasMetaData1 = responseAlias1.get(0);
AliasMetaData aliasMetaData1 = responseAlias1.get(0);
assertThat(aliasMetaData1.alias()).isEqualTo(alias1);
assertThat(aliasMetaData1.indexRouting()).isEqualTo("0");
List<AliasMetaData> responseAlias2 = elasticsearchTemplate.queryForAlias(INDEX_NAME_2);
assertThat(responseAlias2).isNotNull();
final AliasMetaData aliasMetaData2 = responseAlias2.get(0);
AliasMetaData aliasMetaData2 = responseAlias2.get(0);
assertThat(aliasMetaData2.alias()).isEqualTo(alias2);
assertThat(aliasMetaData2.searchRouting()).isEqualTo("1");
@ -212,22 +208,15 @@ public class AliasTests {
}
@Builder
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "test-index-sample-core-alias", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Document(indexName = "test-index-sample-core-alias", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class AliasedEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
}

View File

@ -15,11 +15,12 @@
*/
package org.springframework.data.elasticsearch.core;
import java.util.LinkedList;
import java.util.List;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
@ -52,7 +53,7 @@ public class CustomResultMapper implements ResultsMapper {
}
@Override
public <T> LinkedList<T> mapResults(MultiGetResponse responses, Class<T> clazz) {
public <T> List<T> mapResults(MultiGetResponse responses, Class<T> clazz) {
return null;
}
}

View File

@ -19,15 +19,15 @@ import static org.assertj.core.api.Assertions.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.IOException;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.ReadOnlyProperty;
import org.springframework.data.annotation.Transient;
@ -35,10 +35,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Polygon;
/**
* @author Artur Konczak
@ -64,7 +61,7 @@ public class DefaultEntityMapperTests {
// given
// when
String jsonResult = entityMapper.mapToString(Car.builder().model(CAR_MODEL).name(CAR_NAME).build());
String jsonResult = entityMapper.mapToString(new Car(CAR_NAME, CAR_MODEL));
// then
assertThat(jsonResult).isEqualTo(JSON_STRING);
@ -86,11 +83,11 @@ public class DefaultEntityMapperTests {
@Test
public void shouldMapGeoPointElasticsearchNames() throws IOException {
// given
final Point point = new Point(10, 20);
final String pointAsString = point.getX() + "," + point.getY();
final double[] pointAsArray = { point.getX(), point.getY() };
final GeoEntity geoEntity = GeoEntity.builder().pointA(point).pointB(GeoPoint.fromPoint(point))
.pointC(pointAsString).pointD(pointAsArray).build();
Point point = new Point(10, 20);
String pointAsString = point.getX() + "," + point.getY();
double[] pointAsArray = { point.getX(), point.getY() };
GeoEntity geoEntity = GeoEntity.builder().pointA(point).pointB(GeoPoint.fromPoint(point)).pointC(pointAsString)
.pointD(pointAsArray).build();
// when
String jsonResult = entityMapper.mapToString(geoEntity);
@ -135,43 +132,16 @@ public class DefaultEntityMapperTests {
public String property;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@Data
@AllArgsConstructor
@Builder
@NoArgsConstructor
static class Car {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
/**
* @author Artur Konczak
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ -181,11 +151,6 @@ public class DefaultEntityMapperTests {
@Id private String id;
// geo shape - Spring Data
private Box box;
private Circle circle;
private Polygon polygon;
// geo point - Custom implementation + Spring Data
@GeoPointField private Point pointA;

View File

@ -20,12 +20,9 @@ import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
@ -33,7 +30,7 @@ import java.lang.Object;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.elasticsearch.action.get.GetResponse;
@ -54,6 +51,7 @@ import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
@ -206,7 +204,7 @@ public class DefaultResultMapperTests {
when(response.getSourceAsString()).thenReturn("{}");
when(response.getVersion()).thenReturn(1234L);
SampleEntity result = resultMapper.mapResult(response, SampleEntity.class);
MappedEntity result = resultMapper.mapResult(response, MappedEntity.class);
assertThat(result).isNotNull();
assertThat(result.getVersion()).isEqualTo(1234);
@ -229,7 +227,7 @@ public class DefaultResultMapperTests {
when(multiResponse.getResponses()).thenReturn(new MultiGetItemResponse[] {
new MultiGetItemResponse(response1, null), new MultiGetItemResponse(response2, null) });
LinkedList<SampleEntity> results = resultMapper.mapResults(multiResponse, SampleEntity.class);
List<MappedEntity> results = resultMapper.mapResults(multiResponse, MappedEntity.class);
assertThat(results).isNotNull().hasSize(2);
@ -255,7 +253,7 @@ public class DefaultResultMapperTests {
SearchResponse searchResponse = mock(SearchResponse.class);
when(searchResponse.getHits()).thenReturn(searchHits);
AggregatedPage<SampleEntity> results = resultMapper.mapResults(searchResponse, SampleEntity.class,
AggregatedPage<MappedEntity> results = resultMapper.mapResults(searchResponse, MappedEntity.class,
mock(Pageable.class));
assertThat(results).isNotNull();
@ -288,7 +286,7 @@ public class DefaultResultMapperTests {
private String createJsonCar(String name, String model) {
final String q = "\"";
String q = "\"";
StringBuffer sb = new StringBuffer();
sb.append("{").append(q).append("name").append(q).append(":").append(q).append(name).append(q).append(",");
sb.append(q).append("model").append(q).append(":").append(q).append(model).append(q).append("}");
@ -311,52 +309,16 @@ public class DefaultResultMapperTests {
private final String id, name;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
static class Car {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-default-result-mapper", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Data
@Document(indexName = "test-index-sample-default-result-mapper", type = "test-type")
static class MappedEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@ -368,49 +330,6 @@ public class DefaultResultMapperTests {
private GeoPoint location;
@Version private Long version;
@Score private float score;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
}

View File

@ -24,7 +24,6 @@ import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import java.io.IOException;
import java.util.ArrayList;
@ -39,6 +38,7 @@ import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.data.annotation.Id;
@ -210,11 +210,11 @@ public class ElasticsearchEntityMapperUnitTests {
@Test // DATAES-530
public void shouldMapGeoPointElasticsearchNames() throws IOException {
// given
final Point point = new Point(10, 20);
final String pointAsString = point.getX() + "," + point.getY();
final double[] pointAsArray = { point.getX(), point.getY() };
final GeoEntity geoEntity = GeoEntity.builder().pointA(point).pointB(GeoPoint.fromPoint(point))
.pointC(pointAsString).pointD(pointAsArray).build();
Point point = new Point(10, 20);
String pointAsString = point.getX() + "," + point.getY();
double[] pointAsArray = { point.getX(), point.getY() };
GeoEntity geoEntity = GeoEntity.builder().pointA(point).pointB(GeoPoint.fromPoint(point)).pointC(pointAsString)
.pointD(pointAsArray).build();
// when
String jsonResult = entityMapper.mapToString(geoEntity);
@ -682,13 +682,7 @@ public class ElasticsearchEntityMapperUnitTests {
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ -696,29 +690,9 @@ public class ElasticsearchEntityMapperUnitTests {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
/**
* @author Artur Konczak
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder

View File

@ -18,29 +18,18 @@ package org.springframework.data.elasticsearch.core;
import static org.apache.commons.lang.RandomStringUtils.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import lombok.Data;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder;
import org.springframework.test.context.ContextConfiguration;
@ -75,73 +64,13 @@ public class ElasticsearchRestTemplateTests extends ElasticsearchTemplateTests {
elasticsearchTemplate.update(updateQuery);
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Data
@Builder
@Document(indexName = "test-index-sample-core-rest-template", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
@Document(indexName = "test-index-sample-core-rest-template", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
}

View File

@ -105,7 +105,7 @@ public class ElasticsearchTemplateParentChildTests {
XContentBuilder builder;
builder = jsonBuilder().startObject().field("name", newChildName).endObject();
updateRequest.doc(builder);
final UpdateResponse response = update(updateRequest);
UpdateResponse response = update(updateRequest);
assertThat(response.getShardInfo().getSuccessful()).isEqualTo(1);
}
@ -170,7 +170,7 @@ public class ElasticsearchTemplateParentChildTests {
private UpdateResponse update(UpdateRequest updateRequest) {
final UpdateQuery update = new UpdateQuery();
UpdateQuery update = new UpdateQuery();
update.setId(updateRequest.id());
update.setType(updateRequest.type());
update.setIndexName(updateRequest.index());

View File

@ -23,10 +23,9 @@ import static org.springframework.data.elasticsearch.utils.IndexBuilder.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Integer;
@ -44,8 +43,6 @@ import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.assertj.core.util.Lists;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
@ -65,6 +62,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
@ -259,7 +257,7 @@ public class ElasticsearchTemplateTests {
// when
SearchQuery query = new NativeSearchQueryBuilder().withIds(Arrays.asList(documentId, documentId2)).build();
LinkedList<SampleEntity> sampleEntities = elasticsearchTemplate.multiGet(query, SampleEntity.class);
List<SampleEntity> sampleEntities = elasticsearchTemplate.multiGet(query, SampleEntity.class);
// then
assertThat(sampleEntities).hasSize(2);
@ -289,7 +287,7 @@ public class ElasticsearchTemplateTests {
// when
SearchQuery query = new NativeSearchQueryBuilder().withIds(Arrays.asList(documentId, documentId2))
.withFields("message", "type").build();
LinkedList<SampleEntity> sampleEntities = elasticsearchTemplate.multiGet(query, SampleEntity.class,
List<SampleEntity> sampleEntities = elasticsearchTemplate.multiGet(query, SampleEntity.class,
new MultiGetResultMapper() {
@Override
public <T> LinkedList<T> mapResults(MultiGetResponse responses, Class<T> clazz) {
@ -893,7 +891,7 @@ public class ElasticsearchTemplateTests {
// when
boolean created = elasticsearchTemplate.createIndex(SampleEntity.class);
elasticsearchTemplate.putMapping(SampleEntity.class);
final Map setting = elasticsearchTemplate.getSetting(SampleEntity.class);
Map setting = elasticsearchTemplate.getSetting(SampleEntity.class);
// then
assertThat(created).isTrue();
@ -1470,7 +1468,7 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class);
final List<HighlightBuilder.Field> message = new HighlightBuilder().field("message").fields();
List<HighlightBuilder.Field> message = new HighlightBuilder().field("message").fields();
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test"))
.withHighlightFields(message.toArray(new HighlightBuilder.Field[message.size()])).build();
@ -1878,7 +1876,7 @@ public class ElasticsearchTemplateTests {
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
assertThat(sampleEntities.getTotalElements()).isEqualTo(2);
final List<SampleEntity> content = sampleEntities.getContent();
List<SampleEntity> content = sampleEntities.getContent();
assertThat(content.get(0).getId()).isNotNull();
assertThat(content.get(1).getId()).isNotNull();
}
@ -1949,7 +1947,7 @@ public class ElasticsearchTemplateTests {
});
assertThat(sampleEntities.getTotalElements()).isEqualTo(2);
final List<Map> content = sampleEntities.getContent();
List<Map> content = sampleEntities.getContent();
assertThat(content.get(0).get("userId")).isEqualTo(person1.get("userId"));
assertThat(content.get(1).get("userId")).isEqualTo(person2.get("userId"));
}
@ -2456,7 +2454,7 @@ public class ElasticsearchTemplateTests {
// then
assertThat(created).isTrue();
final Map setting = elasticsearchTemplate.getSetting(UseServerConfigurationEntity.class);
Map setting = elasticsearchTemplate.getSetting(UseServerConfigurationEntity.class);
assertThat(setting.get("index.number_of_shards")).isEqualTo("5");
assertThat(setting.get("index.number_of_replicas")).isEqualTo("1");
}
@ -2471,9 +2469,8 @@ public class ElasticsearchTemplateTests {
String content = ElasticsearchTemplate.readFileFromClasspath(settingsFile);
// then
assertThat(content).isEqualTo(
"index:\n" + " number_of_shards: 1\n" + " number_of_replicas: 0\n" + " analysis:\n" + " analyzer:\n"
+ " emailAnalyzer:\n" + " type: custom\n" + " tokenizer: uax_url_email\n");
assertThat(content).isEqualTo("index:\n" + " number_of_shards: 1\n" + " number_of_replicas: 0\n" + " analysis:\n"
+ " analyzer:\n" + " emailAnalyzer:\n" + " type: custom\n" + " tokenizer: uax_url_email");
}
@Test // DATAES-531
@ -2484,7 +2481,7 @@ public class ElasticsearchTemplateTests {
// when
boolean created = elasticsearchTemplate.createIndex(SampleEntity.class);
elasticsearchTemplate.putMapping(SampleEntity.class);
final Map<String, Object> mapping = elasticsearchTemplate.getMapping(SampleEntity.class);
Map<String, Object> mapping = elasticsearchTemplate.getMapping(SampleEntity.class);
// then
assertThat(created).isTrue();
@ -2717,13 +2714,11 @@ public class ElasticsearchTemplateTests {
.withSort(new FieldSortBuilder("message").order(SortOrder.DESC)).withPageable(PageRequest.of(0, 10)).build();
// when
ScrolledPage<SampleEntity> scroll = (ScrolledPage<SampleEntity>) elasticsearchTemplate.startScroll(1000,
searchQuery, SampleEntity.class);
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(1000, searchQuery, SampleEntity.class);
List<SampleEntity> sampleEntities = new ArrayList<>();
while (scroll.hasContent()) {
sampleEntities.addAll(scroll.getContent());
scroll = (ScrolledPage<SampleEntity>) elasticsearchTemplate.continueScroll(scroll.getScrollId(), 1000,
SampleEntity.class);
scroll = elasticsearchTemplate.continueScroll(scroll.getScrollId(), 1000, SampleEntity.class);
}
// then
@ -2766,13 +2761,11 @@ public class ElasticsearchTemplateTests {
.build();
// when
ScrolledPage<SampleEntity> scroll = (ScrolledPage<SampleEntity>) elasticsearchTemplate.startScroll(1000,
searchQuery, SampleEntity.class);
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(1000, searchQuery, SampleEntity.class);
List<SampleEntity> sampleEntities = new ArrayList<>();
while (scroll.hasContent()) {
sampleEntities.addAll(scroll.getContent());
scroll = (ScrolledPage<SampleEntity>) elasticsearchTemplate.continueScroll(scroll.getScrollId(), 1000,
SampleEntity.class);
scroll = elasticsearchTemplate.continueScroll(scroll.getScrollId(), 1000, SampleEntity.class);
}
// then
@ -2811,17 +2804,10 @@ public class ElasticsearchTemplateTests {
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@EqualsAndHashCode(exclude = "score")
@Builder
@Document(indexName = INDEX_NAME_SAMPLE_ENTITY, type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@ -2837,49 +2823,6 @@ public class ElasticsearchTemplateTests {
private GeoPoint location;
@Version private Long version;
@Score private float score;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
/**
@ -2887,14 +2830,12 @@ public class ElasticsearchTemplateTests {
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Setter
@Getter
@NoArgsConstructor
@Data
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-uuid-keyed-core-template", type = "test-type-uuid-keyed", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntityUUIDKeyed {
private static class SampleEntityUUIDKeyed {
@Id private UUID id;
private String type;
@ -2908,60 +2849,12 @@ public class ElasticsearchTemplateTests {
@Version private Long version;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntityUUIDKeyed that = (SampleEntityUUIDKeyed) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Nordine Bittich
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "test-index-book-core-template", type = "book", shards = 1, replicas = 0,
refreshInterval = "-1")
static class Book {
@ -2975,44 +2868,20 @@ public class ElasticsearchTemplateTests {
searchAnalyzer = "standard") }) private String description;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Data
static class Author {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* @author Ivan Greene
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "test-index-version-core-template", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1", versionType = VersionType.EXTERNAL_GTE)
static class GTEVersionEntity {
private static class GTEVersionEntity {
@Version private Long version;
@ -3021,10 +2890,7 @@ public class ElasticsearchTemplateTests {
private String name;
}
/**
* @author Abdul Waheed
* @author Mohsin Husen
*/
@Data
@Document(indexName = "test-index-hetro1-core-template", type = "hetro", replicas = 0, shards = 1)
static class HetroEntity1 {
@ -3032,59 +2898,14 @@ public class ElasticsearchTemplateTests {
private String firstName;
@Version private Long version;
public HetroEntity1(String id, String firstName) {
HetroEntity1(String id, String firstName) {
this.id = id;
this.firstName = firstName;
this.version = System.currentTimeMillis();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SampleEntity)) {
return false;
}
if (this == obj) {
return true;
}
HetroEntity1 rhs = (HetroEntity1) obj;
return new EqualsBuilder().append(this.id, rhs.id).append(this.firstName, rhs.firstName)
.append(this.version, rhs.version).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(id).append(firstName).append(version).toHashCode();
}
}
/**
* @author Abdul Waheed
* @author Mohsin Husen
*/
@Data
@Document(indexName = "test-index-hetro2-core-template", type = "hetro", replicas = 0, shards = 1)
static class HetroEntity2 {
@ -3092,77 +2913,24 @@ public class ElasticsearchTemplateTests {
private String lastName;
@Version private Long version;
public HetroEntity2(String id, String lastName) {
HetroEntity2(String id, String lastName) {
this.id = id;
this.lastName = lastName;
this.version = System.currentTimeMillis();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SampleEntity)) {
return false;
}
if (this == obj) {
return true;
}
HetroEntity2 rhs = (HetroEntity2) obj;
return new EqualsBuilder().append(this.id, rhs.id).append(this.lastName, rhs.lastName)
.append(this.version, rhs.version).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(id).append(lastName).append(version).toHashCode();
}
}
/**
* Created by akonczak on 12/12/2015.
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
@Document(indexName = "test-index-server-configuration", type = "test-type", useServerConfiguration = true,
shards = 10, replicas = 10, refreshInterval = "-1")
static class UseServerConfigurationEntity {
private static class UseServerConfigurationEntity {
@Id private String id;
private String val;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Data
@Document(indexName = "test-index-sample-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleMappingEntity {
@ -3170,24 +2938,6 @@ public class ElasticsearchTemplateTests {
@Field(type = Text, index = false, store = true, analyzer = "standard") private String message;
private SampleMappingEntity.NestedEntity nested;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
static class NestedEntity {
@Field(type = Text) private String someField;

View File

@ -18,28 +18,17 @@ package org.springframework.data.elasticsearch.core;
import static org.apache.commons.lang.RandomStringUtils.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.engine.DocumentMissingException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder;
import org.springframework.test.context.ContextConfiguration;
@ -62,30 +51,12 @@ public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTe
elasticsearchTemplate.update(updateQuery);
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-core-transport-template", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
@Data
@Document(indexName = "test-index-sample-core-transport-template", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
}

View File

@ -19,6 +19,8 @@ import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
@ -29,6 +31,7 @@ import org.elasticsearch.action.search.SearchPhaseExecutionException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@ -111,11 +114,8 @@ public class LogEntityTests {
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
@Data
@Document(indexName = "test-index-log-core", type = "test-log-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class LogEntity {
@ -137,50 +137,6 @@ public class LogEntityTests {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAction() {
return action;
}
public String toString() {
return new StringBuffer().append("{id:").append(id).append(",action:").append(action).append(",code:")
.append(sequenceCode).append(",date:").append(format.format(date)).append("}").toString();
}
public void setAction(String action) {
this.action = action;
}
public long getSequenceCode() {
return sequenceCode;
}
public void setSequenceCode(long sequenceCode) {
this.sequenceCode = sequenceCode;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
/**
@ -189,7 +145,6 @@ public class LogEntityTests {
* @author Artur Konczak
* @author Mohsin Husen
*/
static class LogEntityBuilder {
private LogEntity result;

View File

@ -22,14 +22,11 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import java.net.ConnectException;
@ -47,6 +44,7 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.data.annotation.Id;
@ -60,8 +58,6 @@ import org.springframework.data.elasticsearch.TestUtils;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
@ -78,8 +74,8 @@ import org.springframework.util.StringUtils;
*
* @author Christoph Strobl
* @author Mark Paluch
* @currentRead Golden Fool - Robin Hobb
* @author Peter-Josef Meisch
* @currentRead Golden Fool - Robin Hobb
*/
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:infrastructure.xml")
@ -689,73 +685,17 @@ public class ReactiveElasticsearchTemplateTests {
String message;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@EqualsAndHashCode(exclude = "score")
@Document(indexName = DEFAULT_INDEX, type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
}

View File

@ -22,10 +22,8 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
@ -49,13 +47,13 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
@ -255,13 +253,12 @@ public class ReactiveElasticsearchTemplateUnitTests {
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-core-reactive-template-Unit", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
@Document(indexName = "test-index-sample-core-reactive-template-Unit", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@ -273,49 +270,5 @@ public class ReactiveElasticsearchTemplateUnitTests {
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
}

View File

@ -1,6 +1,21 @@
/*
* Copyright 2018-2019 the original author or authors.
*
* Licensed 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
*
* https://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.
*/
package org.springframework.data.elasticsearch.core;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.io.IOException;
import java.util.HashMap;
@ -8,6 +23,7 @@ import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.DynamicTemplates;
@ -36,7 +52,7 @@ public class SimpleDynamicTemplatesMappingTests extends MappingContextBaseTests
+ "\"mapping\":{\"type\":\"string\",\"analyzer\":\"standard_lowercase_asciifolding\"},"
+ "\"path_match\":\"names.*\"}}]," + "\"properties\":{\"names\":{\"type\":\"object\"}}}}";
assertEquals(EXPECTED_MAPPING_ONE, mapping);
assertThat(mapping).isEqualTo(EXPECTED_MAPPING_ONE);
}
@Test // DATAES-568
@ -50,7 +66,7 @@ public class SimpleDynamicTemplatesMappingTests extends MappingContextBaseTests
+ "\"mapping\":{\"type\":\"string\",\"analyzer\":\"standard_lowercase_asciifolding\"},"
+ "\"path_match\":\"participantA1.*\"}}]," + "\"properties\":{\"names\":{\"type\":\"object\"}}}}";
assertEquals(EXPECTED_MAPPING_TWO, mapping);
assertThat(mapping).isEqualTo(EXPECTED_MAPPING_TWO);
}
/**

View File

@ -15,13 +15,16 @@
*/
package org.springframework.data.elasticsearch.core;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.Data;
import java.io.IOException;
import java.util.Date;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
@ -46,12 +49,13 @@ public class SimpleElasticsearchDateMappingTests extends MappingContextBaseTests
String mapping = getMappingBuilder().buildPropertyMapping(SampleDateMappingEntity.class);
assertEquals(EXPECTED_MAPPING, mapping);
assertThat(mapping).isEqualTo(EXPECTED_MAPPING);
}
/**
* @author Jakub Vavrik
*/
@Data
@Document(indexName = "test-index-date-mapping-core", type = "mapping", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleDateMappingEntity {
@ -66,45 +70,5 @@ public class SimpleElasticsearchDateMappingTests extends MappingContextBaseTests
@Field(type = FieldType.Date) private Date defaultFormatDate;
@Field(type = FieldType.Date, format = DateFormat.basic_date) private Date basicFormatDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getCustomFormatDate() {
return customFormatDate;
}
public void setCustomFormatDate(Date customFormatDate) {
this.customFormatDate = customFormatDate;
}
public Date getDefaultFormatDate() {
return defaultFormatDate;
}
public void setDefaultFormatDate(Date defaultFormatDate) {
this.defaultFormatDate = defaultFormatDate;
}
public Date getBasicFormatDate() {
return basicFormatDate;
}
public void setBasicFormatDate(Date basicFormatDate) {
this.basicFormatDate = basicFormatDate;
}
}
}

View File

@ -21,6 +21,8 @@ import static org.elasticsearch.search.aggregations.AggregationBuilders.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.Integer;
import lombok.Data;
import java.lang.Integer;
import java.util.ArrayList;
import java.util.List;
@ -32,6 +34,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@ -58,14 +61,14 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class ElasticsearchTemplateAggregationTests {
public static final String RIZWAN_IDREES = "Rizwan Idrees";
public static final String MOHSIN_HUSEN = "Mohsin Husen";
public static final String JONATHAN_YAN = "Jonathan Yan";
public static final String ARTUR_KONCZAK = "Artur Konczak";
public static final int YEAR_2002 = 2002;
public static final int YEAR_2001 = 2001;
public static final int YEAR_2000 = 2000;
public static final String INDEX_NAME = "test-index-articles-core-aggregation";
static final String RIZWAN_IDREES = "Rizwan Idrees";
static final String MOHSIN_HUSEN = "Mohsin Husen";
static final String JONATHAN_YAN = "Jonathan Yan";
static final String ARTUR_KONCZAK = "Artur Konczak";
static final int YEAR_2002 = 2002;
static final int YEAR_2001 = 2001;
static final int YEAR_2000 = 2000;
static final String INDEX_NAME = "test-index-articles-core-aggregation";
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@ -128,7 +131,9 @@ public class ElasticsearchTemplateAggregationTests {
* @author Artur Konczak
* @author Mohsin Husen
*/
@Document(indexName = "test-index-articles-core-aggregation", type = "article", shards = 1, replicas = 0, refreshInterval = "-1")
@Data
@Document(indexName = "test-index-articles-core-aggregation", type = "article", shards = 1, replicas = 0,
refreshInterval = "-1")
static class ArticleEntity {
@Id private String id;
@ -152,54 +157,6 @@ public class ElasticsearchTemplateAggregationTests {
public ArticleEntity(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public List<Integer> getPublishedYears() {
return publishedYears;
}
public void setPublishedYears(List<Integer> publishedYears) {
this.publishedYears = publishedYears;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
/**

View File

@ -131,7 +131,7 @@ public class ElasticsearchTemplateCompletionTests {
Fuzziness.AUTO);
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), CompletionEntity.class);
CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest");
List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getEntries().get(0).getOptions();
@ -151,7 +151,7 @@ public class ElasticsearchTemplateCompletionTests {
Fuzziness.AUTO);
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), CompletionEntity.class);
CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest");
List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getEntries().get(0).getOptions();
@ -171,7 +171,7 @@ public class ElasticsearchTemplateCompletionTests {
Fuzziness.AUTO);
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder),
AnnotatedCompletionEntity.class);
CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest");

View File

@ -112,7 +112,7 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
Map<String, List<? extends ToXContent>> contextMap = new HashMap<>();
List<CategoryQueryContext> contexts = new ArrayList<>(1);
final CategoryQueryContext.Builder builder = CategoryQueryContext.builder();
CategoryQueryContext.Builder builder = CategoryQueryContext.builder();
builder.setCategory("mongo");
CategoryQueryContext queryContext = builder.build();
contexts.add(queryContext);
@ -121,7 +121,7 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
((CompletionSuggestionBuilder) completionSuggestionFuzzyBuilder).contexts(contextMap);
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder),
ContextCompletionEntity.class);
assertThat(suggestResponse.getSuggest()).isNotNull();
@ -144,7 +144,7 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
Map<String, List<? extends ToXContent>> contextMap = new HashMap<>();
List<CategoryQueryContext> contexts = new ArrayList<>(1);
final CategoryQueryContext.Builder builder = CategoryQueryContext.builder();
CategoryQueryContext.Builder builder = CategoryQueryContext.builder();
builder.setCategory("elastic");
CategoryQueryContext queryContext = builder.build();
contexts.add(queryContext);
@ -153,7 +153,7 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
((CompletionSuggestionBuilder) completionSuggestionFuzzyBuilder).contexts(contextMap);
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder),
ContextCompletionEntity.class);
assertThat(suggestResponse.getSuggest()).isNotNull();
@ -176,7 +176,7 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
Map<String, List<? extends ToXContent>> contextMap = new HashMap<>();
List<CategoryQueryContext> contexts = new ArrayList<>(1);
final CategoryQueryContext.Builder builder = CategoryQueryContext.builder();
CategoryQueryContext.Builder builder = CategoryQueryContext.builder();
builder.setCategory("kotlin");
CategoryQueryContext queryContext = builder.build();
contexts.add(queryContext);
@ -185,7 +185,7 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
((CompletionSuggestionBuilder) completionSuggestionFuzzyBuilder).contexts(contextMap);
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder),
ContextCompletionEntity.class);
assertThat(suggestResponse.getSuggest()).isNotNull();

View File

@ -19,12 +19,15 @@ package org.springframework.data.elasticsearch.core.facet;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@ -672,7 +675,9 @@ public class ElasticsearchTemplateFacetTests {
* @author Artur Konczak
* @author Mohsin Husen
*/
@Document(indexName = "test-index-articles-core-facet", type = "article", shards = 1, replicas = 0, refreshInterval = "-1")
@Data
@Document(indexName = "test-index-articles-core-facet", type = "article", shards = 1, replicas = 0,
refreshInterval = "-1")
static class ArticleEntity {
@Id private String id;
@ -697,54 +702,6 @@ public class ElasticsearchTemplateFacetTests {
public ArticleEntity(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public List<Integer> getPublishedYears() {
return publishedYears;
}
public void setPublishedYears(List<Integer> publishedYears) {
this.publishedYears = publishedYears;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
/**

View File

@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@ -360,6 +361,7 @@ public class ElasticsearchTemplateGeoTests {
* @author Franck Marchand
* @author Mohsin Husen
*/
@Data
@Document(indexName = "test-index-author-marker-core-geo", type = "geo-class-point-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class AuthorMarkerEntity {
@ -374,30 +376,6 @@ public class ElasticsearchTemplateGeoTests {
public AuthorMarkerEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GeoPoint getLocation() {
return location;
}
public void setLocation(GeoPoint location) {
this.location = location;
}
}
/**

View File

@ -24,7 +24,7 @@ import org.springframework.data.mapping.MappingException;
/**
* Unit tests for {@link SimpleElasticsearchPersistentProperty}.
*
*
* @author Oliver Gierke
* @author Peter-Josef Meisch
*/
@ -43,8 +43,9 @@ public class SimpleElasticsearchPersistentPropertyUnitTests {
@Test // DATAES-562
public void fieldAnnotationWithNameSetsFieldname() {
final SimpleElasticsearchPersistentEntity<?> persistentEntity = context.getRequiredPersistentEntity(FieldNameProperty.class);
final ElasticsearchPersistentProperty persistentProperty = persistentEntity.getPersistentProperty("fieldProperty");
SimpleElasticsearchPersistentEntity<?> persistentEntity = context
.getRequiredPersistentEntity(FieldNameProperty.class);
ElasticsearchPersistentProperty persistentProperty = persistentEntity.getPersistentProperty("fieldProperty");
assertThat(persistentProperty).isNotNull();
assertThat(persistentProperty.getFieldName()).isEqualTo("by-name");
@ -53,8 +54,9 @@ public class SimpleElasticsearchPersistentPropertyUnitTests {
@Test // DATAES-562
public void fieldAnnotationWithValueSetsFieldname() {
final SimpleElasticsearchPersistentEntity<?> persistentEntity = context.getRequiredPersistentEntity(FieldValueProperty.class);
final ElasticsearchPersistentProperty persistentProperty = persistentEntity.getPersistentProperty("fieldProperty");
SimpleElasticsearchPersistentEntity<?> persistentEntity = context
.getRequiredPersistentEntity(FieldValueProperty.class);
ElasticsearchPersistentProperty persistentProperty = persistentEntity.getPersistentProperty("fieldProperty");
assertThat(persistentProperty).isNotNull();
assertThat(persistentProperty.getFieldName()).isEqualTo("by-value");

View File

@ -26,7 +26,6 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.lang.Double;
import java.lang.Long;
import java.util.ArrayList;
import java.util.List;
@ -34,6 +33,7 @@ import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
@ -41,9 +41,7 @@ import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -805,18 +803,14 @@ public class CriteriaQueryTests {
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "test-index-sample-core-query", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
@Document(indexName = "test-index-sample-core-query", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@org.springframework.data.elasticsearch.annotations.Field(type = Text, store = true,
fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}

View File

@ -19,9 +19,8 @@ import static org.assertj.core.api.Assertions.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Collection;
import java.util.Date;
@ -36,6 +35,7 @@ import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
@ -155,8 +155,7 @@ public class CdiRepositoryTests {
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ -187,42 +186,11 @@ public class CdiRepositoryTests {
private String location;
private Date lastModified;
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Product other = (Product) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Document(indexName = "test-index-person-cdi-repository", type = "user", shards = 1, replicas = 0, refreshInterval = "-1")
@Data
@Document(indexName = "test-index-person-cdi-repository", type = "user", shards = 1, replicas = 0,
refreshInterval = "-1")
static class Person {
@Id private String id;
@ -233,50 +201,14 @@ public class CdiRepositoryTests {
@Field(type = FieldType.Nested, includeInParent = true) private List<Book> books;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Car> getCar() {
return car;
}
public void setCar(List<Car> car) {
this.car = car;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Nordine Bittich
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-book-cdi-repository", type = "book", shards = 1, replicas = 0, refreshInterval = "-1")
@Document(indexName = "test-index-book-cdi-repository", type = "book", shards = 1, replicas = 0,
refreshInterval = "-1")
static class Book {
@Id private String id;
@ -288,13 +220,7 @@ public class CdiRepositoryTests {
searchAnalyzer = "standard") }) private String description;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ -302,48 +228,13 @@ public class CdiRepositoryTests {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Data
static class Author {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@ -18,28 +18,17 @@ package org.springframework.data.elasticsearch.repositories.complex.custommethod
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import lombok.Data;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -59,7 +48,6 @@ public class ComplexCustomMethodRepositoryTests {
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
}
@ -75,31 +63,14 @@ public class ComplexCustomMethodRepositoryTests {
assertThat(result).isEqualTo("2+2=4");
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-repositories-complex-custommethod-autowiring", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
@Data
@Document(indexName = "test-index-sample-repositories-complex-custommethod-autowiring", type = "test-type",
shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
}

View File

@ -18,28 +18,17 @@ package org.springframework.data.elasticsearch.repositories.complex.custommethod
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import lombok.Data;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -58,8 +47,7 @@ public class ComplexCustomMethodRepositoryManualWiringTests {
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate,SampleEntity.class);
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
}
@Test
@ -74,31 +62,13 @@ public class ComplexCustomMethodRepositoryManualWiringTests {
assertThat(result).isEqualTo("3+3=6");
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-repository-manual-wiring", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
@Data
@Document(indexName = "test-index-sample-repository-manual-wiring", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
}

View File

@ -21,12 +21,9 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import java.util.ArrayList;
import java.util.Arrays;
@ -35,6 +32,7 @@ import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
@ -46,8 +44,6 @@ import org.springframework.data.domain.Sort.Order;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoBox;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
@ -1256,31 +1252,21 @@ public abstract class CustomMethodRepositoryBaseTests {
return entities;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-repositories-custo-method", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
@Document(indexName = "test-index-sample-repositories-custo-method", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
/**

View File

@ -36,7 +36,6 @@ public class CustomMethodRepositoryRestTests extends CustomMethodRepositoryBaseT
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
}
}

View File

@ -36,7 +36,6 @@ public class CustomMethodRepositoryTests extends CustomMethodRepositoryBaseTests
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
}
}

View File

@ -52,7 +52,6 @@ public class DoubleIDRepositoryTests {
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, DoubleIDEntity.class);
}

View File

@ -59,7 +59,6 @@ public class SpringDataGeoRepositoryTests {
@Before
public void init() {
IndexInitializer.init(template, GeoEntity.class);
}
@ -67,7 +66,7 @@ public class SpringDataGeoRepositoryTests {
public void shouldSaveAndLoadGeoPoints() {
// given
final Point point = new Point(15, 25);
Point point = new Point(15, 25);
GeoEntity entity = GeoEntity.builder().pointA(point).pointB(new GeoPoint(point.getX(), point.getY()))
.pointC(toGeoString(point)).pointD(toGeoArray(point)).build();

View File

@ -51,7 +51,6 @@ public class IntegerIDRepositoryTests {
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, IntegerIDEntity.class);
}

View File

@ -60,7 +60,6 @@ public class InnerObjectTests {
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, Book.class);
}

View File

@ -55,7 +55,6 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, DynamicSettingAndMappingEntity.class);
}

View File

@ -21,9 +21,10 @@ import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Mapping;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
@ -48,7 +49,6 @@ public class FieldDynamicMappingEntityRepositoryTests {
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, FieldDynamicMappingEntity.class);
}

View File

@ -48,7 +48,6 @@ public class SpELEntityTests {
@Before
public void before() {
IndexInitializer.init(template, SpELEntity.class);
}

View File

@ -17,12 +17,15 @@ package org.springframework.data.elasticsearch.repositories.synonym;
import static org.assertj.core.api.Assertions.*;
import lombok.Data;
import java.util.List;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
@ -51,7 +54,6 @@ public class SynonymRepositoryTests {
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, SynonymEntity.class);
}
@ -81,6 +83,7 @@ public class SynonymRepositoryTests {
/**
* @author Mohsin Husen
*/
@Data
@Document(indexName = "test-index-synonym", type = "synonym-type")
@Setting(settingPath = "/synonyms/settings.json")
@Mapping(mappingPath = "/synonyms/mappings.json")
@ -88,22 +91,6 @@ public class SynonymRepositoryTests {
@Id private String id;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
/**

View File

@ -20,13 +20,11 @@ import static org.elasticsearch.index.query.QueryBuilders.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@ -34,6 +32,7 @@ import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
@ -246,8 +245,8 @@ public class UUIDElasticsearchRepositoryTests {
repository.save(sampleEntityUUIDKeyed2);
// when
final List<UUID> docIds = Arrays.asList(documentId, documentId2);
LinkedList<SampleEntityUUIDKeyed> sampleEntities = (LinkedList<SampleEntityUUIDKeyed>) repository
List<UUID> docIds = Arrays.asList(documentId, documentId2);
List<SampleEntityUUIDKeyed> sampleEntities = (List<SampleEntityUUIDKeyed>) repository
.findAllById(docIds);
// then
@ -582,17 +581,10 @@ public class UUIDElasticsearchRepositoryTests {
return sampleEntities;
}
/**
* @author Gad Akuka
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
@Document(indexName = "test-index-uuid-keyed", type = "test-type-uuid-keyed", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntityUUIDKeyed {
@ -608,49 +600,6 @@ public class UUIDElasticsearchRepositoryTests {
private GeoPoint location;
@Version private Long version;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntityUUIDKeyed that = (SampleEntityUUIDKeyed) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
/**

View File

@ -19,30 +19,22 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.TestUtils;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.repository.ReactiveElasticsearchRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -79,30 +71,16 @@ public class ReactiveElasticsearchRepositoriesRegistrarTests {
interface ReactiveSampleEntityRepository extends ReactiveElasticsearchRepository<SampleEntity, String> {}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-reactive-repositories-registrar", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
@Document(indexName = "test-index-sample-reactive-repositories-registrar", type = "test-type", shards = 1,
replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
}

View File

@ -20,22 +20,15 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.lang.Boolean;
import java.lang.Long;
import java.lang.Object;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
@ -47,16 +40,23 @@ import org.elasticsearch.action.support.WriteRequest.RefreshPolicy;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.elasticsearch.TestUtils;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import org.springframework.data.elasticsearch.config.AbstractReactiveElasticsearchConfiguration;
import org.springframework.data.elasticsearch.repository.config.EnableReactiveElasticsearchRepositories;
@ -509,31 +509,20 @@ public class SimpleReactiveElasticsearchRepositoryTests {
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = INDEX, type = TYPE, shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id
private String id;
@Field(type = Text, store = true, fielddata = true)
private String type;
@Field(type = Text, store = true, fielddata = true)
private String message;
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField
private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version
private Long version;
@Score
private float score;
@Version private Long version;
@Score private float score;
}
}

View File

@ -22,14 +22,10 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@ -39,6 +35,7 @@ import org.elasticsearch.action.ActionRequestValidationException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
@ -48,10 +45,7 @@ import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
@ -77,7 +71,6 @@ public class SimpleElasticsearchRepositoryTests {
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
}
@ -640,68 +633,20 @@ public class SimpleElasticsearchRepositoryTests {
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-simple-repository", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
@Document(indexName = "test-index-sample-simple-repository", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
/**

View File

@ -6,13 +6,22 @@ package org.springframework.data.elasticsearch.utils;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
/**
* Utility to initialize indexes.
*
* @author Peter-Josef Meisch
*/
final public class IndexInitializer {
public class IndexInitializer {
private IndexInitializer() {}
/**
* Initialize a fresh index with mappings for {@link Class}. Drops the index if it exists before creation.
*
* @param operations
* @param clazz
*/
public static void init(ElasticsearchOperations operations, Class<?> clazz) {
operations.deleteIndex(clazz);
operations.createIndex(clazz);
operations.putMapping(clazz);

View File

@ -12,7 +12,6 @@
<constructor-arg name="client" ref="client"/>
</bean>
<elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repositories.doubleid"
consider-nested-repositories="true"/>

View File

@ -12,7 +12,6 @@
<constructor-arg name="client" ref="client"/>
</bean>
<elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repositories.existing.index"
consider-nested-repositories="true" />

View File

@ -12,7 +12,6 @@
<constructor-arg name="client" ref="client"/>
</bean>
<elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.immutable"
consider-nested-repositories="true"/>

View File

@ -12,7 +12,6 @@
<constructor-arg name="client" ref="client"/>
</bean>
<elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repositories.integer"
consider-nested-repositories="true" />

View File

@ -12,7 +12,6 @@
<constructor-arg name="client" ref="client"/>
</bean>
<elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repository.query.keywords"
consider-nested-repositories="true"/>

View File

@ -12,7 +12,6 @@
<constructor-arg name="client" ref="client"/>
</bean>
<elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repository.support.simple"
consider-nested-repositories="true"/>

View File

@ -12,7 +12,6 @@
<constructor-arg name="client" ref="client"/>
</bean>
<elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repositories.spel"
consider-nested-repositories="true" />

View File

@ -12,7 +12,6 @@
<constructor-arg name="client" ref="client"/>
</bean>
<elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repositories.uuidkeyed"
consider-nested-repositories="true"/>