DATAES-721 - Deprecation and Warnings cleanup.

Original PR: #367
This commit is contained in:
Peter-Josef Meisch 2019-12-29 21:46:58 +01:00 committed by GitHub
parent a68c6ba5d7
commit d026884c12
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
123 changed files with 895 additions and 825 deletions

View File

@ -82,7 +82,7 @@ Consider the following:
==== ====
[source,java] [source,java]
---- ----
@Document(indexName = "marvel", type = "characters") @Document(indexName = "marvel")
public class Person { public class Person {
private @Id String id; private @Id String id;

View File

@ -20,8 +20,8 @@ package org.springframework.data.elasticsearch.annotations;
* @since 4.0 * @since 4.0
*/ */
public @interface IndexPrefixes { public @interface IndexPrefixes {
static final int MIN_DEFAULT = 2; int MIN_DEFAULT = 2;
static final int MAX_DEFAULT = 2; int MAX_DEFAULT = 2;
int minChars() default MIN_DEFAULT; int minChars() default MIN_DEFAULT;

View File

@ -66,7 +66,7 @@ class ClusterNodes implements Streamable<TransportAddress> {
Assert.hasText(host, () -> String.format("No host name given cluster node %s!", node)); Assert.hasText(host, () -> String.format("No host name given cluster node %s!", node));
Assert.hasText(port, () -> String.format("No port given in cluster node %s!", node)); Assert.hasText(port, () -> String.format("No port given in cluster node %s!", node));
return new TransportAddress(toInetAddress(host), Integer.valueOf(port)); return new TransportAddress(toInetAddress(host), Integer.parseInt(port));
}).collect(Collectors.toList()); }).collect(Collectors.toList());
} }

View File

@ -104,7 +104,7 @@ public class ElasticsearchHost {
@Override @Override
public String toString() { public String toString() {
return "ElasticsearchHost(" + endpoint + ", " + state.name() + ")"; return "ElasticsearchHost(" + endpoint + ", " + state.name() + ')';
} }
public enum State { public enum State {

View File

@ -81,7 +81,7 @@ public class NodeClientFactoryBean implements FactoryBean<Client>, InitializingB
} }
@Override @Override
public NodeClient getObject() throws Exception { public NodeClient getObject() {
return nodeClient; return nodeClient;
} }
@ -148,7 +148,7 @@ public class NodeClientFactoryBean implements FactoryBean<Client>, InitializingB
} }
@Override @Override
public void destroy() throws Exception { public void destroy() {
try { try {
// NodeClient.close() is a noop, no need to call it here // NodeClient.close() is a noop, no need to call it here
nodeClient = null; nodeClient = null;

View File

@ -41,7 +41,7 @@ public class RestClientFactoryBean implements FactoryBean<RestHighLevelClient>,
static final String COMMA = ","; static final String COMMA = ",";
@Override @Override
public void destroy() throws Exception { public void destroy() {
try { try {
log.info("Closing elasticSearch client"); log.info("Closing elasticSearch client");
if (client != null) { if (client != null) {
@ -58,7 +58,7 @@ public class RestClientFactoryBean implements FactoryBean<RestHighLevelClient>,
} }
@Override @Override
public RestHighLevelClient getObject() throws Exception { public RestHighLevelClient getObject() {
return client; return client;
} }
@ -75,7 +75,7 @@ public class RestClientFactoryBean implements FactoryBean<RestHighLevelClient>,
protected void buildClient() throws Exception { protected void buildClient() throws Exception {
Assert.hasText(hosts, "[Assertion Failed] At least one host must be set."); Assert.hasText(hosts, "[Assertion Failed] At least one host must be set.");
ArrayList<HttpHost> httpHosts = new ArrayList<HttpHost>(); ArrayList<HttpHost> httpHosts = new ArrayList<>();
for (String host : hosts.split(COMMA)) { for (String host : hosts.split(COMMA)) {
URL hostUrl = new URL(host); URL hostUrl = new URL(host);
httpHosts.add(new HttpHost(hostUrl.getHost(), hostUrl.getPort(), hostUrl.getProtocol())); httpHosts.add(new HttpHost(hostUrl.getHost(), hostUrl.getPort(), hostUrl.getProtocol()));

View File

@ -52,7 +52,7 @@ public class TransportClientFactoryBean implements FactoryBean<TransportClient>,
private Properties properties; private Properties properties;
@Override @Override
public void destroy() throws Exception { public void destroy() {
try { try {
logger.info("Closing elasticSearch client"); logger.info("Closing elasticSearch client");
if (client != null) { if (client != null) {
@ -64,7 +64,7 @@ public class TransportClientFactoryBean implements FactoryBean<TransportClient>,
} }
@Override @Override
public TransportClient getObject() throws Exception { public TransportClient getObject() {
return client; return client;
} }
@ -83,7 +83,7 @@ public class TransportClientFactoryBean implements FactoryBean<TransportClient>,
buildClient(); buildClient();
} }
protected void buildClient() throws Exception { protected void buildClient() {
client = new PreBuiltTransportClient(settings()); client = new PreBuiltTransportClient(settings());

View File

@ -440,6 +440,7 @@ public class DefaultReactiveElasticsearchClient implements ReactiveElasticsearch
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient#ping(org.springframework.http.HttpHeaders, org.elasticsearch.index.reindex.DeleteByQueryRequest) * @see org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient#ping(org.springframework.http.HttpHeaders, org.elasticsearch.index.reindex.DeleteByQueryRequest)
*/ */
@Override
public Mono<BulkByScrollResponse> deleteBy(HttpHeaders headers, DeleteByQueryRequest deleteRequest) { public Mono<BulkByScrollResponse> deleteBy(HttpHeaders headers, DeleteByQueryRequest deleteRequest) {
return sendRequest(deleteRequest, RequestCreator.deleteByQuery(), BulkByScrollResponse.class, headers) // return sendRequest(deleteRequest, RequestCreator.deleteByQuery(), BulkByScrollResponse.class, headers) //
@ -764,14 +765,7 @@ public class DefaultReactiveElasticsearchClient implements ReactiveElasticsearch
static Function<DeleteByQueryRequest, Request> deleteByQuery() { static Function<DeleteByQueryRequest, Request> deleteByQuery() {
return request -> { return request -> RequestConverters.deleteByQuery(request);
try {
return RequestConverters.deleteByQuery(request);
} catch (IOException e) {
throw new ElasticsearchException("Could not parse request", e);
}
};
} }
static Function<BulkRequest, Request> bulk() { static Function<BulkRequest, Request> bulk() {

View File

@ -60,6 +60,7 @@ class MultiNodeHostProvider implements HostProvider {
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.elasticsearch.client.reactive.HostProvider#clusterInfo() * @see org.springframework.data.elasticsearch.client.reactive.HostProvider#clusterInfo()
*/ */
@Override
public Mono<ClusterInformation> clusterInfo() { public Mono<ClusterInformation> clusterInfo() {
return nodes(null).map(this::updateNodeState).buffer(hosts.size()) return nodes(null).map(this::updateNodeState).buffer(hosts.size())
.then(Mono.just(new ClusterInformation(new LinkedHashSet<>(this.hosts.values())))); .then(Mono.just(new ClusterInformation(new LinkedHashSet<>(this.hosts.values()))));

View File

@ -16,11 +16,8 @@
package org.springframework.data.elasticsearch.client.reactive; package org.springframework.data.elasticsearch.client.reactive;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import org.elasticsearch.action.ActionResponse; import org.elasticsearch.action.ActionResponse;

View File

@ -103,6 +103,7 @@ import org.springframework.lang.Nullable;
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
* @since 3.2 * @since 3.2
*/ */
@SuppressWarnings("JavadocReference")
public class RequestConverters { public class RequestConverters {
private static final XContentType REQUEST_BODY_CONTENT_TYPE = XContentType.JSON; private static final XContentType REQUEST_BODY_CONTENT_TYPE = XContentType.JSON;
@ -364,7 +365,7 @@ public class RequestConverters {
XContentType upsertContentType = updateRequest.upsertRequest().getContentType(); XContentType upsertContentType = updateRequest.upsertRequest().getContentType();
if ((xContentType != null) && (xContentType != upsertContentType)) { if ((xContentType != null) && (xContentType != upsertContentType)) {
throw new IllegalStateException("Update request cannot have different content types for doc [" + xContentType throw new IllegalStateException("Update request cannot have different content types for doc [" + xContentType
+ "]" + " and upsert [" + upsertContentType + "] documents"); + ']' + " and upsert [" + upsertContentType + "] documents");
} else { } else {
xContentType = upsertContentType; xContentType = upsertContentType;
} }
@ -460,7 +461,7 @@ public class RequestConverters {
return request; return request;
} }
public static Request explain(ExplainRequest explainRequest) throws IOException { public static Request explain(ExplainRequest explainRequest) {
Request request = new Request(HttpMethod.GET.name(), Request request = new Request(HttpMethod.GET.name(),
endpoint(explainRequest.index(), explainRequest.type(), explainRequest.id(), "_explain")); endpoint(explainRequest.index(), explainRequest.type(), explainRequest.id(), "_explain"));
@ -482,7 +483,7 @@ public class RequestConverters {
return request; return request;
} }
public static Request rankEval(RankEvalRequest rankEvalRequest) throws IOException { public static Request rankEval(RankEvalRequest rankEvalRequest) {
Request request = new Request(HttpMethod.GET.name(), Request request = new Request(HttpMethod.GET.name(),
endpoint(rankEvalRequest.indices(), Strings.EMPTY_ARRAY, "_rank_eval")); endpoint(rankEvalRequest.indices(), Strings.EMPTY_ARRAY, "_rank_eval"));
@ -501,8 +502,7 @@ public class RequestConverters {
return prepareReindexRequest(reindexRequest, false); return prepareReindexRequest(reindexRequest, false);
} }
private static Request prepareReindexRequest(ReindexRequest reindexRequest, boolean waitForCompletion) private static Request prepareReindexRequest(ReindexRequest reindexRequest, boolean waitForCompletion) {
throws IOException {
String endpoint = new EndpointBuilder().addPathPart("_reindex").build(); String endpoint = new EndpointBuilder().addPathPart("_reindex").build();
Request request = new Request(HttpMethod.POST.name(), endpoint); Request request = new Request(HttpMethod.POST.name(), endpoint);
Params params = new Params(request).withWaitForCompletion(waitForCompletion).withRefresh(reindexRequest.isRefresh()) Params params = new Params(request).withWaitForCompletion(waitForCompletion).withRefresh(reindexRequest.isRefresh())
@ -516,7 +516,7 @@ public class RequestConverters {
return request; return request;
} }
public static Request updateByQuery(UpdateByQueryRequest updateByQueryRequest) throws IOException { public static Request updateByQuery(UpdateByQueryRequest updateByQueryRequest) {
String endpoint = endpoint(updateByQueryRequest.indices(), updateByQueryRequest.getDocTypes(), "_update_by_query"); String endpoint = endpoint(updateByQueryRequest.indices(), updateByQueryRequest.getDocTypes(), "_update_by_query");
Request request = new Request(HttpMethod.POST.name(), endpoint); Request request = new Request(HttpMethod.POST.name(), endpoint);
Params params = new Params(request).withRouting(updateByQueryRequest.getRouting()) Params params = new Params(request).withRouting(updateByQueryRequest.getRouting())
@ -541,7 +541,7 @@ public class RequestConverters {
return request; return request;
} }
public static Request deleteByQuery(DeleteByQueryRequest deleteByQueryRequest) throws IOException { public static Request deleteByQuery(DeleteByQueryRequest deleteByQueryRequest) {
String endpoint = endpoint(deleteByQueryRequest.indices(), deleteByQueryRequest.getDocTypes(), "_delete_by_query"); String endpoint = endpoint(deleteByQueryRequest.indices(), deleteByQueryRequest.getDocTypes(), "_delete_by_query");
Request request = new Request(HttpMethod.POST.name(), endpoint); Request request = new Request(HttpMethod.POST.name(), endpoint);
Params params = new Params(request).withRouting(deleteByQueryRequest.getRouting()) Params params = new Params(request).withRouting(deleteByQueryRequest.getRouting())
@ -587,7 +587,7 @@ public class RequestConverters {
return request; return request;
} }
public static Request putScript(PutStoredScriptRequest putStoredScriptRequest) throws IOException { public static Request putScript(PutStoredScriptRequest putStoredScriptRequest) {
String endpoint = new EndpointBuilder().addPathPartAsIs("_scripts").addPathPart(putStoredScriptRequest.id()) String endpoint = new EndpointBuilder().addPathPartAsIs("_scripts").addPathPart(putStoredScriptRequest.id())
.build(); .build();
Request request = new Request(HttpMethod.POST.name(), endpoint); Request request = new Request(HttpMethod.POST.name(), endpoint);
@ -601,7 +601,7 @@ public class RequestConverters {
return request; return request;
} }
public static Request analyze(AnalyzeRequest request) throws IOException { public static Request analyze(AnalyzeRequest request) {
EndpointBuilder builder = new EndpointBuilder(); EndpointBuilder builder = new EndpointBuilder();
String index = request.index(); String index = request.index();
if (index != null) { if (index != null) {
@ -1145,7 +1145,7 @@ public class RequestConverters {
} }
if (requestContentType != xContentType) { if (requestContentType != xContentType) {
throw new IllegalArgumentException("Mismatching content-type found for request with content-type [" throw new IllegalArgumentException("Mismatching content-type found for request with content-type ["
+ requestContentType + "], previous requests have content-type [" + xContentType + "]"); + requestContentType + "], previous requests have content-type [" + xContentType + ']');
} }
return xContentType; return xContentType;
} }
@ -1194,7 +1194,7 @@ public class RequestConverters {
// encode each part (e.g. index, type and id) separately before merging them into the path // encode each part (e.g. index, type and id) separately before merging them into the path
// we prepend "/" to the path part to make this path absolute, otherwise there can be issues with // we prepend "/" to the path part to make this path absolute, otherwise there can be issues with
// paths that start with `-` or contain `:` // paths that start with `-` or contain `:`
URI uri = new URI(null, null, null, -1, "/" + pathPart, null, null); URI uri = new URI(null, null, null, -1, '/' + pathPart, null, null);
// manually encode any slash that each part may contain // manually encode any slash that each part may contain
return uri.getRawPath().substring(1).replaceAll("/", "%2F"); return uri.getRawPath().substring(1).replaceAll("/", "%2F");
} catch (URISyntaxException e) { } catch (URISyntaxException e) {

View File

@ -127,7 +127,7 @@ public class ElasticsearchConfigurationSupport {
return Collections.emptySet(); return Collections.emptySet();
} }
Set<Class<?>> initialEntitySet = new HashSet<Class<?>>(); Set<Class<?>> initialEntitySet = new HashSet<>();
if (StringUtils.hasText(basePackage)) { if (StringUtils.hasText(basePackage)) {

View File

@ -79,6 +79,7 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
// endregion // endregion
// region DocumentOperations // region DocumentOperations
@Override
public void delete(Query query, Class<?> clazz, IndexCoordinates index) { public void delete(Query query, Class<?> clazz, IndexCoordinates index) {
Assert.notNull(query, "Query must not be null."); Assert.notNull(query, "Query must not be null.");

View File

@ -20,10 +20,13 @@ import static org.springframework.data.elasticsearch.core.query.Criteria.*;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.ListIterator;
import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.index.query.*; import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.GeoBoundingBoxQueryBuilder;
import org.elasticsearch.index.query.GeoDistanceQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.elasticsearch.core.geo.GeoBox; import org.springframework.data.elasticsearch.core.geo.GeoBox;
import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.Criteria; import org.springframework.data.elasticsearch.core.query.Criteria;
@ -39,20 +42,16 @@ import org.springframework.util.Assert;
* @author Franck Marchand * @author Franck Marchand
* @author Mohsin Husen * @author Mohsin Husen
* @author Artur Konczak * @author Artur Konczak
* * @author Peter-Josef Meisch
*/ */
class CriteriaFilterProcessor { class CriteriaFilterProcessor {
QueryBuilder createFilterFromCriteria(Criteria criteria) { QueryBuilder createFilterFromCriteria(Criteria criteria) {
List<QueryBuilder> fbList = new LinkedList<>(); List<QueryBuilder> fbList = new LinkedList<>();
QueryBuilder filter = null; QueryBuilder filter = null;
ListIterator<Criteria> chainIterator = criteria.getCriteriaChain().listIterator(); for (Criteria chainedCriteria : criteria.getCriteriaChain()) {
while (chainIterator.hasNext()) {
QueryBuilder fb = null; QueryBuilder fb = null;
Criteria chainedCriteria = chainIterator.next();
if (chainedCriteria.isOr()) { if (chainedCriteria.isOr()) {
fb = QueryBuilders.boolQuery(); fb = QueryBuilders.boolQuery();
for (QueryBuilder f : createFilterFragmentForCriteria(chainedCriteria)) { for (QueryBuilder f : createFilterFragmentForCriteria(chainedCriteria)) {
@ -60,7 +59,8 @@ class CriteriaFilterProcessor {
} }
fbList.add(fb); fbList.add(fb);
} else if (chainedCriteria.isNegating()) { } else if (chainedCriteria.isNegating()) {
List<QueryBuilder> negationFilters = buildNegationFilter(criteria.getField().getName(), criteria.getFilterCriteriaEntries().iterator()); List<QueryBuilder> negationFilters = buildNegationFilter(criteria.getField().getName(),
criteria.getFilterCriteriaEntries().iterator());
if (!negationFilters.isEmpty()) { if (!negationFilters.isEmpty()) {
fbList.addAll(negationFilters); fbList.addAll(negationFilters);
@ -83,7 +83,6 @@ class CriteriaFilterProcessor {
return filter; return filter;
} }
private List<QueryBuilder> createFilterFragmentForCriteria(Criteria chainedCriteria) { private List<QueryBuilder> createFilterFragmentForCriteria(Criteria chainedCriteria) {
Iterator<Criteria.CriteriaEntry> it = chainedCriteria.getFilterCriteriaEntries().iterator(); Iterator<Criteria.CriteriaEntry> it = chainedCriteria.getFilterCriteriaEntries().iterator();
List<QueryBuilder> filterList = new LinkedList<>(); List<QueryBuilder> filterList = new LinkedList<>();
@ -101,7 +100,6 @@ class CriteriaFilterProcessor {
return filterList; return filterList;
} }
private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) { private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) {
if (value == null) { if (value == null) {
return null; return null;
@ -116,8 +114,10 @@ class CriteriaFilterProcessor {
Object[] valArray = (Object[]) value; Object[] valArray = (Object[]) value;
Assert.noNullElements(valArray, "Geo distance filter takes 2 not null elements array as parameter."); Assert.noNullElements(valArray, "Geo distance filter takes 2 not null elements array as parameter.");
Assert.isTrue(valArray.length == 2, "Geo distance filter takes a 2-elements array as parameter."); Assert.isTrue(valArray.length == 2, "Geo distance filter takes a 2-elements array as parameter.");
Assert.isTrue(valArray[0] instanceof GeoPoint || valArray[0] instanceof String || valArray[0] instanceof Point, "First element of a geo distance filter must be a GeoPoint, a Point or a text"); Assert.isTrue(valArray[0] instanceof GeoPoint || valArray[0] instanceof String || valArray[0] instanceof Point,
Assert.isTrue(valArray[1] instanceof String || valArray[1] instanceof Distance, "Second element of a geo distance filter must be a text or a Distance"); "First element of a geo distance filter must be a GeoPoint, a Point or a text");
Assert.isTrue(valArray[1] instanceof String || valArray[1] instanceof Distance,
"Second element of a geo distance filter must be a text or a Distance");
StringBuilder dist = new StringBuilder(); StringBuilder dist = new StringBuilder();
@ -129,15 +129,18 @@ class CriteriaFilterProcessor {
if (valArray[0] instanceof GeoPoint) { if (valArray[0] instanceof GeoPoint) {
GeoPoint loc = (GeoPoint) valArray[0]; GeoPoint loc = (GeoPoint) valArray[0];
geoDistanceQueryBuilder.point(loc.getLat(),loc.getLon()).distance(dist.toString()).geoDistance(GeoDistance.PLANE); geoDistanceQueryBuilder.point(loc.getLat(), loc.getLon()).distance(dist.toString())
.geoDistance(GeoDistance.PLANE);
} else if (valArray[0] instanceof Point) { } else if (valArray[0] instanceof Point) {
GeoPoint loc = GeoPoint.fromPoint((Point) valArray[0]); GeoPoint loc = GeoPoint.fromPoint((Point) valArray[0]);
geoDistanceQueryBuilder.point(loc.getLat(), loc.getLon()).distance(dist.toString()).geoDistance(GeoDistance.PLANE); geoDistanceQueryBuilder.point(loc.getLat(), loc.getLon()).distance(dist.toString())
.geoDistance(GeoDistance.PLANE);
} else { } else {
String loc = (String) valArray[0]; String loc = (String) valArray[0];
if (loc.contains(",")) { if (loc.contains(",")) {
String c[] = loc.split(","); String[] c = loc.split(",");
geoDistanceQueryBuilder.point(Double.parseDouble(c[0]), Double.parseDouble(c[1])).distance(dist.toString()).geoDistance(GeoDistance.PLANE); geoDistanceQueryBuilder.point(Double.parseDouble(c[0]), Double.parseDouble(c[1])).distance(dist.toString())
.geoDistance(GeoDistance.PLANE);
} else { } else {
geoDistanceQueryBuilder.geohash(loc).distance(dist.toString()).geoDistance(GeoDistance.PLANE); geoDistanceQueryBuilder.geohash(loc).distance(dist.toString()).geoDistance(GeoDistance.PLANE);
} }
@ -150,7 +153,8 @@ class CriteriaFilterProcessor {
case BBOX: { case BBOX: {
filter = QueryBuilders.geoBoundingBoxQuery(fieldName); filter = QueryBuilders.geoBoundingBoxQuery(fieldName);
Assert.isTrue(value instanceof Object[], "Value of a boundedBy filter should be an array of one or two values."); Assert.isTrue(value instanceof Object[],
"Value of a boundedBy filter should be an array of one or two values.");
Object[] valArray = (Object[]) value; Object[] valArray = (Object[]) value;
Assert.noNullElements(valArray, "Geo boundedBy filter takes a not null element array as parameter."); Assert.noNullElements(valArray, "Geo boundedBy filter takes a not null element array as parameter.");
@ -163,7 +167,8 @@ class CriteriaFilterProcessor {
twoParameterBBox((GeoBoundingBoxQueryBuilder) filter, valArray); twoParameterBBox((GeoBoundingBoxQueryBuilder) filter, valArray);
} else { } else {
// error // error
Assert.isTrue(false, "Geo distance filter takes a 1-elements array(GeoBox) or 2-elements array(GeoPoints or Strings(format lat,lon or geohash))."); Assert.isTrue(false,
"Geo distance filter takes a 1-elements array(GeoBox) or 2-elements array(GeoPoints or Strings(format lat,lon or geohash)).");
} }
break; break;
} }
@ -172,7 +177,6 @@ class CriteriaFilterProcessor {
return filter; return filter;
} }
/** /**
* extract the distance string from a {@link org.springframework.data.geo.Distance} object. * extract the distance string from a {@link org.springframework.data.geo.Distance} object.
* *
@ -196,7 +200,8 @@ class CriteriaFilterProcessor {
} }
private void oneParameterBBox(GeoBoundingBoxQueryBuilder filter, Object value) { private void oneParameterBBox(GeoBoundingBoxQueryBuilder filter, Object value) {
Assert.isTrue(value instanceof GeoBox || value instanceof Box, "single-element of boundedBy filter must be type of GeoBox or Box"); Assert.isTrue(value instanceof GeoBox || value instanceof Box,
"single-element of boundedBy filter must be type of GeoBox or Box");
GeoBox geoBBox; GeoBox geoBBox;
if (value instanceof Box) { if (value instanceof Box) {
@ -206,7 +211,8 @@ class CriteriaFilterProcessor {
geoBBox = (GeoBox) value; geoBBox = (GeoBox) value;
} }
filter.setCorners(geoBBox.getTopLeft().getLat(), geoBBox.getTopLeft().getLon(), geoBBox.getBottomRight().getLat(), geoBBox.getBottomRight().getLon()); filter.setCorners(geoBBox.getTopLeft().getLat(), geoBBox.getTopLeft().getLon(), geoBBox.getBottomRight().getLat(),
geoBBox.getBottomRight().getLon());
} }
private static boolean isType(Object[] array, Class clazz) { private static boolean isType(Object[] array, Class clazz) {
@ -219,7 +225,8 @@ class CriteriaFilterProcessor {
} }
private void twoParameterBBox(GeoBoundingBoxQueryBuilder filter, Object[] values) { private void twoParameterBBox(GeoBoundingBoxQueryBuilder filter, Object[] values) {
Assert.isTrue(isType(values, GeoPoint.class) || isType(values, String.class), " both elements of boundedBy filter must be type of GeoPoint or text(format lat,lon or geohash)"); Assert.isTrue(isType(values, GeoPoint.class) || isType(values, String.class),
" both elements of boundedBy filter must be type of GeoPoint or text(format lat,lon or geohash)");
if (values[0] instanceof GeoPoint) { if (values[0] instanceof GeoPoint) {
GeoPoint topLeft = (GeoPoint) values[0]; GeoPoint topLeft = (GeoPoint) values[0];
GeoPoint bottomRight = (GeoPoint) values[1]; GeoPoint bottomRight = (GeoPoint) values[1];
@ -236,7 +243,8 @@ class CriteriaFilterProcessor {
while (it.hasNext()) { while (it.hasNext()) {
Criteria.CriteriaEntry criteriaEntry = it.next(); Criteria.CriteriaEntry criteriaEntry = it.next();
QueryBuilder notFilter = QueryBuilders.boolQuery().mustNot(processCriteriaEntry(criteriaEntry.getKey(), criteriaEntry.getValue(), fieldName)); QueryBuilder notFilter = QueryBuilders.boolQuery()
.mustNot(processCriteriaEntry(criteriaEntry.getKey(), criteriaEntry.getValue(), fieldName));
notFilterList.add(notFilter); notFilterList.add(notFilter);
} }

View File

@ -157,13 +157,13 @@ class CriteriaQueryProcessor {
query = queryStringQuery(searchText).field(fieldName).defaultOperator(AND); query = queryStringQuery(searchText).field(fieldName).defaultOperator(AND);
break; break;
case CONTAINS: case CONTAINS:
query = queryStringQuery("*" + searchText + "*").field(fieldName).analyzeWildcard(true); query = queryStringQuery('*' + searchText + '*').field(fieldName).analyzeWildcard(true);
break; break;
case STARTS_WITH: case STARTS_WITH:
query = queryStringQuery(searchText + "*").field(fieldName).analyzeWildcard(true); query = queryStringQuery(searchText + '*').field(fieldName).analyzeWildcard(true);
break; break;
case ENDS_WITH: case ENDS_WITH:
query = queryStringQuery("*" + searchText).field(fieldName).analyzeWildcard(true); query = queryStringQuery('*' + searchText).field(fieldName).analyzeWildcard(true);
break; break;
case EXPRESSION: case EXPRESSION:
query = queryStringQuery(value.toString()).field(fieldName); query = queryStringQuery(value.toString()).field(fieldName);

View File

@ -26,9 +26,7 @@ import java.util.Map;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse;
import org.elasticsearch.client.Request; import org.elasticsearch.client.Request;
@ -36,7 +34,9 @@ import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response; import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.cluster.metadata.AliasMetaData; import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.core.client.support.AliasData; import org.springframework.data.elasticsearch.core.client.support.AliasData;
@ -121,13 +121,11 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
RestClient restClient = client.getLowLevelClient(); RestClient restClient = client.getLowLevelClient();
try { try {
Request request = new Request("GET", Request request = new Request("GET", '/' + index.getIndexName() + "/_mapping");
'/' + index.getIndexName() + "/_mapping/" + index.getTypeName() + "?include_type_name=true");
Response response = restClient.performRequest(request); Response response = restClient.performRequest(request);
return convertMappingResponse(EntityUtils.toString(response.getEntity()), index.getTypeName()); return convertMappingResponse(EntityUtils.toString(response.getEntity()));
} catch (Exception e) { } catch (Exception e) {
throw new ElasticsearchException("Error while getting mapping for indexName : " + index.getIndexName() throw new ElasticsearchException("Error while getting mapping for indexName : " + index.getIndexName(), e);
+ " type : " + index.getTypeName() + ' ', e);
} }
} }
@ -210,14 +208,14 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
} }
// region Helper methods // region Helper methods
private Map<String, Object> convertMappingResponse(String mappingResponse, String type) { private Map<String, Object> convertMappingResponse(String mappingResponse) {
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
try { try {
Map<String, Object> result = null; Map<String, Object> result = null;
JsonNode node = mapper.readTree(mappingResponse); JsonNode node = mapper.readTree(mappingResponse);
node = node.findValue("mappings").findValue(type); node = node.findValue("mappings");
result = mapper.readValue(mapper.writeValueAsString(node), HashMap.class); result = mapper.readValue(mapper.writeValueAsString(node), HashMap.class);
return result; return result;
@ -248,7 +246,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
new TypeReference<Map<String, AliasData>>() {}); new TypeReference<Map<String, AliasData>>() {});
Iterable<Map.Entry<String, AliasData>> aliasIter = aliasData.entrySet(); Iterable<Map.Entry<String, AliasData>> aliasIter = aliasData.entrySet();
List<AliasMetaData> aliasMetaDataList = new ArrayList<AliasMetaData>(); List<AliasMetaData> aliasMetaDataList = new ArrayList<>();
for (Map.Entry<String, AliasData> aliasentry : aliasIter) { for (Map.Entry<String, AliasData> aliasentry : aliasIter) {
AliasData data = aliasentry.getValue(); AliasData data = aliasentry.getValue();
@ -261,6 +259,5 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
throw new ElasticsearchException("Could not map alias response : " + aliasResponse, e); throw new ElasticsearchException("Could not map alias response : " + aliasResponse, e);
} }
} }
// endregion // endregion
} }

View File

@ -87,15 +87,15 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp
@Override @Override
public Map<String, Object> getMapping(IndexCoordinates index) { public Map<String, Object> getMapping(IndexCoordinates index) {
Assert.notNull(index, "No index defined for putMapping()"); Assert.notNull(index, "No index defined for getMapping()");
try { try {
return client.admin().indices() return client.admin().indices().getMappings( //
.getMappings(new GetMappingsRequest().indices(index.getIndexNames()).types(index.getTypeNames())).actionGet() new GetMappingsRequest().indices(index.getIndexNames())).actionGet() //
.getMappings().get(index.getIndexName()).get(index.getTypeName()).getSourceAsMap(); .getMappings().get(index.getIndexName()).get(IndexCoordinates.TYPE) //
.getSourceAsMap();
} catch (Exception e) { } catch (Exception e) {
throw new ElasticsearchException("Error while getting mapping for indexName : " + index.getIndexName() throw new ElasticsearchException("Error while getting mapping for indexName : " + index.getIndexName(), e);
+ " type : " + index.getTypeName() + ' ' + e.getMessage());
} }
} }

View File

@ -41,7 +41,6 @@ import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.suggest.SuggestBuilder; import org.elasticsearch.search.suggest.SuggestBuilder;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.document.DocumentAdapters; import org.springframework.data.elasticsearch.core.document.DocumentAdapters;
import org.springframework.data.elasticsearch.core.document.SearchDocumentResponse; import org.springframework.data.elasticsearch.core.document.SearchDocumentResponse;

View File

@ -35,7 +35,6 @@ import org.elasticsearch.search.suggest.SuggestBuilder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.document.DocumentAdapters; import org.springframework.data.elasticsearch.core.document.DocumentAdapters;
import org.springframework.data.elasticsearch.core.document.SearchDocumentResponse; import org.springframework.data.elasticsearch.core.document.SearchDocumentResponse;
@ -128,8 +127,7 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
public <T> T get(GetQuery query, Class<T> clazz, IndexCoordinates index) { public <T> T get(GetQuery query, Class<T> clazz, IndexCoordinates index) {
GetRequestBuilder getRequestBuilder = requestFactory.getRequestBuilder(client, query, index); GetRequestBuilder getRequestBuilder = requestFactory.getRequestBuilder(client, query, index);
GetResponse response = getRequestBuilder.execute().actionGet(); GetResponse response = getRequestBuilder.execute().actionGet();
T entity = elasticsearchConverter.mapDocument(DocumentAdapters.from(response), clazz); return elasticsearchConverter.mapDocument(DocumentAdapters.from(response), clazz);
return entity;
} }
@Override @Override
@ -163,7 +161,7 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
@Override @Override
public String delete(String id, IndexCoordinates index) { public String delete(String id, IndexCoordinates index) {
return client.prepareDelete(index.getIndexName(), index.getTypeName(), id).execute().actionGet().getId(); return client.prepareDelete(index.getIndexName(), IndexCoordinates.TYPE, id).execute().actionGet().getId();
} }
@Override @Override

View File

@ -99,8 +99,6 @@ class EntityOperations {
* @param index index name override can be {@literal null}. * @param index index name override can be {@literal null}.
* @param type index type override can be {@literal null}. * @param type index type override can be {@literal null}.
* @return the {@link IndexCoordinates} containing index name and index type. * @return the {@link IndexCoordinates} containing index name and index type.
* @see ElasticsearchPersistentEntity#getIndexName()
* @see ElasticsearchPersistentEntity#getIndexType()
*/ */
IndexCoordinates determineIndex(Entity<?> entity, @Nullable String index, @Nullable String type) { IndexCoordinates determineIndex(Entity<?> entity, @Nullable String index, @Nullable String type) {
return determineIndex(entity.getPersistentEntity(), index, type); return determineIndex(entity.getPersistentEntity(), index, type);
@ -116,12 +114,10 @@ class EntityOperations {
* @param index index name override can be {@literal null}. * @param index index name override can be {@literal null}.
* @param type index type override can be {@literal null}. * @param type index type override can be {@literal null}.
* @return the {@link IndexCoordinates} containing index name and index type. * @return the {@link IndexCoordinates} containing index name and index type.
* @see ElasticsearchPersistentEntity#getIndexName()
* @see ElasticsearchPersistentEntity#getIndexType()
*/ */
IndexCoordinates determineIndex(ElasticsearchPersistentEntity<?> persistentEntity, @Nullable String index, IndexCoordinates determineIndex(ElasticsearchPersistentEntity<?> persistentEntity, @Nullable String index,
@Nullable String type) { @Nullable String type) {
return IndexCoordinates.of(indexName(persistentEntity, index)).withTypes(typeName(persistentEntity, type)); return persistentEntity.getIndexCoordinates();
} }
private static String indexName(@Nullable ElasticsearchPersistentEntity<?> entity, @Nullable String index) { private static String indexName(@Nullable ElasticsearchPersistentEntity<?> entity, @Nullable String index) {
@ -134,16 +130,6 @@ class EntityOperations {
return index; return index;
} }
private static String typeName(@Nullable ElasticsearchPersistentEntity<?> entity, @Nullable String type) {
if (StringUtils.isEmpty(type)) {
Assert.notNull(entity, "Cannot determine index type");
return entity.getIndexCoordinates().getTypeName();
}
return type;
}
/** /**
* A representation of information about an entity. * A representation of information about an entity.
* *
@ -268,6 +254,7 @@ class EntityOperations {
* @return the current version or {@literal null} in case it's uninitialized or the entity doesn't expose a version * @return the current version or {@literal null} in case it's uninitialized or the entity doesn't expose a version
* property. * property.
*/ */
@Override
@Nullable @Nullable
Number getVersion(); Number getVersion();
} }

View File

@ -182,8 +182,8 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
Object id = entity.getId(); Object id = entity.getId();
IndexRequest request = id != null IndexRequest request = id != null
? new IndexRequest(index.getIndexName(), index.getTypeName(), converter.convertId(id)) ? new IndexRequest(index.getIndexName()).id(converter.convertId(id))
: new IndexRequest(index.getIndexName(), index.getTypeName()); : new IndexRequest(index.getIndexName());
request.source(converter.mapObject(value).toJson(), Requests.INDEX_CONTENT_TYPE); request.source(converter.mapObject(value).toJson(), Requests.INDEX_CONTENT_TYPE);
@ -223,7 +223,7 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
return Mono.defer(() -> { return Mono.defer(() -> {
return doFindById(new GetRequest(index.getIndexName(), index.getTypeName(), id)); return doFindById(new GetRequest(index.getIndexName(), id));
}); });
} }
@ -241,7 +241,7 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
private Mono<Boolean> doExists(String id, ElasticsearchPersistentEntity<?> entity, @Nullable IndexCoordinates index) { private Mono<Boolean> doExists(String id, ElasticsearchPersistentEntity<?> entity, @Nullable IndexCoordinates index) {
return Mono.defer(() -> doExists(new GetRequest(index.getIndexName(), index.getTypeName(), id))); return Mono.defer(() -> doExists(new GetRequest(index.getIndexName(), id)));
} }
/* /*
@ -285,7 +285,7 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
return Mono.defer(() -> { return Mono.defer(() -> {
return doDelete(prepareDeleteRequest(source, new DeleteRequest(index.getIndexName(), index.getTypeName(), id))); return doDelete(prepareDeleteRequest(source, new DeleteRequest(index.getIndexName(), id)));
}); });
} }
@ -312,7 +312,6 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
return Flux.defer(() -> { return Flux.defer(() -> {
DeleteByQueryRequest request = new DeleteByQueryRequest(index.getIndexNames()); DeleteByQueryRequest request = new DeleteByQueryRequest(index.getIndexNames());
request.types(index.getTypeNames());
request.setQuery(mappedQuery(query, entity)); request.setQuery(mappedQuery(query, entity));
return doDeleteBy(prepareDeleteByRequest(request)); return doDeleteBy(prepareDeleteByRequest(request));

View File

@ -21,12 +21,9 @@ import static org.springframework.util.CollectionUtils.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder; import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequestBuilder;
import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkRequestBuilder;
@ -42,6 +39,8 @@ import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateRequestBuilder; import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests; import org.elasticsearch.client.Requests;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.XContentType;
@ -176,24 +175,26 @@ class RequestFactory {
return bulkRequestBuilder; return bulkRequestBuilder;
} }
@SuppressWarnings("unchecked")
public CreateIndexRequest createIndexRequest(String indexName, Object settings) { public CreateIndexRequest createIndexRequest(String indexName, Object settings) {
CreateIndexRequest request = new CreateIndexRequest(indexName); CreateIndexRequest request = new CreateIndexRequest(indexName);
if (settings instanceof String) { if (settings instanceof String) {
request.settings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE); request.settings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE);
} else if (settings instanceof Map) { } else if (settings instanceof Map) {
request.settings((Map) settings); request.settings((Map<String, ?>) settings);
} else if (settings instanceof XContentBuilder) { } else if (settings instanceof XContentBuilder) {
request.settings((XContentBuilder) settings); request.settings((XContentBuilder) settings);
} }
return request; return request;
} }
@SuppressWarnings("unchecked")
public CreateIndexRequestBuilder createIndexRequestBuilder(Client client, String indexName, Object settings) { public CreateIndexRequestBuilder createIndexRequestBuilder(Client client, String indexName, Object settings) {
CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(indexName); CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(indexName);
if (settings instanceof String) { if (settings instanceof String) {
createIndexRequestBuilder.setSettings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE); createIndexRequestBuilder.setSettings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE);
} else if (settings instanceof Map) { } else if (settings instanceof Map) {
createIndexRequestBuilder.setSettings((Map) settings); createIndexRequestBuilder.setSettings((Map<String, ?>) settings);
} else if (settings instanceof XContentBuilder) { } else if (settings instanceof XContentBuilder) {
createIndexRequestBuilder.setSettings((XContentBuilder) settings); createIndexRequestBuilder.setSettings((XContentBuilder) settings);
} }
@ -202,7 +203,6 @@ class RequestFactory {
public DeleteByQueryRequest deleteByQueryRequest(DeleteQuery deleteQuery, IndexCoordinates index) { public DeleteByQueryRequest deleteByQueryRequest(DeleteQuery deleteQuery, IndexCoordinates index) {
DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(index.getIndexNames()) // DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(index.getIndexNames()) //
.setDocTypes(index.getTypeNames()) //
.setQuery(deleteQuery.getQuery()) // .setQuery(deleteQuery.getQuery()) //
.setAbortOnVersionConflict(false) // .setAbortOnVersionConflict(false) //
.setRefresh(true); .setRefresh(true);
@ -224,8 +224,7 @@ class RequestFactory {
.abortOnVersionConflict(false) // .abortOnVersionConflict(false) //
.refresh(true); .refresh(true);
SearchRequestBuilder source = requestBuilder.source() // SearchRequestBuilder source = requestBuilder.source();
.setTypes(index.getTypeNames());
if (deleteQuery.getScrollTimeInMillis() != null) if (deleteQuery.getScrollTimeInMillis() != null)
source.setScroll(TimeValue.timeValueMillis(deleteQuery.getScrollTimeInMillis())); source.setScroll(TimeValue.timeValueMillis(deleteQuery.getScrollTimeInMillis()));
@ -234,11 +233,11 @@ class RequestFactory {
} }
public GetRequest getRequest(GetQuery query, IndexCoordinates index) { public GetRequest getRequest(GetQuery query, IndexCoordinates index) {
return new GetRequest(index.getIndexName(), index.getTypeName(), query.getId()); return new GetRequest(index.getIndexName(), query.getId());
} }
public GetRequestBuilder getRequestBuilder(Client client, GetQuery query, IndexCoordinates index) { public GetRequestBuilder getRequestBuilder(Client client, GetQuery query, IndexCoordinates index) {
return client.prepareGet(index.getIndexName(), index.getTypeName(), query.getId()); return client.prepareGet(index.getIndexName(), null, query.getId());
} }
public HighlightBuilder highlightBuilder(Query query) { public HighlightBuilder highlightBuilder(Query query) {
@ -265,7 +264,6 @@ class RequestFactory {
public IndexRequest indexRequest(IndexQuery query, IndexCoordinates index) { public IndexRequest indexRequest(IndexQuery query, IndexCoordinates index) {
String indexName = index.getIndexName(); String indexName = index.getIndexName();
String type = index.getTypeName();
IndexRequest indexRequest; IndexRequest indexRequest;
@ -273,17 +271,17 @@ class RequestFactory {
String id = StringUtils.isEmpty(query.getId()) ? getPersistentEntityId(query.getObject()) : query.getId(); String id = StringUtils.isEmpty(query.getId()) ? getPersistentEntityId(query.getObject()) : query.getId();
// If we have a query id and a document id, do not ask ES to generate one. // If we have a query id and a document id, do not ask ES to generate one.
if (id != null) { if (id != null) {
indexRequest = new IndexRequest(indexName, type, id); indexRequest = new IndexRequest(indexName).id(id);
} else { } else {
indexRequest = new IndexRequest(indexName, type); indexRequest = new IndexRequest(indexName);
} }
indexRequest.source(elasticsearchConverter.mapObject(query.getObject()).toJson(), Requests.INDEX_CONTENT_TYPE); indexRequest.source(elasticsearchConverter.mapObject(query.getObject()).toJson(), Requests.INDEX_CONTENT_TYPE);
} else if (query.getSource() != null) { } else if (query.getSource() != null) {
indexRequest = new IndexRequest(indexName, type, query.getId()).source(query.getSource(), indexRequest = new IndexRequest(indexName).id(query.getId()).source(query.getSource(),
Requests.INDEX_CONTENT_TYPE); Requests.INDEX_CONTENT_TYPE);
} else { } else {
throw new ElasticsearchException( throw new ElasticsearchException(
"object or source is null, failed to index the document [id: " + query.getId() + "]"); "object or source is null, failed to index the document [id: " + query.getId() + ']');
} }
if (query.getVersion() != null) { if (query.getVersion() != null) {
indexRequest.version(query.getVersion()); indexRequest.version(query.getVersion());
@ -296,7 +294,7 @@ class RequestFactory {
public IndexRequestBuilder indexRequestBuilder(Client client, IndexQuery query, IndexCoordinates index) { public IndexRequestBuilder indexRequestBuilder(Client client, IndexQuery query, IndexCoordinates index) {
String indexName = index.getIndexName(); String indexName = index.getIndexName();
String type = index.getTypeName(); String type = IndexCoordinates.TYPE;
IndexRequestBuilder indexRequestBuilder; IndexRequestBuilder indexRequestBuilder;
@ -315,7 +313,7 @@ class RequestFactory {
Requests.INDEX_CONTENT_TYPE); Requests.INDEX_CONTENT_TYPE);
} else { } else {
throw new ElasticsearchException( throw new ElasticsearchException(
"object or source is null, failed to index the document [id: " + query.getId() + "]"); "object or source is null, failed to index the document [id: " + query.getId() + ']');
} }
if (query.getVersion() != null) { if (query.getVersion() != null) {
indexRequestBuilder.setVersion(query.getVersion()); indexRequestBuilder.setVersion(query.getVersion());
@ -327,8 +325,7 @@ class RequestFactory {
} }
public MoreLikeThisQueryBuilder moreLikeThisQueryBuilder(MoreLikeThisQuery query, IndexCoordinates index) { public MoreLikeThisQueryBuilder moreLikeThisQueryBuilder(MoreLikeThisQuery query, IndexCoordinates index) {
MoreLikeThisQueryBuilder.Item item = new MoreLikeThisQueryBuilder.Item(index.getIndexName(), index.getTypeName(), MoreLikeThisQueryBuilder.Item item = new MoreLikeThisQueryBuilder.Item(index.getIndexName(), query.getId());
query.getId());
MoreLikeThisQueryBuilder moreLikeThisQueryBuilder = QueryBuilders MoreLikeThisQueryBuilder moreLikeThisQueryBuilder = QueryBuilders
.moreLikeThisQuery(new MoreLikeThisQueryBuilder.Item[] { item }); .moreLikeThisQuery(new MoreLikeThisQueryBuilder.Item[] { item });
@ -414,7 +411,7 @@ class RequestFactory {
UpdateRequest queryUpdateRequest = query.getUpdateRequest(); UpdateRequest queryUpdateRequest = query.getUpdateRequest();
UpdateRequest updateRequest = new UpdateRequest(index.getIndexName(), index.getTypeName(), query.getId()) // UpdateRequest updateRequest = new UpdateRequest(index.getIndexName(), query.getId()) //
.routing(queryUpdateRequest.routing()) // .routing(queryUpdateRequest.routing()) //
.retryOnConflict(queryUpdateRequest.retryOnConflict()) // .retryOnConflict(queryUpdateRequest.retryOnConflict()) //
.timeout(queryUpdateRequest.timeout()) // .timeout(queryUpdateRequest.timeout()) //
@ -455,7 +452,7 @@ class RequestFactory {
UpdateRequest queryUpdateRequest = query.getUpdateRequest(); UpdateRequest queryUpdateRequest = query.getUpdateRequest();
UpdateRequestBuilder updateRequestBuilder = client UpdateRequestBuilder updateRequestBuilder = client
.prepareUpdate(index.getIndexName(), index.getTypeName(), query.getId()) // .prepareUpdate(index.getIndexName(), IndexCoordinates.TYPE, query.getId()) //
.setRouting(queryUpdateRequest.routing()) // .setRouting(queryUpdateRequest.routing()) //
.setRetryOnConflict(queryUpdateRequest.retryOnConflict()) // .setRetryOnConflict(queryUpdateRequest.retryOnConflict()) //
.setTimeout(queryUpdateRequest.timeout()) // .setTimeout(queryUpdateRequest.timeout()) //
@ -490,77 +487,14 @@ class RequestFactory {
} }
private SearchRequest prepareSearchRequest(Query query, @Nullable Class<?> clazz, IndexCoordinates index) { private SearchRequest prepareSearchRequest(Query query, @Nullable Class<?> clazz, IndexCoordinates index) {
return prepareSearchRequest(query, Optional.empty(), clazz, index);
}
public PutMappingRequest putMappingRequest(IndexCoordinates index, Object mapping) {
PutMappingRequest request = new PutMappingRequest(index.getIndexName()).type(index.getTypeName());
if (mapping instanceof String) {
request.source(String.valueOf(mapping), XContentType.JSON);
} else if (mapping instanceof Map) {
request.source((Map) mapping);
} else if (mapping instanceof XContentBuilder) {
request.source((XContentBuilder) mapping);
}
return request;
}
public PutMappingRequestBuilder putMappingRequestBuilder(Client client, IndexCoordinates index, Object mapping) {
PutMappingRequestBuilder requestBuilder = client.admin().indices().preparePutMapping(index.getIndexName())
.setType(index.getTypeName());
if (mapping instanceof String) {
requestBuilder.setSource(String.valueOf(mapping), XContentType.JSON);
} else if (mapping instanceof Map) {
requestBuilder.setSource((Map) mapping);
} else if (mapping instanceof XContentBuilder) {
requestBuilder.setSource((XContentBuilder) mapping);
}
return requestBuilder;
}
public MultiGetRequest multiGetRequest(Query query, IndexCoordinates index) {
MultiGetRequest multiGetRequest = new MultiGetRequest();
getMultiRequestItems(query, index).forEach(multiGetRequest::add);
return multiGetRequest;
}
public MultiGetRequestBuilder multiGetRequestBuilder(Client client, Query searchQuery, IndexCoordinates index) {
MultiGetRequestBuilder multiGetRequestBuilder = client.prepareMultiGet();
getMultiRequestItems(searchQuery, index).forEach(multiGetRequestBuilder::add);
return multiGetRequestBuilder;
}
private List<MultiGetRequest.Item> getMultiRequestItems(Query searchQuery, IndexCoordinates index) {
List<MultiGetRequest.Item> items = new ArrayList<>();
if (!isEmpty(searchQuery.getFields())) {
searchQuery.addSourceFilter(new FetchSourceFilter(toArray(searchQuery.getFields()), null));
}
for (String id : searchQuery.getIds()) {
MultiGetRequest.Item item = new MultiGetRequest.Item(index.getIndexName(), index.getTypeName(), id);
if (searchQuery.getRoute() != null) {
item = item.routing(searchQuery.getRoute());
}
items.add(item);
}
return items;
}
private SearchRequest prepareSearchRequest(Query query, Optional<QueryBuilder> builder, @Nullable Class<?> clazz,
IndexCoordinates index) {
Assert.notNull(index.getIndexNames(), "No index defined for Query"); Assert.notNull(index.getIndexNames(), "No index defined for Query");
Assert.notEmpty(index.getIndexNames(), "No index defined for Query"); Assert.notEmpty(index.getIndexNames(), "No index defined for Query");
Assert.notNull(index.getTypeNames(), "No type defined for Query");
SearchRequest request = new SearchRequest(index.getIndexNames()); SearchRequest request = new SearchRequest(index.getIndexNames());
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
request.types(index.getTypeNames());
sourceBuilder.version(true); sourceBuilder.version(true);
sourceBuilder.trackScores(query.getTrackScores()); sourceBuilder.trackScores(query.getTrackScores());
builder.ifPresent(sourceBuilder::query);
if (query.getSourceFilter() != null) { if (query.getSourceFilter() != null) {
SourceFilter sourceFilter = query.getSourceFilter(); SourceFilter sourceFilter = query.getSourceFilter();
sourceBuilder.fetchSource(sourceFilter.getIncludes(), sourceFilter.getExcludes()); sourceBuilder.fetchSource(sourceFilter.getIncludes(), sourceFilter.getExcludes());
@ -612,15 +546,119 @@ class RequestFactory {
return request; return request;
} }
private SearchRequestBuilder prepareSearchRequestBuilder(Query query, Client client, @SuppressWarnings("unchecked")
@Nullable ElasticsearchPersistentEntity<?> entity, IndexCoordinates index) { public PutMappingRequest putMappingRequest(IndexCoordinates index, Object mapping) {
PutMappingRequest request = new PutMappingRequest(index.getIndexName());
if (mapping instanceof String) {
request.source(String.valueOf(mapping), XContentType.JSON);
} else if (mapping instanceof Map) {
request.source((Map<String, ?>) mapping);
} else if (mapping instanceof XContentBuilder) {
request.source((XContentBuilder) mapping);
}
return request;
}
@SuppressWarnings("rawtypes")
public PutMappingRequestBuilder putMappingRequestBuilder(Client client, IndexCoordinates index, Object mapping) {
PutMappingRequestBuilder requestBuilder = client.admin().indices().preparePutMapping(index.getIndexName())
.setType(IndexCoordinates.TYPE);
if (mapping instanceof String) {
requestBuilder.setSource(String.valueOf(mapping), XContentType.JSON);
} else if (mapping instanceof Map) {
requestBuilder.setSource((Map) mapping);
} else if (mapping instanceof XContentBuilder) {
requestBuilder.setSource((XContentBuilder) mapping);
}
return requestBuilder;
}
public MultiGetRequest multiGetRequest(Query query, IndexCoordinates index) {
MultiGetRequest multiGetRequest = new MultiGetRequest();
getMultiRequestItems(query, index).forEach(multiGetRequest::add);
return multiGetRequest;
}
public MultiGetRequestBuilder multiGetRequestBuilder(Client client, Query searchQuery, IndexCoordinates index) {
MultiGetRequestBuilder multiGetRequestBuilder = client.prepareMultiGet();
getMultiRequestItems(searchQuery, index).forEach(multiGetRequestBuilder::add);
return multiGetRequestBuilder;
}
private List<MultiGetRequest.Item> getMultiRequestItems(Query searchQuery, IndexCoordinates index) {
List<MultiGetRequest.Item> items = new ArrayList<>();
if (!isEmpty(searchQuery.getFields())) {
searchQuery.addSourceFilter(new FetchSourceFilter(toArray(searchQuery.getFields()), null));
}
for (String id : searchQuery.getIds()) {
MultiGetRequest.Item item = new MultiGetRequest.Item(index.getIndexName(), id);
if (searchQuery.getRoute() != null) {
item = item.routing(searchQuery.getRoute());
}
items.add(item);
}
return items;
}
private void prepareNativeSearch(NativeSearchQuery query, SearchSourceBuilder sourceBuilder) {
if (!query.getScriptFields().isEmpty()) {
for (ScriptField scriptedField : query.getScriptFields()) {
sourceBuilder.scriptField(scriptedField.fieldName(), scriptedField.script());
}
}
if (query.getCollapseBuilder() != null) {
sourceBuilder.collapse(query.getCollapseBuilder());
}
if (!isEmpty(query.getIndicesBoost())) {
for (IndexBoost indexBoost : query.getIndicesBoost()) {
sourceBuilder.indexBoost(indexBoost.getIndexName(), indexBoost.getBoost());
}
}
if (!isEmpty(query.getAggregations())) {
for (AbstractAggregationBuilder<?> aggregationBuilder : query.getAggregations()) {
sourceBuilder.aggregation(aggregationBuilder);
}
}
}
private void prepareNativeSearch(SearchRequestBuilder searchRequestBuilder, NativeSearchQuery nativeSearchQuery) {
if (!isEmpty(nativeSearchQuery.getScriptFields())) {
for (ScriptField scriptedField : nativeSearchQuery.getScriptFields()) {
searchRequestBuilder.addScriptField(scriptedField.fieldName(), scriptedField.script());
}
}
if (nativeSearchQuery.getCollapseBuilder() != null) {
searchRequestBuilder.setCollapse(nativeSearchQuery.getCollapseBuilder());
}
if (!isEmpty(nativeSearchQuery.getIndicesBoost())) {
for (IndexBoost indexBoost : nativeSearchQuery.getIndicesBoost()) {
searchRequestBuilder.addIndexBoost(indexBoost.getIndexName(), indexBoost.getBoost());
}
}
if (!isEmpty(nativeSearchQuery.getAggregations())) {
for (AbstractAggregationBuilder<?> aggregationBuilder : nativeSearchQuery.getAggregations()) {
searchRequestBuilder.addAggregation(aggregationBuilder);
}
}
}
private SearchRequestBuilder prepareSearchRequestBuilder(Query query, Client client, @Nullable Class<?> clazz,
IndexCoordinates index) {
Assert.notNull(index.getIndexNames(), "No index defined for Query"); Assert.notNull(index.getIndexNames(), "No index defined for Query");
Assert.notEmpty(index.getIndexNames(), "No index defined for Query"); Assert.notEmpty(index.getIndexNames(), "No index defined for Query");
Assert.notNull(index.getTypeNames(), "No type defined for Query");
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index.getIndexNames()) // SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index.getIndexNames()) //
.setSearchType(query.getSearchType()) // .setSearchType(query.getSearchType()) //
.setTypes(index.getTypeNames()) //
.setVersion(true) // .setVersion(true) //
.setTrackScores(query.getTrackScores()); .setTrackScores(query.getTrackScores());
@ -654,7 +692,7 @@ class RequestFactory {
searchRequestBuilder.setPreference(query.getPreference()); searchRequestBuilder.setPreference(query.getPreference());
} }
prepareSort(query, searchRequestBuilder, entity); prepareSort(query, searchRequestBuilder, getPersistentEntity(clazz));
HighlightBuilder highlightBuilder = highlightBuilder(query); HighlightBuilder highlightBuilder = highlightBuilder(query);
@ -669,62 +707,7 @@ class RequestFactory {
return searchRequestBuilder; return searchRequestBuilder;
} }
private void prepareNativeSearch(NativeSearchQuery query, SearchSourceBuilder sourceBuilder) { @SuppressWarnings("rawtypes")
NativeSearchQuery nativeSearchQuery = query;
if (!nativeSearchQuery.getScriptFields().isEmpty()) {
for (ScriptField scriptedField : nativeSearchQuery.getScriptFields()) {
sourceBuilder.scriptField(scriptedField.fieldName(), scriptedField.script());
}
}
if (nativeSearchQuery.getCollapseBuilder() != null) {
sourceBuilder.collapse(nativeSearchQuery.getCollapseBuilder());
}
if (!isEmpty(nativeSearchQuery.getIndicesBoost())) {
for (IndexBoost indexBoost : nativeSearchQuery.getIndicesBoost()) {
sourceBuilder.indexBoost(indexBoost.getIndexName(), indexBoost.getBoost());
}
}
if (!isEmpty(nativeSearchQuery.getAggregations())) {
for (AbstractAggregationBuilder aggregationBuilder : nativeSearchQuery.getAggregations()) {
sourceBuilder.aggregation(aggregationBuilder);
}
}
}
private void prepareNativeSearch(SearchRequestBuilder searchRequestBuilder, NativeSearchQuery nativeSearchQuery) {
if (!isEmpty(nativeSearchQuery.getScriptFields())) {
for (ScriptField scriptedField : nativeSearchQuery.getScriptFields()) {
searchRequestBuilder.addScriptField(scriptedField.fieldName(), scriptedField.script());
}
}
if (nativeSearchQuery.getCollapseBuilder() != null) {
searchRequestBuilder.setCollapse(nativeSearchQuery.getCollapseBuilder());
}
if (!isEmpty(nativeSearchQuery.getIndicesBoost())) {
for (IndexBoost indexBoost : nativeSearchQuery.getIndicesBoost()) {
searchRequestBuilder.addIndexBoost(indexBoost.getIndexName(), indexBoost.getBoost());
}
}
if (!isEmpty(nativeSearchQuery.getAggregations())) {
for (AbstractAggregationBuilder aggregationBuilder : nativeSearchQuery.getAggregations()) {
searchRequestBuilder.addAggregation(aggregationBuilder);
}
}
}
private SearchRequestBuilder prepareSearchRequestBuilder(Query query, Client client, @Nullable Class<?> clazz,
IndexCoordinates index) {
return prepareSearchRequestBuilder(query, client, getPersistentEntity(clazz), index);
}
private void prepareSort(Query query, SearchSourceBuilder sourceBuilder, private void prepareSort(Query query, SearchSourceBuilder sourceBuilder,
@Nullable ElasticsearchPersistentEntity<?> entity) { @Nullable ElasticsearchPersistentEntity<?> entity) {
@ -741,6 +724,7 @@ class RequestFactory {
} }
} }
@SuppressWarnings("rawtypes")
private void prepareSort(Query query, SearchRequestBuilder searchRequestBuilder, private void prepareSort(Query query, SearchRequestBuilder searchRequestBuilder,
@Nullable ElasticsearchPersistentEntity<?> entity) { @Nullable ElasticsearchPersistentEntity<?> entity) {
if (query.getSort() != null) { if (query.getSort() != null) {
@ -756,7 +740,7 @@ class RequestFactory {
} }
} }
private SortBuilder getSortBuilder(Sort.Order order, @Nullable ElasticsearchPersistentEntity<?> entity) { private SortBuilder<?> getSortBuilder(Sort.Order order, @Nullable ElasticsearchPersistentEntity<?> entity) {
SortOrder sortOrder = order.getDirection().isDescending() ? SortOrder.DESC : SortOrder.ASC; SortOrder sortOrder = order.getDirection().isDescending() ? SortOrder.DESC : SortOrder.ASC;
if (ScoreSortBuilder.NAME.equals(order.getProperty())) { if (ScoreSortBuilder.NAME.equals(order.getProperty())) {
@ -854,7 +838,7 @@ class RequestFactory {
return null; return null;
} }
private VersionType retrieveVersionTypeFromPersistentEntity(Class clazz) { private VersionType retrieveVersionTypeFromPersistentEntity(Class<?> clazz) {
if (clazz != null) { if (clazz != null) {
return elasticsearchConverter.getMappingContext().getRequiredPersistentEntity(clazz).getVersionType(); return elasticsearchConverter.getMappingContext().getRequiredPersistentEntity(clazz).getVersionType();

View File

@ -60,7 +60,7 @@ public final class SearchHitSupport {
if (result instanceof AggregatedPage<?>) { if (result instanceof AggregatedPage<?>) {
AggregatedPage<?> page = (AggregatedPage<?>) result; AggregatedPage<?> page = (AggregatedPage<?>) result;
List<?> list = page.getContent().stream().map(o -> unwrapSearchHits(o)).collect(Collectors.toList()); List<?> list = page.getContent().stream().map(SearchHitSupport::unwrapSearchHits).collect(Collectors.toList());
return new AggregatedPageImpl<>(list, null, page.getTotalElements(), page.getAggregations(), page.getScrollId(), return new AggregatedPageImpl<>(list, null, page.getTotalElements(), page.getAggregations(), page.getScrollId(),
page.getMaxScore()); page.getMaxScore());

View File

@ -237,6 +237,7 @@ public interface SearchOperations {
* @return scrolled page result * @return scrolled page result
* @deprecated since 4.0, use {@link #searchScrollContinue(String, long, Class)}. * @deprecated since 4.0, use {@link #searchScrollContinue(String, long, Class)}.
*/ */
@SuppressWarnings("unchecked")
@Deprecated @Deprecated
default <T> ScrolledPage<T> continueScroll(@Nullable String scrollId, long scrollTimeInMillis, Class<T> clazz) { default <T> ScrolledPage<T> continueScroll(@Nullable String scrollId, long scrollTimeInMillis, Class<T> clazz) {
return (ScrolledPage<T>) SearchHitSupport return (ScrolledPage<T>) SearchHitSupport

View File

@ -16,13 +16,8 @@
package org.springframework.data.elasticsearch.core.client.support; package org.springframework.data.elasticsearch.core.client.support;
import lombok.Data; import lombok.Data;
import lombok.Getter;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
@Data @Data

View File

@ -84,6 +84,7 @@ public class DefaultElasticsearchTypeMapper extends DefaultTypeMapper<Map<String
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.convert.TypeAliasAccessor#readAliasFrom(java.lang.Object) * @see org.springframework.data.convert.TypeAliasAccessor#readAliasFrom(java.lang.Object)
*/ */
@Override
public Alias readAliasFrom(Map<String, Object> source) { public Alias readAliasFrom(Map<String, Object> source) {
return Alias.ofNullable(source.get(typeKey)); return Alias.ofNullable(source.get(typeKey));
} }
@ -92,6 +93,7 @@ public class DefaultElasticsearchTypeMapper extends DefaultTypeMapper<Map<String
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.convert.TypeAliasAccessor#writeTypeTo(java.lang.Object, java.lang.Object) * @see org.springframework.data.convert.TypeAliasAccessor#writeTypeTo(java.lang.Object, java.lang.Object)
*/ */
@Override
public void writeTypeTo(Map<String, Object> sink, Object alias) { public void writeTypeTo(Map<String, Object> sink, Object alias) {
if (typeKey == null) { if (typeKey == null) {

View File

@ -33,6 +33,7 @@ import org.springframework.util.NumberUtils;
* Elasticsearch specific {@link CustomConversions}. * Elasticsearch specific {@link CustomConversions}.
* *
* @author Christoph Strobl * @author Christoph Strobl
* @author Peter-Josef Meisch
* @since 3.2 * @since 3.2
*/ */
public class ElasticsearchCustomConversions extends CustomConversions { public class ElasticsearchCustomConversions extends CustomConversions {
@ -42,9 +43,7 @@ public class ElasticsearchCustomConversions extends CustomConversions {
static { static {
List<Object> converters = new ArrayList<>(); List<Object> converters = new ArrayList<>(GeoConverters.getConvertersToRegister());
converters.addAll(GeoConverters.getConvertersToRegister());
converters.add(StringToUUIDConverter.INSTANCE); converters.add(StringToUUIDConverter.INSTANCE);
converters.add(UUIDToStringConverter.INSTANCE); converters.add(UUIDToStringConverter.INSTANCE);
converters.add(BigDecimalToDoubleConverter.INSTANCE); converters.add(BigDecimalToDoubleConverter.INSTANCE);

View File

@ -169,9 +169,10 @@ public class MappingElasticsearchConverter
.map(searchDocument -> read(type, searchDocument)) // .map(searchDocument -> read(type, searchDocument)) //
.collect(Collectors.toList()); .collect(Collectors.toList());
Aggregations aggregations = searchDocumentResponse.getAggregations(); Aggregations aggregations = searchDocumentResponse.getAggregations();
return new SearchHits<T>(totalHits, maxScore, scrollId, searchHits, aggregations); return new SearchHits<>(totalHits, maxScore, scrollId, searchHits, aggregations);
} }
@Override
public <T> SearchHit<T> read(Class<T> type, SearchDocument searchDocument) { public <T> SearchHit<T> read(Class<T> type, SearchDocument searchDocument) {
Assert.notNull(type, "type must not be null"); Assert.notNull(type, "type must not be null");
@ -182,7 +183,7 @@ public class MappingElasticsearchConverter
Object[] sortValues = searchDocument.getSortValues(); Object[] sortValues = searchDocument.getSortValues();
T content = mapDocument(searchDocument, type); T content = mapDocument(searchDocument, type);
return new SearchHit<T>(id, score, sortValues, content); return new SearchHit<>(id, score, sortValues, content);
} }
@Override @Override

View File

@ -372,9 +372,7 @@ public class DocumentAdapters {
Objects.requireNonNull(action); Objects.requireNonNull(action);
documentFields.forEach(field -> { documentFields.forEach(field -> action.accept(field.getName(), getValue(field)));
action.accept(field.getName(), getValue(field));
});
} }
/* /*
@ -719,7 +717,7 @@ public class DocumentAdapters {
String id = hasId() ? getId() : "?"; String id = hasId() ? getId() : "?";
String version = hasVersion() ? Long.toString(getVersion()) : "?"; String version = hasVersion() ? Long.toString(getVersion()) : "?";
return getClass().getSimpleName() + "@" + id + "#" + version + " " + toJson(); return getClass().getSimpleName() + '@' + id + '#' + version + ' ' + toJson();
} }
} }
} }

View File

@ -281,6 +281,6 @@ class MapDocument implements Document {
String id = hasId() ? getId() : "?"; String id = hasId() ? getId() : "?";
String version = hasVersion() ? Long.toString(getVersion()) : "?"; String version = hasVersion() ? Long.toString(getVersion()) : "?";
return getClass().getSimpleName() + "@" + id + "#" + version + " " + toJson(); return getClass().getSimpleName() + '@' + id + '#' + version + ' ' + toJson();
} }
} }

View File

@ -31,7 +31,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.Transient;
import org.springframework.data.elasticsearch.annotations.*; import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.annotations.CompletionContext;
import org.springframework.data.elasticsearch.annotations.CompletionField;
import org.springframework.data.elasticsearch.annotations.DynamicMapping;
import org.springframework.data.elasticsearch.annotations.DynamicTemplates;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.Mapping;
import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ResourceUtil; import org.springframework.data.elasticsearch.core.ResourceUtil;
import org.springframework.data.elasticsearch.core.completion.Completion; import org.springframework.data.elasticsearch.core.completion.Completion;
@ -39,6 +49,7 @@ import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverte
import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.mapping.MappingException;
import org.springframework.data.mapping.PropertyHandler; import org.springframework.data.mapping.PropertyHandler;
import org.springframework.data.util.TypeInformation; import org.springframework.data.util.TypeInformation;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
@ -95,14 +106,15 @@ public class MappingBuilder {
* builds the Elasticsearch mapping for the given clazz. * builds the Elasticsearch mapping for the given clazz.
* *
* @return JSON string * @return JSON string
* @throws IOException * @throws ElasticsearchException on errors while building the mapping
*/ */
public String buildPropertyMapping(Class<?> clazz) throws IOException { public String buildPropertyMapping(Class<?> clazz) throws ElasticsearchException {
try {
ElasticsearchPersistentEntity<?> entity = elasticsearchConverter.getMappingContext() ElasticsearchPersistentEntity<?> entity = elasticsearchConverter.getMappingContext()
.getRequiredPersistentEntity(clazz); .getRequiredPersistentEntity(clazz);
XContentBuilder builder = jsonBuilder().startObject().startObject(entity.getIndexCoordinates().getTypeName()); XContentBuilder builder = jsonBuilder().startObject();
// Dynamic templates // Dynamic templates
addDynamicTemplatesMapping(builder, entity); addDynamicTemplatesMapping(builder, entity);
@ -115,11 +127,13 @@ public class MappingBuilder {
mapEntity(builder, entity, true, "", false, FieldType.Auto, null, entity.findAnnotation(DynamicMapping.class)); mapEntity(builder, entity, true, "", false, FieldType.Auto, null, entity.findAnnotation(DynamicMapping.class));
builder.endObject() // indexType builder.endObject() // root object
.endObject() // root object
.close(); .close();
return builder.getOutputStream().toString(); return builder.getOutputStream().toString();
} catch (MappingException | IOException e) {
throw new ElasticsearchException("could not build mapping", e);
}
} }
private void mapEntity(XContentBuilder builder, @Nullable ElasticsearchPersistentEntity entity, boolean isRootObject, private void mapEntity(XContentBuilder builder, @Nullable ElasticsearchPersistentEntity entity, boolean isRootObject,

View File

@ -44,6 +44,7 @@ public interface ElasticsearchPersistentEntity<T> extends PersistentEntity<T, El
String getIndexStoreType(); String getIndexStoreType();
@Override
ElasticsearchPersistentProperty getVersionProperty(); ElasticsearchPersistentProperty getVersionProperty();
String getParentType(); String getParentType();

View File

@ -41,7 +41,7 @@ public interface ElasticsearchPersistentProperty extends PersistentProperty<Elas
* Returns whether the current property is a <em>potential</em> score property of the owning * Returns whether the current property is a <em>potential</em> score property of the owning
* {@link ElasticsearchPersistentEntity}. This method is mainly used by {@link ElasticsearchPersistentEntity} * {@link ElasticsearchPersistentEntity}. This method is mainly used by {@link ElasticsearchPersistentEntity}
* implementation to discover score property candidates on {@link ElasticsearchPersistentEntity} creation you should * implementation to discover score property candidates on {@link ElasticsearchPersistentEntity} creation you should
* rather call {@link ElasticsearchPersistentEntity#isScoreProperty(PersistentProperty)} to determine whether the * rather call {@link ElasticsearchPersistentEntity#getScoreProperty()} to determine whether the
* current property is the score property of that {@link ElasticsearchPersistentEntity} under consideration. * current property is the score property of that {@link ElasticsearchPersistentEntity} under consideration.
* *
* @return * @return
@ -53,7 +53,7 @@ public interface ElasticsearchPersistentProperty extends PersistentProperty<Elas
* Returns whether the current property is a <em>potential</em> parent property of the owning * Returns whether the current property is a <em>potential</em> parent property of the owning
* {@link ElasticsearchPersistentEntity}. This method is mainly used by {@link ElasticsearchPersistentEntity} * {@link ElasticsearchPersistentEntity}. This method is mainly used by {@link ElasticsearchPersistentEntity}
* implementation to discover parent property candidates on {@link ElasticsearchPersistentEntity} creation you should * implementation to discover parent property candidates on {@link ElasticsearchPersistentEntity} creation you should
* rather call {@link ElasticsearchPersistentEntity#isParentProperty()} to determine whether the current property is * rather call {@link ElasticsearchPersistentEntity#getScoreProperty()} to determine whether the current property is
* the parent property of that {@link ElasticsearchPersistentEntity} under consideration. * the parent property of that {@link ElasticsearchPersistentEntity} under consideration.
* *
* @return * @return
@ -78,6 +78,7 @@ public interface ElasticsearchPersistentProperty extends PersistentProperty<Elas
INSTANCE; INSTANCE;
@Override
public String convert(ElasticsearchPersistentProperty source) { public String convert(ElasticsearchPersistentProperty source) {
return source.getFieldName(); return source.getFieldName();
} }
@ -91,6 +92,7 @@ public interface ElasticsearchPersistentProperty extends PersistentProperty<Elas
INSTANCE; INSTANCE;
@Override
public String convert(ElasticsearchPersistentProperty source) { public String convert(ElasticsearchPersistentProperty source) {
return source.getName(); return source.getName();
} }

View File

@ -31,6 +31,8 @@ import org.springframework.util.Assert;
*/ */
public class IndexCoordinates { public class IndexCoordinates {
public static final String TYPE = "_doc";
private final String[] indexNames; private final String[] indexNames;
private final String[] typeNames; private final String[] typeNames;

View File

@ -20,12 +20,13 @@ import java.util.List;
import org.elasticsearch.action.support.ActiveShardCount; import org.elasticsearch.action.support.ActiveShardCount;
import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
/** /**
* Options that may be passed to an * Options that may be passed to an
* {@link org.springframework.data.elasticsearch.core.ElasticsearchOperations#bulkIndex(List, BulkOptions)} or * {@link org.springframework.data.elasticsearch.core.DocumentOperations#bulkIndex(List, BulkOptions, IndexCoordinates)} or
* {@link org.springframework.data.elasticsearch.core.ElasticsearchOperations#bulkUpdate(List, BulkOptions)} call. <br/> * {@link org.springframework.data.elasticsearch.core.DocumentOperations#bulkUpdate(List, BulkOptions, IndexCoordinates)} call. <br/>
* Use {@link BulkOptions#builder()} to obtain a builder, then set the desired properties and call * Use {@link BulkOptions#builder()} to obtain a builder, then set the desired properties and call
* {@link BulkOptionsBuilder#build()} to get the BulkOptions object. * {@link BulkOptionsBuilder#build()} to get the BulkOptions object.
* *

View File

@ -515,8 +515,8 @@ public class Criteria {
private void assertNoBlankInWildcardedQuery(String searchString, boolean leadingWildcard, boolean trailingWildcard) { private void assertNoBlankInWildcardedQuery(String searchString, boolean leadingWildcard, boolean trailingWildcard) {
if (searchString != null && searchString.contains(CRITERIA_VALUE_SEPERATOR)) { if (searchString != null && searchString.contains(CRITERIA_VALUE_SEPERATOR)) {
throw new InvalidDataAccessApiUsageException("Cannot constructQuery '" + (leadingWildcard ? "*" : "") + "\"" throw new InvalidDataAccessApiUsageException("Cannot constructQuery '" + (leadingWildcard ? "*" : "") + '"'
+ searchString + "\"" + (trailingWildcard ? "*" : "") + "'. Use expression or multiple clauses instead."); + searchString + '"' + (trailingWildcard ? "*" : "") + "'. Use expression or multiple clauses instead.");
} }
} }
@ -618,7 +618,7 @@ public class Criteria {
/** /**
* @since 4.0 * @since 4.0
*/ */
EXISTS; EXISTS
} }
public static class CriteriaEntry { public static class CriteriaEntry {

View File

@ -24,6 +24,7 @@ import org.springframework.util.Assert;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
* @author Mark Paluch * @author Mark Paluch
* @author Peter-Josef Meisch
*/ */
public class CriteriaQuery extends AbstractQuery { public class CriteriaQuery extends AbstractQuery {
@ -45,7 +46,7 @@ public class CriteriaQuery extends AbstractQuery {
this.addSort(pageable.getSort()); this.addSort(pageable.getSort());
} }
public static final Query fromQuery(CriteriaQuery source) { public static Query fromQuery(CriteriaQuery source) {
return fromQuery(source, new CriteriaQuery()); return fromQuery(source, new CriteriaQuery());
} }

View File

@ -39,7 +39,6 @@ public class FetchSourceFilterBuilder {
if (includes == null) includes = new String[0]; if (includes == null) includes = new String[0];
if (excludes == null) excludes = new String[0]; if (excludes == null) excludes = new String[0];
SourceFilter sourceFilter = new FetchSourceFilter(includes, excludes); return new FetchSourceFilter(includes, excludes);
return sourceFilter;
} }
} }

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.core.query; package org.springframework.data.elasticsearch.core.query;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateRequest;
/** /**

View File

@ -18,7 +18,6 @@ package org.springframework.data.elasticsearch.repository;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.repository.NoRepositoryBean; import org.springframework.data.repository.NoRepositoryBean;

View File

@ -90,7 +90,7 @@ abstract class AbstractReactiveElasticsearchRepositoryQuery implements Repositor
IndexCoordinates index = IndexCoordinates.of(indexName).withTypes(indexTypeName); IndexCoordinates index = IndexCoordinates.of(indexName).withTypes(indexTypeName);
ReactiveElasticsearchQueryExecution execution = getExecution(parameterAccessor, ReactiveElasticsearchQueryExecution execution = getExecution(parameterAccessor,
new ResultProcessingConverter(processor, elasticsearchOperations)); new ResultProcessingConverter(processor));
return execution.execute(query, processor.getReturnedType().getDomainType(), targetType, index); return execution.execute(query, processor.getReturnedType().getDomainType(), targetType, index);
} }

View File

@ -19,11 +19,17 @@ import org.springframework.data.repository.core.EntityMetadata;
/** /**
* @author Christoph Strobl * @author Christoph Strobl
* @author Peter-Josef Meisch
* @since 3.2 * @since 3.2
*/ */
public interface ElasticsearchEntityMetadata<T> extends EntityMetadata<T> { public interface ElasticsearchEntityMetadata<T> extends EntityMetadata<T> {
String getIndexName(); String getIndexName();
/**
* @return the type for the index
* @deprecated since 4.0
*/
@Deprecated
String getIndexTypeName(); String getIndexTypeName();
} }

View File

@ -26,6 +26,7 @@ import org.springframework.data.repository.query.Parameters;
/** /**
* @author Christoph Strobl * @author Christoph Strobl
* @author Peter-Josef Meisch
* @since 3.2 * @since 3.2
*/ */
public class ElasticsearchParameters extends Parameters<ElasticsearchParameters, ElasticsearchParameter> { public class ElasticsearchParameters extends Parameters<ElasticsearchParameters, ElasticsearchParameter> {
@ -55,26 +56,14 @@ public class ElasticsearchParameters extends Parameters<ElasticsearchParameters,
*/ */
class ElasticsearchParameter extends Parameter { class ElasticsearchParameter extends Parameter {
private final MethodParameter parameter;
/** /**
* Creates a new {@link ElasticsearchParameter}. * Creates a new {@link ElasticsearchParameter}.
* *
* @param parameter must not be {@literal null}. * @param parameter must not be {@literal null}.
*/ */
ElasticsearchParameter(MethodParameter parameter) { ElasticsearchParameter(MethodParameter parameter) {
super(parameter); super(parameter);
this.parameter = parameter;
} }
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.Parameter#isSpecialParameter()
*/
@Override
public boolean isSpecialParameter() {
return super.isSpecialParameter();
}
} }
} }

View File

@ -81,13 +81,12 @@ public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery
SearchHits<?> searchHits = elasticsearchOperations.search(query, clazz, index); SearchHits<?> searchHits = elasticsearchOperations.search(query, clazz, index);
result = SearchHitSupport.page(searchHits, query.getPageable()); result = SearchHitSupport.page(searchHits, query.getPageable());
} else if (queryMethod.isStreamQuery()) { } else if (queryMethod.isStreamQuery()) {
Class<?> entityType = clazz;
if (accessor.getPageable().isUnpaged()) { if (accessor.getPageable().isUnpaged()) {
query.setPageable(PageRequest.of(0, DEFAULT_STREAM_BATCH_SIZE)); query.setPageable(PageRequest.of(0, DEFAULT_STREAM_BATCH_SIZE));
} else { } else {
query.setPageable(accessor.getPageable()); query.setPageable(accessor.getPageable());
} }
result = StreamUtils.createStreamFromIterator(elasticsearchOperations.stream(query, entityType, index)); result = StreamUtils.createStreamFromIterator(elasticsearchOperations.stream(query, clazz, index));
} else if (queryMethod.isCollectionQuery()) { } else if (queryMethod.isCollectionQuery()) {
if (accessor.getPageable().isUnpaged()) { if (accessor.getPageable().isUnpaged()) {

View File

@ -67,6 +67,7 @@ public class ElasticsearchQueryMethod extends QueryMethod {
* @return the {@link ElasticsearchEntityMetadata} for the query methods {@link #getReturnedObjectType() return type}. * @return the {@link ElasticsearchEntityMetadata} for the query methods {@link #getReturnedObjectType() return type}.
* @since 3.2 * @since 3.2
*/ */
@Override
public ElasticsearchEntityMetadata<?> getEntityInformation() { public ElasticsearchEntityMetadata<?> getEntityInformation() {
if (metadata == null) { if (metadata == null) {

View File

@ -44,9 +44,7 @@ class ReactiveElasticsearchParametersParameterAccessor extends ElasticsearchPara
this.subscriptions = new ArrayList<>(values.length); this.subscriptions = new ArrayList<>(values.length);
for (int i = 0; i < values.length; i++) { for (Object value : values) {
Object value = values[i];
if (value == null || !ReactiveWrappers.supports(value.getClass())) { if (value == null || !ReactiveWrappers.supports(value.getClass())) {
@ -95,6 +93,7 @@ class ReactiveElasticsearchParametersParameterAccessor extends ElasticsearchPara
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.repository.query.ParametersParameterAccessor#getBindableValue(int) * @see org.springframework.data.repository.query.ParametersParameterAccessor#getBindableValue(int)
*/ */
@Override
public Object getBindableValue(int index) { public Object getBindableValue(int index) {
return getValue(getParameters().getBindableParameter(index).getIndex()); return getValue(getParameters().getBindableParameter(index).getIndex());
} }

View File

@ -17,7 +17,6 @@ package org.springframework.data.elasticsearch.repository.query;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations;
import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.repository.query.ResultProcessor; import org.springframework.data.repository.query.ResultProcessor;
import org.springframework.data.repository.query.ReturnedType; import org.springframework.data.repository.query.ReturnedType;
@ -66,13 +65,10 @@ public interface ReactiveElasticsearchQueryExecution {
final class ResultProcessingConverter implements Converter<Object, Object> { final class ResultProcessingConverter implements Converter<Object, Object> {
private final ResultProcessor processor; private final ResultProcessor processor;
private final ReactiveElasticsearchOperations operations;
public ResultProcessingConverter(ResultProcessor processor, ReactiveElasticsearchOperations operations) { public ResultProcessingConverter(ResultProcessor processor) {
Assert.notNull(processor, "processor must not be null"); Assert.notNull(processor, "processor must not be null");
Assert.notNull(operations, "operations must not be null");
this.processor = processor; this.processor = processor;
this.operations = operations;
} }
/* /*

View File

@ -38,6 +38,7 @@ import org.springframework.util.ClassUtils;
/** /**
* @author Christoph Strobl * @author Christoph Strobl
* @author Peter-Josef Meisch
* @since 3.2 * @since 3.2
*/ */
public class ReactiveElasticsearchQueryMethod extends ElasticsearchQueryMethod { public class ReactiveElasticsearchQueryMethod extends ElasticsearchQueryMethod {
@ -45,13 +46,10 @@ public class ReactiveElasticsearchQueryMethod extends ElasticsearchQueryMethod {
private static final ClassTypeInformation<Page> PAGE_TYPE = ClassTypeInformation.from(Page.class); private static final ClassTypeInformation<Page> PAGE_TYPE = ClassTypeInformation.from(Page.class);
private static final ClassTypeInformation<Slice> SLICE_TYPE = ClassTypeInformation.from(Slice.class); private static final ClassTypeInformation<Slice> SLICE_TYPE = ClassTypeInformation.from(Slice.class);
private final Method method;
public ReactiveElasticsearchQueryMethod(Method method, RepositoryMetadata metadata, ProjectionFactory factory, public ReactiveElasticsearchQueryMethod(Method method, RepositoryMetadata metadata, ProjectionFactory factory,
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) { MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
super(method, metadata, factory, mappingContext); super(method, metadata, factory, mappingContext);
this.method = method;
if (hasParameterOfType(method, Pageable.class)) { if (hasParameterOfType(method, Pageable.class)) {

View File

@ -30,13 +30,12 @@ import org.springframework.data.repository.query.parser.PartTree;
public class ReactivePartTreeElasticsearchQuery extends AbstractReactiveElasticsearchRepositoryQuery { public class ReactivePartTreeElasticsearchQuery extends AbstractReactiveElasticsearchRepositoryQuery {
private final PartTree tree; private final PartTree tree;
private final ResultProcessor processor;
public ReactivePartTreeElasticsearchQuery(ReactiveElasticsearchQueryMethod queryMethod, public ReactivePartTreeElasticsearchQuery(ReactiveElasticsearchQueryMethod queryMethod,
ReactiveElasticsearchOperations elasticsearchOperations) { ReactiveElasticsearchOperations elasticsearchOperations) {
super(queryMethod, elasticsearchOperations); super(queryMethod, elasticsearchOperations);
this.processor = queryMethod.getResultProcessor(); ResultProcessor processor = queryMethod.getResultProcessor();
this.tree = new PartTree(queryMethod.getName(), processor.getReturnedType().getDomainType()); this.tree = new PartTree(queryMethod.getName(), processor.getReturnedType().getDomainType());
} }

View File

@ -16,10 +16,12 @@
package org.springframework.data.elasticsearch.repository.query; package org.springframework.data.elasticsearch.repository.query;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
* @author Christoph Strobl * @author Christoph Strobl
* @author Peter-Josef Meisch
* @since 3.2 * @since 3.2
*/ */
public class SimpleElasticsearchEntityMetadata<T> implements ElasticsearchEntityMetadata<T> { public class SimpleElasticsearchEntityMetadata<T> implements ElasticsearchEntityMetadata<T> {
@ -43,7 +45,7 @@ public class SimpleElasticsearchEntityMetadata<T> implements ElasticsearchEntity
@Override @Override
public String getIndexTypeName() { public String getIndexTypeName() {
return entity.getIndexCoordinates().getTypeName(); return IndexCoordinates.TYPE;
} }
@Override @Override

View File

@ -101,7 +101,7 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
putMapping(); putMapping();
} }
} catch (ElasticsearchException exception) { } catch (ElasticsearchException exception) {
LOGGER.error("failed to load elasticsearch nodes : {}", exception.getDetailedMessage()); LOGGER.warn("Cannot create index: {}", exception.getDetailedMessage());
} }
} }

View File

@ -106,6 +106,7 @@ public class ReactiveElasticsearchRepositoryFactory extends ReactiveRepositoryFa
* (non-Javadoc) * (non-Javadoc)
* @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getEntityInformation(java.lang.Class) * @see org.springframework.data.repository.core.support.RepositoryFactorySupport#getEntityInformation(java.lang.Class)
*/ */
@Override
public <T, ID> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) { public <T, ID> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
return getEntityInformation(domainClass, null); return getEntityInformation(domainClass, null);
} }

View File

@ -19,10 +19,8 @@ import static org.assertj.core.api.Assertions.*;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.data.elasticsearch.junit.jupiter.ClusterConnectionInfo; import org.springframework.data.elasticsearch.junit.jupiter.ClusterConnectionInfo;
import org.springframework.data.elasticsearch.junit.jupiter.IntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.IntegrationTest;
import org.springframework.data.elasticsearch.junit.jupiter.SpringDataElasticsearchExtension;
/** /**
* Testing the setup and parameter injection of the CusterConnectionInfo. * Testing the setup and parameter injection of the CusterConnectionInfo.

View File

@ -44,6 +44,7 @@ import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.InnerField; import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.GetQuery; import org.springframework.data.elasticsearch.core.query.GetQuery;
@ -66,14 +67,15 @@ import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = { ElasticsearchTemplateConfiguration.class }) @ContextConfiguration(classes = { ElasticsearchTemplateConfiguration.class })
public class NestedObjectTests { public class NestedObjectTests {
@Autowired private ElasticsearchOperations elasticsearchTemplate; @Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
indexOperations = operations.getIndexOperations();
IndexInitializer.init(elasticsearchTemplate, Book.class); IndexInitializer.init(indexOperations, Book.class);
IndexInitializer.init(elasticsearchTemplate, Person.class); IndexInitializer.init(indexOperations, Person.class);
IndexInitializer.init(elasticsearchTemplate, PersonMultipleLevelNested.class); IndexInitializer.init(indexOperations, PersonMultipleLevelNested.class);
} }
@Test @Test
@ -124,14 +126,14 @@ public class NestedObjectTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
IndexCoordinates index = IndexCoordinates.of("test-index-person").withTypes("user"); IndexCoordinates index = IndexCoordinates.of("test-index-person").withTypes("user");
elasticsearchTemplate.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
elasticsearchTemplate.refresh(Person.class); indexOperations.refresh(Person.class);
QueryBuilder builder = nestedQuery("car", QueryBuilder builder = nestedQuery("car",
boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None); boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None);
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
SearchHits<Person> persons = elasticsearchTemplate.search(searchQuery, Person.class, index); SearchHits<Person> persons = operations.search(searchQuery, Person.class, index);
assertThat(persons).hasSize(1); assertThat(persons).hasSize(1);
} }
@ -143,14 +145,14 @@ public class NestedObjectTests {
List<IndexQuery> indexQueries = createPerson(); List<IndexQuery> indexQueries = createPerson();
// when // when
elasticsearchTemplate.bulkIndex(indexQueries, operations.bulkIndex(indexQueries,
IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user")); IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user"));
elasticsearchTemplate.refresh(PersonMultipleLevelNested.class); indexOperations.refresh(PersonMultipleLevelNested.class);
// then // then
GetQuery getQuery = new GetQuery(); GetQuery getQuery = new GetQuery();
getQuery.setId("1"); getQuery.setId("1");
PersonMultipleLevelNested personIndexed = elasticsearchTemplate.get(getQuery, PersonMultipleLevelNested.class, PersonMultipleLevelNested personIndexed = operations.get(getQuery, PersonMultipleLevelNested.class,
IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user")); IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user"));
assertThat(personIndexed).isNotNull(); assertThat(personIndexed).isNotNull();
} }
@ -162,11 +164,11 @@ public class NestedObjectTests {
List<IndexQuery> indexQueries = createPerson(); List<IndexQuery> indexQueries = createPerson();
// when // when
elasticsearchTemplate.bulkIndex(indexQueries, operations.bulkIndex(indexQueries,
IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user")); IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user"));
// then // then
Map<String, Object> mapping = elasticsearchTemplate.getMapping(PersonMultipleLevelNested.class); Map<String, Object> mapping = indexOperations.getMapping(PersonMultipleLevelNested.class);
assertThat(mapping).isNotNull(); assertThat(mapping).isNotNull();
Map<String, Object> propertyMap = (Map<String, Object>) mapping.get("properties"); Map<String, Object> propertyMap = (Map<String, Object>) mapping.get("properties");
@ -183,8 +185,8 @@ public class NestedObjectTests {
// when // when
IndexCoordinates index = IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user"); IndexCoordinates index = IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user");
elasticsearchTemplate.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
elasticsearchTemplate.refresh(PersonMultipleLevelNested.class); indexOperations.refresh(PersonMultipleLevelNested.class);
// then // then
BoolQueryBuilder builder = boolQuery(); BoolQueryBuilder builder = boolQuery();
@ -193,7 +195,7 @@ public class NestedObjectTests {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
SearchHits<PersonMultipleLevelNested> personIndexed = elasticsearchTemplate.search(searchQuery, SearchHits<PersonMultipleLevelNested> personIndexed = operations.search(searchQuery,
PersonMultipleLevelNested.class, index); PersonMultipleLevelNested.class, index);
assertThat(personIndexed).isNotNull(); assertThat(personIndexed).isNotNull();
assertThat(personIndexed.getTotalHits()).isEqualTo(1); assertThat(personIndexed.getTotalHits()).isEqualTo(1);
@ -323,14 +325,14 @@ public class NestedObjectTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
IndexCoordinates index = IndexCoordinates.of("test-index-person").withTypes("user"); IndexCoordinates index = IndexCoordinates.of("test-index-person").withTypes("user");
elasticsearchTemplate.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
elasticsearchTemplate.refresh(Person.class); indexOperations.refresh(Person.class);
// when // when
QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")), ScoreMode.None); QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")), ScoreMode.None);
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
SearchHits<Person> persons = elasticsearchTemplate.search(searchQuery, Person.class, index); SearchHits<Person> persons = operations.search(searchQuery, Person.class, index);
// then // then
assertThat(persons).hasSize(1); assertThat(persons).hasSize(1);
@ -372,13 +374,13 @@ public class NestedObjectTests {
// when // when
IndexCoordinates index = IndexCoordinates.of("test-index-book-nested-objects").withTypes("book"); IndexCoordinates index = IndexCoordinates.of("test-index-book-nested-objects").withTypes("book");
elasticsearchTemplate.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
elasticsearchTemplate.refresh(Book.class); indexOperations.refresh(Book.class);
// then // then
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.None)).build(); .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.None)).build();
SearchHits<Book> books = elasticsearchTemplate.search(searchQuery, Book.class, index); SearchHits<Book> books = operations.search(searchQuery, Book.class, index);
assertThat(books.getSearchHits()).hasSize(1); assertThat(books.getSearchHits()).hasSize(1);
assertThat(books.getSearchHit(0).getContent().getId()).isEqualTo(book2.getId()); assertThat(books.getSearchHit(0).getContent().getId()).isEqualTo(book2.getId());
@ -386,7 +388,7 @@ public class NestedObjectTests {
@Setter @Setter
@Getter @Getter
@Document(indexName = "test-index-book-nested-objects", type = "book", shards = 1, replicas = 0, @Document(indexName = "test-index-book-nested-objects", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class Book { static class Book {
@ -400,7 +402,7 @@ public class NestedObjectTests {
} }
@Data @Data
@Document(indexName = "test-index-person", type = "user", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-index-person", replicas = 0, refreshInterval = "-1")
static class Person { static class Person {
@Id private String id; @Id private String id;
@ -425,7 +427,7 @@ public class NestedObjectTests {
* @author Artur Konczak * @author Artur Konczak
*/ */
@Data @Data
@Document(indexName = "test-index-person-multiple-level-nested", type = "user", shards = 1, replicas = 0, @Document(indexName = "test-index-person-multiple-level-nested", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class PersonMultipleLevelNested { static class PersonMultipleLevelNested {

View File

@ -34,7 +34,6 @@ import org.springframework.data.elasticsearch.client.reactive.ReactiveRestClient
import org.springframework.data.elasticsearch.support.SearchHitsUtil; import org.springframework.data.elasticsearch.support.SearchHitsUtil;
import org.springframework.data.util.Version; import org.springframework.data.util.Version;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/** /**
* @author Christoph Strobl * @author Christoph Strobl
@ -115,7 +114,6 @@ public final class TestUtils {
private static class DocumentLookup implements OfType { private static class DocumentLookup implements OfType {
private String id; private String id;
private String type;
public DocumentLookup(String id) { public DocumentLookup(String id) {
this.id = id; this.id = id;
@ -126,9 +124,6 @@ public final class TestUtils {
public boolean existsIn(String index) { public boolean existsIn(String index) {
GetRequest request = new GetRequest(index).id(id); GetRequest request = new GetRequest(index).id(id);
if (StringUtils.hasText(type)) {
request = request.type(type);
}
try (RestHighLevelClient client = restHighLevelClient()) { try (RestHighLevelClient client = restHighLevelClient()) {
return client.get(request, RequestOptions.DEFAULT).isExists(); return client.get(request, RequestOptions.DEFAULT).isExists();
} }
@ -136,7 +131,6 @@ public final class TestUtils {
@Override @Override
public ExistsIn ofType(String type) { public ExistsIn ofType(String type) {
this.type = type;
return this; return this;
} }
} }

View File

@ -18,6 +18,7 @@ package org.springframework.data.elasticsearch.client.reactive;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.*;
import lombok.SneakyThrows; import lombok.SneakyThrows;
import org.elasticsearch.client.indices.GetIndexRequest;
import reactor.test.StepVerifier; import reactor.test.StepVerifier;
import java.io.IOException; import java.io.IOException;
@ -31,7 +32,6 @@ import java.util.stream.IntStream;
import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.Version; import org.elasticsearch.Version;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest; import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetRequest;
@ -134,17 +134,14 @@ public class ReactiveElasticsearchClientTests {
public void infoShouldReturnClusterInformation() { public void infoShouldReturnClusterInformation() {
client.info().as(StepVerifier::create) // client.info().as(StepVerifier::create) //
.consumeNextWith(it -> { .consumeNextWith(it -> assertThat(it.getVersion()).isGreaterThanOrEqualTo(Version.CURRENT)) //
assertThat(it.getVersion()).isGreaterThanOrEqualTo(Version.CURRENT);
}) //
.verifyComplete(); .verifyComplete();
} }
@Test // DATAES-519 @Test // DATAES-519
public void getOnNonExistingIndexShouldThrowException() { public void getOnNonExistingIndexShouldThrowException() {
client.get(new GetRequest(INDEX_I, TYPE_I, "nonono")) // client.get(new GetRequest(INDEX_I, "nonono")) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.expectError(ElasticsearchStatusException.class) // .expectError(ElasticsearchStatusException.class) //
.verify(); .verify();
@ -155,7 +152,7 @@ public class ReactiveElasticsearchClientTests {
String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
client.get(new GetRequest(INDEX_I, TYPE_I, id)) // client.get(new GetRequest(INDEX_I, id)) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.consumeNextWith(it -> { .consumeNextWith(it -> {
@ -171,17 +168,7 @@ public class ReactiveElasticsearchClientTests {
addSourceDocument().ofType(TYPE_I).to(INDEX_I); addSourceDocument().ofType(TYPE_I).to(INDEX_I);
String id = "this-one-does-not-exist"; String id = "this-one-does-not-exist";
client.get(new GetRequest(INDEX_I, TYPE_I, id)) // client.get(new GetRequest(INDEX_I, id)) //
.as(StepVerifier::create) //
.verifyComplete();
}
@Test // DATAES-488
public void getShouldCompleteForNonExistingType() {
String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
client.get(new GetRequest(INDEX_I, "fantasy-books", id)) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
} }
@ -193,17 +180,13 @@ public class ReactiveElasticsearchClientTests {
String id2 = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String id2 = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
MultiGetRequest request = new MultiGetRequest() // MultiGetRequest request = new MultiGetRequest() //
.add(INDEX_I, TYPE_I, id1) // .add(INDEX_I, id1) //
.add(INDEX_I, TYPE_I, id2); .add(INDEX_I, id2);
client.multiGet(request) // client.multiGet(request) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.consumeNextWith(it -> { .consumeNextWith(it -> assertThat(it.getId()).isEqualTo(id1)) //
assertThat(it.getId()).isEqualTo(id1); .consumeNextWith(it -> assertThat(it.getId()).isEqualTo(id2)) //
}) //
.consumeNextWith(it -> {
assertThat(it.getId()).isEqualTo(id2);
}) //
.verifyComplete(); .verifyComplete();
} }
@ -214,14 +197,12 @@ public class ReactiveElasticsearchClientTests {
addSourceDocument().ofType(TYPE_I).to(INDEX_I); addSourceDocument().ofType(TYPE_I).to(INDEX_I);
MultiGetRequest request = new MultiGetRequest() // MultiGetRequest request = new MultiGetRequest() //
.add(INDEX_I, TYPE_I, id1) // .add(INDEX_I, id1) //
.add(INDEX_I, TYPE_I, "this-one-does-not-exist"); .add(INDEX_I, "this-one-does-not-exist");
client.multiGet(request) // client.multiGet(request) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.consumeNextWith(it -> { .consumeNextWith(it -> assertThat(it.getId()).isEqualTo(id1)) //
assertThat(it.getId()).isEqualTo(id1);
}) //
.verifyComplete(); .verifyComplete();
} }
@ -232,9 +213,9 @@ public class ReactiveElasticsearchClientTests {
String id2 = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String id2 = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
MultiGetRequest request = new MultiGetRequest() // MultiGetRequest request = new MultiGetRequest() //
.add(INDEX_I, TYPE_I, id1) // .add(INDEX_I,id1) //
.add(INDEX_I, TYPE_I, "this-one-does-not-exist") // .add(INDEX_I,"this-one-does-not-exist") //
.add(INDEX_I, TYPE_I, id2); // .add(INDEX_I,id2); //
client.multiGet(request) // client.multiGet(request) //
.map(GetResult::getId) // .map(GetResult::getId) //
@ -249,7 +230,9 @@ public class ReactiveElasticsearchClientTests {
String id1 = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String id1 = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
String id2 = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String id2 = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
client.multiGet(new MultiGetRequest().add(INDEX_II, TYPE_I, id1).add(INDEX_II, TYPE_I, id2)) // client.multiGet(new MultiGetRequest() //
.add(INDEX_II, id1)
.add(INDEX_II, id2)) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
} }
@ -261,8 +244,8 @@ public class ReactiveElasticsearchClientTests {
String id2 = addSourceDocument().ofType(TYPE_II).to(INDEX_II); String id2 = addSourceDocument().ofType(TYPE_II).to(INDEX_II);
MultiGetRequest request = new MultiGetRequest() // MultiGetRequest request = new MultiGetRequest() //
.add(INDEX_I, TYPE_I, id1) // .add(INDEX_I, id1) //
.add(INDEX_II, TYPE_II, id2); .add(INDEX_II, id2);
client.multiGet(request) // client.multiGet(request) //
.map(GetResult::getId) // .map(GetResult::getId) //
@ -276,7 +259,7 @@ public class ReactiveElasticsearchClientTests {
String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
client.exists(new GetRequest(INDEX_I, TYPE_I, id)) // client.exists(new GetRequest(INDEX_I, id)) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.expectNext(true)// .expectNext(true)//
.verifyComplete(); .verifyComplete();
@ -287,7 +270,7 @@ public class ReactiveElasticsearchClientTests {
String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
client.exists(new GetRequest(INDEX_II, TYPE_I, id)) // client.exists(new GetRequest(INDEX_II, id)) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.expectNext(false)// .expectNext(false)//
.verifyComplete(); .verifyComplete();
@ -325,7 +308,7 @@ public class ReactiveElasticsearchClientTests {
public void updateShouldUpsertNonExistingDocumentWhenUsedWithUpsert() { public void updateShouldUpsertNonExistingDocumentWhenUsedWithUpsert() {
String id = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString();
UpdateRequest request = new UpdateRequest(INDEX_I, TYPE_I, id) // UpdateRequest request = new UpdateRequest(INDEX_I, id) //
.doc(DOC_SOURCE) // .doc(DOC_SOURCE) //
.docAsUpsert(true); .docAsUpsert(true);
@ -344,7 +327,7 @@ public class ReactiveElasticsearchClientTests {
String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
UpdateRequest request = new UpdateRequest(INDEX_I, TYPE_I, id) // UpdateRequest request = new UpdateRequest(INDEX_I, id) //
.doc(Collections.singletonMap("dutiful", "farseer")); .doc(Collections.singletonMap("dutiful", "farseer"));
client.update(request) // client.update(request) //
@ -362,7 +345,7 @@ public class ReactiveElasticsearchClientTests {
public void updateShouldErrorNonExistingDocumentWhenNotUpserted() { public void updateShouldErrorNonExistingDocumentWhenNotUpserted() {
String id = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString();
UpdateRequest request = new UpdateRequest(INDEX_I, TYPE_I, id) // UpdateRequest request = new UpdateRequest(INDEX_I, id) //
.doc(DOC_SOURCE); .doc(DOC_SOURCE);
client.update(request) // client.update(request) //
@ -375,13 +358,11 @@ public class ReactiveElasticsearchClientTests {
String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
DeleteRequest request = new DeleteRequest(INDEX_I, TYPE_I, id); DeleteRequest request = new DeleteRequest(INDEX_I, id);
client.delete(request) // client.delete(request) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.consumeNextWith(it -> { .consumeNextWith(it -> assertThat(it.status()).isEqualTo(RestStatus.OK)) //
assertThat(it.status()).isEqualTo(RestStatus.OK);
}) //
.verifyComplete(); .verifyComplete();
} }
@ -390,13 +371,11 @@ public class ReactiveElasticsearchClientTests {
addSourceDocument().ofType(TYPE_I).to(INDEX_I); addSourceDocument().ofType(TYPE_I).to(INDEX_I);
DeleteRequest request = new DeleteRequest(INDEX_I, TYPE_I, "this-one-does-not-exist"); DeleteRequest request = new DeleteRequest(INDEX_I, "this-one-does-not-exist");
client.delete(request) // client.delete(request) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.consumeNextWith(it -> { .consumeNextWith(it -> assertThat(it.status()).isEqualTo(RestStatus.NOT_FOUND)) //
assertThat(it.status()).isEqualTo(RestStatus.NOT_FOUND);
}) //
.verifyComplete(); .verifyComplete();
} }
@ -406,7 +385,7 @@ public class ReactiveElasticsearchClientTests {
addSourceDocument().ofType(TYPE_I).to(INDEX_I); addSourceDocument().ofType(TYPE_I).to(INDEX_I);
addSourceDocument().ofType(TYPE_I).to(INDEX_I); addSourceDocument().ofType(TYPE_I).to(INDEX_I);
SearchRequest request = new SearchRequest(INDEX_I).types(TYPE_I) // SearchRequest request = new SearchRequest(INDEX_I) //
.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery())); .source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
client.search(request) // client.search(request) //
@ -420,7 +399,7 @@ public class ReactiveElasticsearchClientTests {
syncClient.indices().create(new CreateIndexRequest(INDEX_I), RequestOptions.DEFAULT); syncClient.indices().create(new CreateIndexRequest(INDEX_I), RequestOptions.DEFAULT);
SearchRequest request = new SearchRequest(INDEX_I).types(TYPE_I) // SearchRequest request = new SearchRequest(INDEX_I) //
.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery())); .source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
client.search(request) // client.search(request) //
@ -435,7 +414,6 @@ public class ReactiveElasticsearchClientTests {
String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String id = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
DeleteByQueryRequest request = new DeleteByQueryRequest(INDEX_I) // DeleteByQueryRequest request = new DeleteByQueryRequest(INDEX_I) //
.setDocTypes(TYPE_I) //
.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("_id", id))); .setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("_id", id)));
client.deleteBy(request) // client.deleteBy(request) //
@ -452,7 +430,6 @@ public class ReactiveElasticsearchClientTests {
addSourceDocument().ofType(TYPE_I).to(INDEX_I); addSourceDocument().ofType(TYPE_I).to(INDEX_I);
DeleteByQueryRequest request = new DeleteByQueryRequest(INDEX_I) // DeleteByQueryRequest request = new DeleteByQueryRequest(INDEX_I) //
.setDocTypes(TYPE_I) //
.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("_id", "it-was-not-me"))); .setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("_id", "it-was-not-me")));
client.deleteBy(request) // client.deleteBy(request) //
@ -467,7 +444,7 @@ public class ReactiveElasticsearchClientTests {
IntStream.range(0, 100).forEach(it -> add(Collections.singletonMap(it + "-foo", "bar")).ofType(TYPE_I).to(INDEX_I)); IntStream.range(0, 100).forEach(it -> add(Collections.singletonMap(it + "-foo", "bar")).ofType(TYPE_I).to(INDEX_I));
SearchRequest request = new SearchRequest(INDEX_I).types(TYPE_I) // SearchRequest request = new SearchRequest(INDEX_I) //
.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery())); .source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
request = request.scroll(TimeValue.timeValueMinutes(1)); request = request.scroll(TimeValue.timeValueMinutes(1));
@ -483,7 +460,7 @@ public class ReactiveElasticsearchClientTests {
IntStream.range(0, 100).forEach(it -> add(Collections.singletonMap(it + "-foo", "bar")).ofType(TYPE_I).to(INDEX_I)); IntStream.range(0, 100).forEach(it -> add(Collections.singletonMap(it + "-foo", "bar")).ofType(TYPE_I).to(INDEX_I));
SearchRequest request = new SearchRequest(INDEX_I).types(TYPE_I) // SearchRequest request = new SearchRequest(INDEX_I) //
.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery())); .source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));
request = request.scroll(TimeValue.timeValueMinutes(1)); request = request.scroll(TimeValue.timeValueMinutes(1));
@ -524,7 +501,7 @@ public class ReactiveElasticsearchClientTests {
.as(StepVerifier::create) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
assertThat(syncClient.indices().exists(new GetIndexRequest().indices(INDEX_I), RequestOptions.DEFAULT)).isTrue(); assertThat(syncClient.indices().exists(new GetIndexRequest(INDEX_I), RequestOptions.DEFAULT)).isTrue();
} }
@Test // DATAES-569 @Test // DATAES-569
@ -546,7 +523,7 @@ public class ReactiveElasticsearchClientTests {
.as(StepVerifier::create) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
assertThat(syncClient.indices().exists(new GetIndexRequest().indices(INDEX_I), RequestOptions.DEFAULT)).isFalse(); assertThat(syncClient.indices().exists(new GetIndexRequest(INDEX_I), RequestOptions.DEFAULT)).isFalse();
} }
@Test // DATAES-569 @Test // DATAES-569
@ -658,9 +635,9 @@ public class ReactiveElasticsearchClientTests {
String idFirstDoc = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String idFirstDoc = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
String idSecondDoc = addSourceDocument().ofType(TYPE_I).to(INDEX_I); String idSecondDoc = addSourceDocument().ofType(TYPE_I).to(INDEX_I);
UpdateRequest requestFirstDoc = new UpdateRequest(INDEX_I, TYPE_I, idFirstDoc) // UpdateRequest requestFirstDoc = new UpdateRequest(INDEX_I, idFirstDoc) //
.doc(Collections.singletonMap("dutiful", "farseer")); .doc(Collections.singletonMap("dutiful", "farseer"));
UpdateRequest requestSecondDoc = new UpdateRequest(INDEX_I, TYPE_I, idSecondDoc) // UpdateRequest requestSecondDoc = new UpdateRequest(INDEX_I, idSecondDoc) //
.doc(Collections.singletonMap("secondDocUpdate", "secondDocUpdatePartTwo")); .doc(Collections.singletonMap("secondDocUpdate", "secondDocUpdatePartTwo"));
BulkRequest bulkRequest = new BulkRequest(); BulkRequest bulkRequest = new BulkRequest();
@ -683,13 +660,13 @@ public class ReactiveElasticsearchClientTests {
return add(DOC_SOURCE); return add(DOC_SOURCE);
} }
private AddToIndexOfType add(Map<String, ? extends Object> source) { private AddToIndexOfType add(Map<String, ?> source) {
return new AddDocument(source); return new AddDocument(source);
} }
private IndexRequest indexRequest(Map source, String index, String type) { private IndexRequest indexRequest(Map source, String index, String type) {
return new IndexRequest(index, type) // return new IndexRequest(index) //
.id(UUID.randomUUID().toString()) // .id(UUID.randomUUID().toString()) //
.source(source) // .source(source) //
.setRefreshPolicy(RefreshPolicy.IMMEDIATE) // .setRefreshPolicy(RefreshPolicy.IMMEDIATE) //
@ -711,10 +688,10 @@ public class ReactiveElasticsearchClientTests {
class AddDocument implements AddToIndexOfType { class AddDocument implements AddToIndexOfType {
Map<String, ? extends Object> source; Map<String, ?> source;
@Nullable String type; @Nullable String type;
AddDocument(Map<String, ? extends Object> source) { AddDocument(Map<String, ?> source) {
this.source = source; this.source = source;
} }

View File

@ -16,7 +16,6 @@
package org.springframework.data.elasticsearch.client.reactive; package org.springframework.data.elasticsearch.client.reactive;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
import static org.springframework.data.elasticsearch.client.reactive.ReactiveMockClientTestsUtils.MockWebClientProvider.Receive.*; import static org.springframework.data.elasticsearch.client.reactive.ReactiveMockClientTestsUtils.MockWebClientProvider.Receive.*;

View File

@ -129,10 +129,12 @@ public class ReactiveMockClientTestsUtils {
this.activeDefaultHost = activeDefaultHost; this.activeDefaultHost = activeDefaultHost;
} }
@Override
public Mono<InetSocketAddress> lookupActiveHost() { public Mono<InetSocketAddress> lookupActiveHost() {
return delegate.lookupActiveHost(); return delegate.lookupActiveHost();
} }
@Override
public Mono<InetSocketAddress> lookupActiveHost(Verification verification) { public Mono<InetSocketAddress> lookupActiveHost(Verification verification) {
if (StringUtils.hasText(activeDefaultHost)) { if (StringUtils.hasText(activeDefaultHost)) {
@ -142,14 +144,17 @@ public class ReactiveMockClientTestsUtils {
return delegate.lookupActiveHost(verification); return delegate.lookupActiveHost(verification);
} }
@Override
public Mono<WebClient> getActive() { public Mono<WebClient> getActive() {
return delegate.getActive(); return delegate.getActive();
} }
@Override
public Mono<WebClient> getActive(Verification verification) { public Mono<WebClient> getActive(Verification verification) {
return delegate.getActive(verification); return delegate.getActive(verification);
} }
@Override
public WebClient createWebClient(InetSocketAddress endpoint) { public WebClient createWebClient(InetSocketAddress endpoint) {
return delegate.createWebClient(endpoint); return delegate.createWebClient(endpoint);
} }
@ -210,6 +215,7 @@ public class ReactiveMockClientTestsUtils {
return get(getInetSocketAddress(host)); return get(getInetSocketAddress(host));
} }
@Override
public WebClient get(InetSocketAddress endpoint) { public WebClient get(InetSocketAddress endpoint) {
synchronized (lock) { synchronized (lock) {

View File

@ -65,7 +65,7 @@ public class ElasticsearchConfigurationTests {
assertThat(repository).isNotNull(); assertThat(repository).isNotNull();
} }
@Document(indexName = "test-index-config-abstractelasticsearchconfiguraiton", type = "test-type", createIndex = false) @Document(indexName = "test-index-config-abstractelasticsearchconfiguraiton", createIndex = false)
static class CreateIndexFalseEntity { static class CreateIndexFalseEntity {
@Id private String id; @Id private String id;

View File

@ -63,7 +63,7 @@ public class ElasticsearchNamespaceHandlerTests {
assertThat(context.getBean(RestClientFactoryBean.class)).isInstanceOf(RestClientFactoryBean.class); assertThat(context.getBean(RestClientFactoryBean.class)).isInstanceOf(RestClientFactoryBean.class);
} }
@Document(indexName = "test-index-config-namespace", type = "test-type", createIndex = false) @Document(indexName = "test-index-config-namespace", createIndex = false)
static class CreateIndexFalseEntity { static class CreateIndexFalseEntity {
@Id private String id; @Id private String id;

View File

@ -35,7 +35,7 @@ import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score; import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField; import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.repository.Repository; import org.springframework.data.repository.Repository;
@ -50,7 +50,7 @@ import org.springframework.test.context.ContextConfiguration;
public class EnableNestedElasticsearchRepositoriesTests { public class EnableNestedElasticsearchRepositoriesTests {
@Configuration @Configuration
@Import({ ElasticsearchTemplateConfiguration.class }) @Import({ ElasticsearchRestTemplateConfiguration.class })
@EnableElasticsearchRepositories(basePackages = { "org.springframework.data.elasticsearch.config.nested" }, @EnableElasticsearchRepositories(basePackages = { "org.springframework.data.elasticsearch.config.nested" },
considerNestedRepositories = true) considerNestedRepositories = true)
static class Config {} static class Config {}
@ -64,8 +64,7 @@ public class EnableNestedElasticsearchRepositoriesTests {
@Data @Data
@Builder @Builder
@Document(indexName = "test-index-sample-config-nested", type = "test-type", shards = 1, replicas = 0, @Document(indexName = "test-index-sample-config-nested", replicas = 0, refreshInterval = "-1")
refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {
@Id private String id; @Id private String id;

View File

@ -0,0 +1,33 @@
/*
* 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.config.nested;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.test.context.ContextConfiguration;
/**
* @author Peter-Josef Meisch
*/
@ContextConfiguration(classes = { EnableNestedElasticsearchRepositoriesTransportTests.Config.class })
public class EnableNestedElasticsearchRepositoriesTransportTests {
@Configuration
@Import({ ElasticsearchTemplateConfiguration.class })
@EnableElasticsearchRepositories(considerNestedRepositories = true)
static class Config {}
}

View File

@ -83,7 +83,7 @@ public class EnableElasticsearchRepositoriesTests implements ApplicationContextA
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(operations, SampleEntity.class); IndexInitializer.init(operations.getIndexOperations(), SampleEntity.class);
} }
@Test @Test
@ -112,8 +112,7 @@ public class EnableElasticsearchRepositoriesTests implements ApplicationContextA
} }
@Data @Data
@Document(indexName = "test-index-sample-config-not-nested", type = "test-type", shards = 1, replicas = 0, @Document(indexName = "test-index-sample-config-not-nested", replicas = 0, refreshInterval = "-1")
refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {
@Id private String id; @Id private String id;
@ -129,8 +128,7 @@ public class EnableElasticsearchRepositoriesTests implements ApplicationContextA
} }
@Data @Data
@Document(indexName = "test-index-uuid-keyed-config-not-nested", type = "test-type-uuid-keyed", shards = 1, @Document(indexName = "test-index-uuid-keyed-config-not-nested", replicas = 0, refreshInterval = "-1")
replicas = 0, refreshInterval = "-1")
static class SampleEntityUUIDKeyed { static class SampleEntityUUIDKeyed {
@Id private UUID id; @Id private UUID id;

View File

@ -45,7 +45,7 @@ public class DocumentAdaptersUnitTests {
public void shouldAdaptGetResponse() { public void shouldAdaptGetResponse() {
Map<String, DocumentField> fields = Collections.singletonMap("field", Map<String, DocumentField> fields = Collections.singletonMap("field",
new DocumentField("field", Arrays.asList("value"))); new DocumentField("field", Collections.singletonList("value")));
GetResult getResult = new GetResult("index", "type", "my-id", 1, 1, 42, true, null, fields, null); GetResult getResult = new GetResult("index", "type", "my-id", 1, 1, 42, true, null, fields, null);
GetResponse response = new GetResponse(getResult); GetResponse response = new GetResponse(getResult);
@ -80,7 +80,7 @@ public class DocumentAdaptersUnitTests {
public void shouldAdaptSearchResponse() { public void shouldAdaptSearchResponse() {
Map<String, DocumentField> fields = Collections.singletonMap("field", Map<String, DocumentField> fields = Collections.singletonMap("field",
new DocumentField("field", Arrays.asList("value"))); new DocumentField("field", Collections.singletonList("value")));
SearchHit searchHit = new SearchHit(123, "my-id", new Text("type"), fields); SearchHit searchHit = new SearchHit(123, "my-id", new Text("type"), fields);
searchHit.score(42); searchHit.score(42);
@ -99,7 +99,7 @@ public class DocumentAdaptersUnitTests {
Map<String, DocumentField> fields = new LinkedHashMap<>(); Map<String, DocumentField> fields = new LinkedHashMap<>();
fields.put("string", new DocumentField("string", Arrays.asList("value"))); fields.put("string", new DocumentField("string", Collections.singletonList("value")));
fields.put("bool", new DocumentField("bool", Arrays.asList(true, true, false))); fields.put("bool", new DocumentField("bool", Arrays.asList(true, true, false)));
SearchHit searchHit = new SearchHit(123, "my-id", new Text("type"), fields); SearchHit searchHit = new SearchHit(123, "my-id", new Text("type"), fields);
@ -115,7 +115,7 @@ public class DocumentAdaptersUnitTests {
Map<String, DocumentField> fields = new LinkedHashMap<>(); Map<String, DocumentField> fields = new LinkedHashMap<>();
fields.put("string", new DocumentField("string", Arrays.asList("value"))); fields.put("string", new DocumentField("string", Collections.singletonList("value")));
fields.put("bool", new DocumentField("bool", Arrays.asList(true, true, false))); fields.put("bool", new DocumentField("bool", Arrays.asList(true, true, false)));
fields.put("null", new DocumentField("null", Collections.emptyList())); fields.put("null", new DocumentField("null", Collections.emptyList()));
@ -133,7 +133,7 @@ public class DocumentAdaptersUnitTests {
Map<String, DocumentField> fields = new LinkedHashMap<>(); Map<String, DocumentField> fields = new LinkedHashMap<>();
fields.put("string", new DocumentField("string", Arrays.asList("value"))); fields.put("string", new DocumentField("string", Collections.singletonList("value")));
fields.put("bool", new DocumentField("bool", Arrays.asList(true, true, false))); fields.put("bool", new DocumentField("bool", Arrays.asList(true, true, false)));
SearchHit searchHit = new SearchHit(123, "my-id", new Text("type"), fields); SearchHit searchHit = new SearchHit(123, "my-id", new Text("type"), fields);

View File

@ -60,14 +60,12 @@ public class ElasticsearchRestTemplateTests extends ElasticsearchTemplateTests {
IndexRequest indexRequest = new IndexRequest(); IndexRequest indexRequest = new IndexRequest();
indexRequest.source("{}", XContentType.JSON); indexRequest.source("{}", XContentType.JSON);
UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)).withIndexRequest(indexRequest).build(); UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)).withIndexRequest(indexRequest).build();
assertThatThrownBy(() -> { assertThatThrownBy(() -> operations.update(updateQuery, index)).isInstanceOf(ElasticsearchStatusException.class);
operations.update(updateQuery, index);
}).isInstanceOf(ElasticsearchStatusException.class);
} }
@Data @Data
@Builder @Builder
@Document(indexName = "test-index-sample-core-rest-template", type = "test-type", shards = 1, replicas = 0, @Document(indexName = "test-index-sample-core-rest-template", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {

View File

@ -332,9 +332,7 @@ public abstract class ElasticsearchTemplateTests {
.withPreference("_only_nodes:oops").build(); .withPreference("_only_nodes:oops").build();
// when // when
assertThatThrownBy(() -> { assertThatThrownBy(() -> operations.search(searchQueryWithInvalidPreference, SampleEntity.class, index)).isInstanceOf(Exception.class);
operations.search(searchQueryWithInvalidPreference, SampleEntity.class, index);
}).isInstanceOf(Exception.class);
} }
@Test // DATAES-422 - Add support for IndicesOptions in search queries @Test // DATAES-422 - Add support for IndicesOptions in search queries
@ -515,7 +513,7 @@ public abstract class ElasticsearchTemplateTests {
// when // when
DeleteQuery deleteQuery = new DeleteQuery(); DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(typeQuery(TYPE_NAME)); deleteQuery.setQuery(termQuery("message", "foo"));
operations.delete(deleteQuery, IndexCoordinates.of("test-index-*").withTypes(TYPE_NAME)); operations.delete(deleteQuery, IndexCoordinates.of("test-index-*").withTypes(TYPE_NAME));
@ -1390,8 +1388,8 @@ public abstract class ElasticsearchTemplateTests {
indexOperations.createIndex(INDEX_1_NAME); indexOperations.createIndex(INDEX_1_NAME);
// when // when
indexOperations.putMapping(IndexCoordinates.of(INDEX_1_NAME).withTypes(TYPE_NAME), entity); indexOperations.putMapping(IndexCoordinates.of(INDEX_1_NAME).withTypes(TYPE_NAME), entity);
// then // then
Map<String, Object> mapping = indexOperations.getMapping(IndexCoordinates.of(INDEX_1_NAME).withTypes(TYPE_NAME)); Map<String, Object> mapping = indexOperations.getMapping(IndexCoordinates.of(INDEX_1_NAME).withTypes(TYPE_NAME));
assertThat(mapping.get("properties")).isNotNull(); assertThat(mapping.get("properties")).isNotNull();
@ -1441,7 +1439,7 @@ public abstract class ElasticsearchTemplateTests {
} }
@Test // DATAES-227 @Test // DATAES-227
public void shouldUseUpsertOnUpdate() throws IOException { public void shouldUseUpsertOnUpdate() {
// given // given
Map<String, Object> doc = new HashMap<>(); Map<String, Object> doc = new HashMap<>();
@ -1465,7 +1463,7 @@ public abstract class ElasticsearchTemplateTests {
} }
@Test // DATAES-693 @Test // DATAES-693
public void shouldReturnSourceWhenRequested() throws IOException { public void shouldReturnSourceWhenRequested() {
// given // given
Map<String, Object> doc = new HashMap<>(); Map<String, Object> doc = new HashMap<>();
doc.put("id", "1"); doc.put("id", "1");
@ -1525,12 +1523,10 @@ public abstract class ElasticsearchTemplateTests {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withIndicesOptions(IndicesOptions.lenientExpandOpen()).build(); .withIndicesOptions(IndicesOptions.lenientExpandOpen()).build();
List<SearchHit<SampleEntity>> entities = new ArrayList<>();
ScrolledPage<SearchHit<SampleEntity>> scroll = operations.searchScrollStart(scrollTimeInMillis, searchQuery, ScrolledPage<SearchHit<SampleEntity>> scroll = operations.searchScrollStart(scrollTimeInMillis, searchQuery,
SampleEntity.class, index); SampleEntity.class, index);
entities.addAll(scroll.getContent()); List<SearchHit<SampleEntity>> entities = new ArrayList<>(scroll.getContent());
while (scroll.hasContent()) { while (scroll.hasContent()) {
scroll = operations.searchScrollContinue(scroll.getScrollId(), scrollTimeInMillis, SampleEntity.class); scroll = operations.searchScrollContinue(scroll.getScrollId(), scrollTimeInMillis, SampleEntity.class);
@ -1858,9 +1854,7 @@ public abstract class ElasticsearchTemplateTests {
indexOperations.refresh(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)); indexOperations.refresh(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY));
// reindex with version one below // reindex with version one below
assertThatThrownBy(() -> { assertThatThrownBy(() -> operations.index(indexQueryBuilder.withVersion(entity.getVersion() - 1).build(), index)).hasMessageContaining("version").hasMessageContaining("conflict");
operations.index(indexQueryBuilder.withVersion(entity.getVersion() - 1).build(), index);
}).hasMessageContaining("version").hasMessageContaining("conflict");
} }
@Test @Test
@ -2140,9 +2134,7 @@ public abstract class ElasticsearchTemplateTests {
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria());
// when // when
assertThatThrownBy(() -> { assertThatThrownBy(() -> operations.count(criteriaQuery, (IndexCoordinates) null)).isInstanceOf(IllegalArgumentException.class);
operations.count(criteriaQuery, (IndexCoordinates) null);
}).isInstanceOf(IllegalArgumentException.class);
} }
@Test // DATAES-67 @Test // DATAES-67
@ -2159,9 +2151,7 @@ public abstract class ElasticsearchTemplateTests {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
// when // when
assertThatThrownBy(() -> { assertThatThrownBy(() -> operations.count(searchQuery, (IndexCoordinates) null)).isInstanceOf(IllegalArgumentException.class);
operations.count(searchQuery, (IndexCoordinates) null);
}).isInstanceOf(IllegalArgumentException.class);
} }
@Test // DATAES-71 @Test // DATAES-71
@ -2173,7 +2163,7 @@ public abstract class ElasticsearchTemplateTests {
+ " \"analyzer\": {\n" + " \"emailAnalyzer\": {\n" + " \"analyzer\": {\n" + " \"emailAnalyzer\": {\n"
+ " \"type\": \"custom\",\n" + " \"type\": \"custom\",\n"
+ " \"tokenizer\": \"uax_url_email\"\n" + " }\n" + " \"tokenizer\": \"uax_url_email\"\n" + " }\n"
+ " }\n" + " }\n" + " }\n" + "}"; + " }\n" + " }\n" + " }\n" + '}';
indexOperations.deleteIndex(INDEX_3_NAME); indexOperations.deleteIndex(INDEX_3_NAME);
@ -2215,7 +2205,7 @@ public abstract class ElasticsearchTemplateTests {
+ " \"analyzer\": {\n" + " \"emailAnalyzer\": {\n" + " \"analyzer\": {\n" + " \"emailAnalyzer\": {\n"
+ " \"type\": \"custom\",\n" + " \"type\": \"custom\",\n"
+ " \"tokenizer\": \"uax_url_email\"\n" + " }\n" + " \"tokenizer\": \"uax_url_email\"\n" + " }\n"
+ " }\n" + " }\n" + " }\n" + "}"; + " }\n" + " }\n" + " }\n" + '}';
// when // when
indexOperations.deleteIndex(SampleEntity.class); indexOperations.deleteIndex(SampleEntity.class);
@ -2798,7 +2788,7 @@ public abstract class ElasticsearchTemplateTests {
assertThat(aliases).isEmpty(); assertThat(aliases).isEmpty();
} }
@Document(indexName = INDEX_2_NAME, replicas = 0, shards = 1) @Document(indexName = INDEX_2_NAME, replicas = 0)
class ResultAggregator { class ResultAggregator {
private String id; private String id;
@ -2900,7 +2890,7 @@ public abstract class ElasticsearchTemplateTests {
@AllArgsConstructor @AllArgsConstructor
@EqualsAndHashCode(exclude = "score") @EqualsAndHashCode(exclude = "score")
@Builder @Builder
@Document(indexName = INDEX_NAME_SAMPLE_ENTITY, type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = INDEX_NAME_SAMPLE_ENTITY, replicas = 0, refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {
@Id private String id; @Id private String id;
@ -2923,7 +2913,7 @@ public abstract class ElasticsearchTemplateTests {
@Data @Data
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-uuid-keyed-core-template", type = "test-type-uuid-keyed", shards = 1, replicas = 0, @Document(indexName = "test-index-uuid-keyed-core-template", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
private static class SampleEntityUUIDKeyed { private static class SampleEntityUUIDKeyed {
@ -2945,7 +2935,7 @@ public abstract class ElasticsearchTemplateTests {
@Builder @Builder
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
@Document(indexName = "test-index-book-core-template", type = "book", shards = 1, replicas = 0, @Document(indexName = "test-index-book-core-template", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class Book { static class Book {
@ -2969,7 +2959,7 @@ public abstract class ElasticsearchTemplateTests {
@Builder @Builder
@AllArgsConstructor @AllArgsConstructor
@NoArgsConstructor @NoArgsConstructor
@Document(indexName = "test-index-version-core-template", type = "test-type", shards = 1, replicas = 0, @Document(indexName = "test-index-version-core-template", replicas = 0,
refreshInterval = "-1", versionType = VersionType.EXTERNAL_GTE) refreshInterval = "-1", versionType = VersionType.EXTERNAL_GTE)
private static class GTEVersionEntity { private static class GTEVersionEntity {
@ -2981,7 +2971,7 @@ public abstract class ElasticsearchTemplateTests {
} }
@Data @Data
@Document(indexName = "test-index-hetro1-core-template", type = "hetro", replicas = 0, shards = 1) @Document(indexName = "test-index-hetro1-core-template", replicas = 0)
static class HetroEntity1 { static class HetroEntity1 {
@Id private String id; @Id private String id;
@ -2996,7 +2986,7 @@ public abstract class ElasticsearchTemplateTests {
} }
@Data @Data
@Document(indexName = "test-index-hetro2-core-template", type = "hetro", replicas = 0, shards = 1) @Document(indexName = "test-index-hetro2-core-template", replicas = 0)
static class HetroEntity2 { static class HetroEntity2 {
@Id private String id; @Id private String id;
@ -3011,7 +3001,7 @@ public abstract class ElasticsearchTemplateTests {
} }
@Data @Data
@Document(indexName = "test-index-server-configuration", type = "test-type", useServerConfiguration = true, @Document(indexName = "test-index-server-configuration", useServerConfiguration = true,
shards = 10, replicas = 10, refreshInterval = "-1") shards = 10, replicas = 10, refreshInterval = "-1")
private static class UseServerConfigurationEntity { private static class UseServerConfigurationEntity {
@ -3021,7 +3011,7 @@ public abstract class ElasticsearchTemplateTests {
} }
@Data @Data
@Document(indexName = "test-index-sample-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-index-sample-mapping", replicas = 0, refreshInterval = "-1")
static class SampleMappingEntity { static class SampleMappingEntity {
@Id private String id; @Id private String id;

View File

@ -59,11 +59,10 @@ public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTe
IndexRequest indexRequest = new IndexRequest(); IndexRequest indexRequest = new IndexRequest();
indexRequest.source("{}", XContentType.JSON); indexRequest.source("{}", XContentType.JSON);
UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)).withIndexRequest(indexRequest).build(); UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)).withIndexRequest(indexRequest).build();
assertThatThrownBy(() -> { assertThatThrownBy(() -> operations.update(updateQuery, index)).isInstanceOf(DocumentMissingException.class);
operations.update(updateQuery, index);
}).isInstanceOf(DocumentMissingException.class);
} }
@Override
@Test // DATAES-187 @Test // DATAES-187
public void shouldUsePageableOffsetToSetFromInSearchRequest() { public void shouldUsePageableOffsetToSetFromInSearchRequest() {
@ -88,7 +87,7 @@ public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTe
} }
@Data @Data
@Document(indexName = "test-index-sample-core-transport-template", type = "test-type", shards = 1, replicas = 0, @Document(indexName = "test-index-sample-core-transport-template", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {

View File

@ -27,23 +27,17 @@ class IndexCoordinatesTest {
@Test @Test
void cannotBeInitializedWithNullIndexName() { void cannotBeInitializedWithNullIndexName() {
assertThatThrownBy(() -> { assertThatThrownBy(() -> IndexCoordinates.of(null)).isInstanceOf(IllegalArgumentException.class);
IndexCoordinates.of(null);
}).isInstanceOf(IllegalArgumentException.class);
} }
@Test @Test
void cannotBeInitializedWithNullIndexNames() { void cannotBeInitializedWithNullIndexNames() {
assertThatThrownBy(() -> { assertThatThrownBy(() -> IndexCoordinates.of((String[]) null)).isInstanceOf(IllegalArgumentException.class);
IndexCoordinates.of((String[]) null);
}).isInstanceOf(IllegalArgumentException.class);
} }
@Test @Test
void cannotBeInitializedWithEmptyIndexNames() { void cannotBeInitializedWithEmptyIndexNames() {
assertThatThrownBy(() -> { assertThatThrownBy(() -> IndexCoordinates.of(new String[] {})).isInstanceOf(IllegalArgumentException.class);
IndexCoordinates.of(new String[] {});
}).isInstanceOf(IllegalArgumentException.class);
} }
@Test @Test

View File

@ -27,6 +27,7 @@ import java.util.Arrays;
import java.util.Date; import java.util.Date;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -61,11 +62,12 @@ public class LogEntityTests {
private final IndexCoordinates index = IndexCoordinates.of("test-index-log-core").withTypes("test-log-type"); private final IndexCoordinates index = IndexCoordinates.of("test-index-log-core").withTypes("test-log-type");
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() throws ParseException { public void before() throws ParseException {
indexOperations = operations.getIndexOperations();
IndexInitializer.init(operations, LogEntity.class); IndexInitializer.init(indexOperations, LogEntity.class);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
IndexQuery indexQuery1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse("2013-10-18 18:01")) IndexQuery indexQuery1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse("2013-10-18 18:01"))
@ -81,7 +83,12 @@ public class LogEntityTests {
.code(2).ip("10.10.10.4").buildIndex(); .code(2).ip("10.10.10.4").buildIndex();
operations.bulkIndex(Arrays.asList(indexQuery1, indexQuery2, indexQuery3, indexQuery4), index); operations.bulkIndex(Arrays.asList(indexQuery1, indexQuery2, indexQuery3, indexQuery4), index);
operations.refresh(LogEntity.class); indexOperations.refresh(LogEntity.class);
}
@AfterEach
void after() {
indexOperations.deleteIndex(LogEntity.class);
} }
@Test // DATAES-66 @Test // DATAES-66
@ -122,7 +129,7 @@ public class LogEntityTests {
* Simple type to test facets * Simple type to test facets
*/ */
@Data @Data
@Document(indexName = "test-index-log-core", type = "test-log-type", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-index-log-core", replicas = 0, refreshInterval = "-1")
static class LogEntity { static class LogEntity {
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

View File

@ -24,6 +24,7 @@ import lombok.Builder;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor; import lombok.NoArgsConstructor;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import reactor.test.StepVerifier; import reactor.test.StepVerifier;
@ -99,7 +100,7 @@ public class ReactiveElasticsearchTemplateTests {
} }
@AfterEach @AfterEach
public void tearDown() { public void after() {
deleteIndices(); deleteIndices();
} }
@ -110,7 +111,7 @@ public class ReactiveElasticsearchTemplateTests {
@Test // DATAES-504 @Test // DATAES-504
public void executeShouldProvideResource() { public void executeShouldProvideResource() {
Mono.from(template.execute(client -> client.ping())) // Mono.from(template.execute(ReactiveElasticsearchClient::ping)) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.expectNext(true) // .expectNext(true) //
.verifyComplete(); .verifyComplete();
@ -456,10 +457,7 @@ public class ReactiveElasticsearchTemplateTests {
@Test // DATAES-518 @Test // DATAES-518
public void searchShouldApplyPagingCorrectly() { public void searchShouldApplyPagingCorrectly() {
List<SampleEntity> source = IntStream.range(0, 100).mapToObj(it -> randomEntity("entity - " + it)) index(IntStream.range(0, 100).mapToObj(it -> randomEntity("entity - " + it)).toArray(SampleEntity[]::new));
.collect(Collectors.toList());
index(source.toArray(new SampleEntity[0]));
CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("entity")) // CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("entity")) //
.addSort(Sort.by("message"))// .addSort(Sort.by("message"))//
@ -473,10 +471,7 @@ public class ReactiveElasticsearchTemplateTests {
@Test // DATAES-518 @Test // DATAES-518
public void findWithoutPagingShouldReadAll() { public void findWithoutPagingShouldReadAll() {
List<SampleEntity> source = IntStream.range(0, 100).mapToObj(it -> randomEntity("entity - " + it)) index(IntStream.range(0, 100).mapToObj(it -> randomEntity("entity - " + it)).toArray(SampleEntity[]::new));
.collect(Collectors.toList());
index(source.toArray(new SampleEntity[0]));
CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("entity")) // CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("entity")) //
.addSort(Sort.by("message"))// .addSort(Sort.by("message"))//
@ -717,7 +712,7 @@ public class ReactiveElasticsearchTemplateTests {
} }
@Data @Data
@Document(indexName = "marvel", type = "characters") @Document(indexName = "marvel")
static class Person { static class Person {
private @Id String id; private @Id String id;
@ -780,7 +775,7 @@ public class ReactiveElasticsearchTemplateTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@EqualsAndHashCode(exclude = "score") @EqualsAndHashCode(exclude = "score")
@Document(indexName = DEFAULT_INDEX, type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = DEFAULT_INDEX, replicas = 0, refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {
@Id private String id; @Id private String id;

View File

@ -258,7 +258,7 @@ public class ReactiveElasticsearchTemplateUnitTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-sample-core-reactive-template-Unit", type = "test-type", shards = 1, replicas = 0, @Document(indexName = "test-index-sample-core-reactive-template-Unit", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {

View File

@ -27,7 +27,6 @@ import java.lang.Integer;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType; import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.Aggregations;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
@ -42,9 +41,9 @@ import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.InnerField; import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.ResultsExtractor;
import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
@ -78,11 +77,12 @@ public class ElasticsearchTemplateAggregationTests {
static final String INDEX_NAME = "test-index-articles-core-aggregation"; static final String INDEX_NAME = "test-index-articles-core-aggregation";
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
indexOperations = operations.getIndexOperations();
IndexInitializer.init(operations, ArticleEntity.class); IndexInitializer.init(indexOperations, ArticleEntity.class);
IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").subject("computing") IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").subject("computing")
.addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10) .addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10)
@ -107,8 +107,7 @@ public class ElasticsearchTemplateAggregationTests {
@AfterEach @AfterEach
public void after() { public void after() {
indexOperations.deleteIndex(ArticleEntity.class);
operations.deleteIndex(ArticleEntity.class);
} }
@Test @Test
@ -136,7 +135,7 @@ public class ElasticsearchTemplateAggregationTests {
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Data @Data
@Document(indexName = "test-index-articles-core-aggregation", type = "article", shards = 1, replicas = 0, @Document(indexName = "test-index-articles-core-aggregation", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class ArticleEntity { static class ArticleEntity {
@ -154,10 +153,6 @@ public class ElasticsearchTemplateAggregationTests {
private int score; private int score;
private ArticleEntity() {
}
public ArticleEntity(String id) { public ArticleEntity(String id) {
this.id = id; this.id = id;
} }

View File

@ -26,6 +26,7 @@ import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders; import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.SuggestionBuilder; import org.elasticsearch.search.suggest.SuggestionBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion; import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -72,6 +73,12 @@ public class ElasticsearchTemplateCompletionTests {
IndexInitializer.init(indexOperations, AnnotatedCompletionEntity.class); IndexInitializer.init(indexOperations, AnnotatedCompletionEntity.class);
} }
@AfterEach
void after() {
indexOperations.deleteIndex("test-index-annotated-completion");
indexOperations.deleteIndex("test-index-core-completion");
}
private void loadCompletionObjectEntities() { private void loadCompletionObjectEntities() {
List<IndexQuery> indexQueries = new ArrayList<>(); List<IndexQuery> indexQueries = new ArrayList<>();
@ -237,7 +244,7 @@ public class ElasticsearchTemplateCompletionTests {
/** /**
* @author Mewes Kochheim * @author Mewes Kochheim
*/ */
@Document(indexName = "test-index-core-completion", type = "completion-type", shards = 1, replicas = 0, @Document(indexName = "test-index-core-completion", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class CompletionEntity { static class CompletionEntity {
@ -321,7 +328,7 @@ public class ElasticsearchTemplateCompletionTests {
/** /**
* @author Mewes Kochheim * @author Mewes Kochheim
*/ */
@Document(indexName = "test-index-annotated-completion", type = "annotated-completion-type", shards = 1, replicas = 0, @Document(indexName = "test-index-annotated-completion", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class AnnotatedCompletionEntity { static class AnnotatedCompletionEntity {

View File

@ -33,6 +33,7 @@ import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder; import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.elasticsearch.search.suggest.completion.context.CategoryQueryContext; import org.elasticsearch.search.suggest.completion.context.CategoryQueryContext;
import org.elasticsearch.search.suggest.completion.context.ContextMapping; import org.elasticsearch.search.suggest.completion.context.ContextMapping;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -71,7 +72,11 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
@BeforeEach @BeforeEach
void setup() { void setup() {
indexOperations = operations.getIndexOperations(); indexOperations = operations.getIndexOperations();
indexOperations.deleteIndex(ContextCompletionEntity.class);
}
@AfterEach
void after() {
indexOperations.deleteIndex(ContextCompletionEntity.class); indexOperations.deleteIndex(ContextCompletionEntity.class);
} }
@ -238,7 +243,7 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
* @author Mewes Kochheim * @author Mewes Kochheim
* @author Robert Gruendler * @author Robert Gruendler
*/ */
@Document(indexName = "test-index-context-completion", type = "context-completion-type", shards = 1, replicas = 0, @Document(indexName = "test-index-context-completion", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class ContextCompletionEntity { static class ContextCompletionEntity {

View File

@ -56,8 +56,6 @@ import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.document.Document; import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.geo.Box; import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle; import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Point; import org.springframework.data.geo.Point;
@ -201,9 +199,7 @@ public class MappingElasticsearchConverterUnitTests {
public void shouldFailToInitializeGivenMappingContextIsNull() { public void shouldFailToInitializeGivenMappingContextIsNull() {
// given // given
assertThatThrownBy(() -> { assertThatThrownBy(() -> new MappingElasticsearchConverter(null)).isInstanceOf(IllegalArgumentException.class);
new MappingElasticsearchConverter(null);
}).isInstanceOf(IllegalArgumentException.class);
} }
@Test @Test
@ -233,7 +229,7 @@ public class MappingElasticsearchConverterUnitTests {
} }
@Test // DATAES-530 @Test // DATAES-530
public void shouldMapObjectToJsonString() throws IOException { public void shouldMapObjectToJsonString() {
// Given // Given
// When // When
@ -245,7 +241,7 @@ public class MappingElasticsearchConverterUnitTests {
} }
@Test // DATAES-530 @Test // DATAES-530
public void shouldMapJsonStringToObject() throws IOException { public void shouldMapJsonStringToObject() {
// Given // Given
// When // When
@ -258,7 +254,7 @@ public class MappingElasticsearchConverterUnitTests {
} }
@Test // DATAES-530 @Test // DATAES-530
public void shouldMapGeoPointElasticsearchNames() throws IOException { public void shouldMapGeoPointElasticsearchNames() {
// given // given
Point point = new Point(10, 20); Point point = new Point(10, 20);
String pointAsString = point.getX() + "," + point.getY(); String pointAsString = point.getX() + "," + point.getY();
@ -277,7 +273,7 @@ public class MappingElasticsearchConverterUnitTests {
} }
@Test // DATAES-530 @Test // DATAES-530
public void ignoresReadOnlyProperties() throws IOException { public void ignoresReadOnlyProperties() {
// given // given
Sample sample = new Sample(); Sample sample = new Sample();
@ -311,7 +307,7 @@ public class MappingElasticsearchConverterUnitTests {
} }
@Test // DATAES-530 @Test // DATAES-530
public void writesConcreteList() throws IOException { public void writesConcreteList() {
Person ginger = new Person(); Person ginger = new Person();
ginger.id = "ginger"; ginger.id = "ginger";
@ -324,7 +320,7 @@ public class MappingElasticsearchConverterUnitTests {
} }
@Test // DATAES-530 @Test // DATAES-530
public void writesInterfaceList() throws IOException { public void writesInterfaceList() {
Inventory gun = new Gun("Glock 19", 33); Inventory gun = new Gun("Glock 19", 33);
Inventory grenade = new Grenade("40 mm"); Inventory grenade = new Grenade("40 mm");
@ -346,7 +342,7 @@ public class MappingElasticsearchConverterUnitTests {
@Test // DATAES-530 @Test // DATAES-530
public void readListOfConcreteTypesCorrectly() { public void readListOfConcreteTypesCorrectly() {
sarahAsMap.put("coWorkers", Arrays.asList(kyleAsMap)); sarahAsMap.put("coWorkers", Collections.singletonList(kyleAsMap));
Person target = mappingElasticsearchConverter.read(Person.class, sarahAsMap); Person target = mappingElasticsearchConverter.read(Person.class, sarahAsMap);
@ -447,7 +443,7 @@ public class MappingElasticsearchConverterUnitTests {
public void readGenericListList() { public void readGenericListList() {
Document source = Document.create(); Document source = Document.create();
source.put("objectList", Arrays.asList(Arrays.asList(t800AsMap, gunAsMap))); source.put("objectList", Collections.singletonList(Arrays.asList(t800AsMap, gunAsMap)));
Skynet target = mappingElasticsearchConverter.read(Skynet.class, source); Skynet target = mappingElasticsearchConverter.read(Skynet.class, source);
@ -738,6 +734,7 @@ public class MappingElasticsearchConverterUnitTests {
String city; String city;
} }
@EqualsAndHashCode(callSuper = true)
@Data @Data
static class Place extends Address { static class Place extends Address {
@ -789,7 +786,7 @@ public class MappingElasticsearchConverterUnitTests {
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@org.springframework.data.elasticsearch.annotations.Document(indexName = "test-index-geo-core-entity-mapper", @org.springframework.data.elasticsearch.annotations.Document(indexName = "test-index-geo-core-entity-mapper",
type = "geo-test-index", shards = 1, replicas = 0, refreshInterval = "-1") type = "geo-test-index", replicas = 0, refreshInterval = "-1")
static class GeoEntity { static class GeoEntity {
@Id private String id; @Id private String id;

View File

@ -29,6 +29,7 @@ import java.util.List;
import org.elasticsearch.geometry.utils.Geohash; import org.elasticsearch.geometry.utils.Geohash;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -89,6 +90,12 @@ public class ElasticsearchTemplateGeoTests {
IndexInitializer.init(indexOperations, LocationMarkerEntity.class); IndexInitializer.init(indexOperations, LocationMarkerEntity.class);
} }
@AfterEach
void after() {
indexOperations.deleteIndex(AuthorMarkerEntity.class);
indexOperations.deleteIndex(LocationMarkerEntity.class);
}
private void loadClassBaseEntities() { private void loadClassBaseEntities() {
List<IndexQuery> indexQueries = new ArrayList<>(); List<IndexQuery> indexQueries = new ArrayList<>();
@ -368,7 +375,7 @@ public class ElasticsearchTemplateGeoTests {
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Data @Data
@Document(indexName = "test-index-author-marker-core-geo", type = "geo-class-point-type", shards = 1, replicas = 0, @Document(indexName = "test-index-author-marker-core-geo", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class AuthorMarkerEntity { static class AuthorMarkerEntity {
@ -427,7 +434,7 @@ public class ElasticsearchTemplateGeoTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-location-marker-core-geo", type = "geo-annotation-point-type", shards = 1, @Document(indexName = "test-index-location-marker-core-geo",
replicas = 0, refreshInterval = "-1") replicas = 0, refreshInterval = "-1")
static class LocationMarkerEntity { static class LocationMarkerEntity {

View File

@ -111,10 +111,10 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void testInfiniteLoopAvoidance() throws IOException, JSONException { public void testInfiniteLoopAvoidance() throws JSONException {
String expected = "{\"mapping\":{\"properties\":{\"message\":{\"store\":true,\"" String expected = "{\"properties\":{\"message\":{\"store\":true,\""
+ "type\":\"text\",\"index\":false," + "\"analyzer\":\"standard\"}}}}"; + "type\":\"text\",\"index\":false," + "\"analyzer\":\"standard\"}}}";
String mapping = getMappingBuilder().buildPropertyMapping(SampleTransientEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(SampleTransientEntity.class);
@ -122,10 +122,10 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void shouldUseValueFromAnnotationType() throws IOException, JSONException { public void shouldUseValueFromAnnotationType() throws JSONException {
// Given // Given
String expected = "{\"price\":{\"properties\":{\"price\":{\"type\":\"double\"}}}}"; String expected = "{\"properties\":{\"price\":{\"type\":\"double\"}}}";
// When // When
String mapping = getMappingBuilder().buildPropertyMapping(StockPrice.class); String mapping = getMappingBuilder().buildPropertyMapping(StockPrice.class);
@ -165,9 +165,9 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void shouldCreateMappingForSpecifiedParentType() throws IOException, JSONException { public void shouldCreateMappingForSpecifiedParentType() throws JSONException {
String expected = "{\"mapping\":{\"_parent\":{\"type\":\"parentType\"},\"properties\":{}}}"; String expected = "{\"_parent\":{\"type\":\"parentType\"},\"properties\":{}}";
String mapping = getMappingBuilder().buildPropertyMapping(MinimalChildEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(MinimalChildEntity.class);
@ -175,11 +175,11 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-76 @Test // DATAES-76
public void shouldBuildMappingWithSuperclass() throws IOException, JSONException { public void shouldBuildMappingWithSuperclass() throws JSONException {
String expected = "{\"mapping\":{\"properties\":{\"message\":{\"store\":true,\"" String expected = "{\"properties\":{\"message\":{\"store\":true,\""
+ "type\":\"text\",\"index\":false,\"analyzer\":\"standard\"}" + ",\"createdDate\":{" + "type\":\"text\",\"index\":false,\"analyzer\":\"standard\"}" + ",\"createdDate\":{"
+ "\"type\":\"date\",\"index\":false}}}}"; + "\"type\":\"date\",\"index\":false}}}";
String mapping = getMappingBuilder().buildPropertyMapping(SampleInheritedEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(SampleInheritedEntity.class);
@ -214,12 +214,12 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void shouldBuildMappingsForGeoPoint() throws IOException, JSONException { public void shouldBuildMappingsForGeoPoint() throws JSONException {
// given // given
String expected = "{\"geo-test-index\": {\"properties\": {" + "\"pointA\":{\"type\":\"geo_point\"}," String expected = "{\"properties\": {" + "\"pointA\":{\"type\":\"geo_point\"},"
+ "\"pointB\":{\"type\":\"geo_point\"}," + "\"pointC\":{\"type\":\"geo_point\"}," + "\"pointB\":{\"type\":\"geo_point\"}," + "\"pointC\":{\"type\":\"geo_point\"},"
+ "\"pointD\":{\"type\":\"geo_point\"}" + "}}}"; + "\"pointD\":{\"type\":\"geo_point\"}" + "}}";
// when // when
String mapping; String mapping;
@ -300,8 +300,8 @@ public class MappingBuilderTests extends MappingContextBaseTests {
public void shouldUseCopyTo() { public void shouldUseCopyTo() {
// given // given
operations.createIndex(CopyToEntity.class); indexOperations.createIndex(CopyToEntity.class);
operations.putMapping(CopyToEntity.class); indexOperations.putMapping(CopyToEntity.class);
// when // when
Map mapping = operations.getMapping(CopyToEntity.class); Map mapping = operations.getMapping(CopyToEntity.class);
@ -316,11 +316,11 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void shouldUseFieldNameOnId() throws IOException, JSONException { public void shouldUseFieldNameOnId() throws JSONException {
// given // given
String expected = "{\"fieldname-type\":{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true}" String expected = "{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true}"
+ "}}}"; + "}}";
// when // when
String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.IdEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.IdEntity.class);
@ -330,11 +330,11 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void shouldUseFieldNameOnText() throws IOException, JSONException { public void shouldUseFieldNameOnText() throws JSONException {
// given // given
String expected = "{\"fieldname-type\":{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true}," String expected = "{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true},"
+ "\"text-property\":{\"type\":\"text\"}" + "}}}"; + "\"text-property\":{\"type\":\"text\"}" + "}}";
// when // when
String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.TextEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.TextEntity.class);
@ -344,11 +344,11 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void shouldUseFieldNameOnMapping() throws IOException, JSONException { public void shouldUseFieldNameOnMapping() throws JSONException {
// given // given
String expected = "{\"fieldname-type\":{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true}," String expected = "{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true},"
+ "\"mapping-property\":{\"type\":\"string\",\"analyzer\":\"standard_lowercase_asciifolding\"}" + "}}}"; + "\"mapping-property\":{\"type\":\"string\",\"analyzer\":\"standard_lowercase_asciifolding\"}" + "}}";
// when // when
String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.MappingEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.MappingEntity.class);
@ -358,11 +358,11 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void shouldUseFieldNameOnGeoPoint() throws IOException, JSONException { public void shouldUseFieldNameOnGeoPoint() throws JSONException {
// given // given
String expected = "{\"fieldname-type\":{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true}," String expected = "{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true},"
+ "\"geopoint-property\":{\"type\":\"geo_point\"}" + "}}}"; + "\"geopoint-property\":{\"type\":\"geo_point\"}" + "}}";
// when // when
String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.GeoPointEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.GeoPointEntity.class);
@ -372,11 +372,11 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void shouldUseFieldNameOnCircularEntity() throws IOException, JSONException { public void shouldUseFieldNameOnCircularEntity() throws JSONException {
// given // given
String expected = "{\"fieldname-type\":{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true}," String expected = "{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true},"
+ "\"circular-property\":{\"type\":\"object\",\"properties\":{\"id-property\":{}}}" + "}}}"; + "\"circular-property\":{\"type\":\"object\",\"properties\":{\"id-property\":{}}}" + "}}";
// when // when
String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.CircularEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.CircularEntity.class);
@ -386,12 +386,12 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void shouldUseFieldNameOnCompletion() throws IOException, JSONException { public void shouldUseFieldNameOnCompletion() throws JSONException {
// given // given
String expected = "{\"fieldname-type\":{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true}," String expected = "{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true},"
+ "\"completion-property\":{\"type\":\"completion\",\"max_input_length\":100,\"preserve_position_increments\":true,\"preserve_separators\":true,\"search_analyzer\":\"simple\",\"analyzer\":\"simple\"},\"completion-property\":{}" + "\"completion-property\":{\"type\":\"completion\",\"max_input_length\":100,\"preserve_position_increments\":true,\"preserve_separators\":true,\"search_analyzer\":\"simple\",\"analyzer\":\"simple\"},\"completion-property\":{}"
+ "}}}"; + "}}";
// when // when
String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.CompletionEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.CompletionEntity.class);
@ -401,12 +401,11 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-568 @Test // DATAES-568
public void shouldUseFieldNameOnMultiField() throws IOException, JSONException { public void shouldUseFieldNameOnMultiField() throws JSONException {
// given // given
String expected = "{\"fieldname-type\":{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true}," String expected = "{\"properties\":{" + "\"id-property\":{\"type\":\"keyword\",\"index\":true},"
+ "\"multifield-property\":{\"type\":\"text\",\"analyzer\":\"whitespace\",\"fields\":{\"prefix\":{\"type\":\"text\",\"analyzer\":\"stop\",\"search_analyzer\":\"standard\"}}}" + "\"multifield-property\":{\"type\":\"text\",\"analyzer\":\"whitespace\",\"fields\":{\"prefix\":{\"type\":\"text\",\"analyzer\":\"stop\",\"search_analyzer\":\"standard\"}}}}}";
+ "}}}";
// when // when
String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.MultiFieldEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(FieldNameEntity.MultiFieldEntity.class);
@ -416,10 +415,10 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test // DATAES-639 @Test // DATAES-639
public void shouldUseIgnoreAbove() throws IOException, JSONException { public void shouldUseIgnoreAbove() throws JSONException {
// given // given
String expected = "{\"ignore-above-type\":{\"properties\":{\"message\":{\"type\":\"keyword\",\"ignore_above\":10}}}}"; String expected = "{\"properties\":{\"message\":{\"type\":\"keyword\",\"ignore_above\":10}}}";
// when // when
String mapping = getMappingBuilder().buildPropertyMapping(IgnoreAboveEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(IgnoreAboveEntity.class);
@ -429,9 +428,8 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test @Test
public void shouldSetFieldMappingProperties() throws JSONException, IOException { public void shouldSetFieldMappingProperties() throws JSONException {
String expected = "{\n" + // String expected = "{\n" + //
" \"fmp\": {\n" + //
" \"properties\": {\n" + // " \"properties\": {\n" + //
" \"storeTrue\": {\n" + // " \"storeTrue\": {\n" + //
" \"store\": true\n" + // " \"store\": true\n" + //
@ -516,7 +514,6 @@ public class MappingBuilderTests extends MappingContextBaseTests {
" \"scaling_factor\": 100.0\n" + // " \"scaling_factor\": 100.0\n" + //
" }\n" + // " }\n" + //
" }\n" + // " }\n" + //
" }\n" + //
"}\n"; // "}\n"; //
// when // when
@ -527,10 +524,9 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
@Test @Test
void shouldWriteDynamicMappingSettings() throws IOException, JSONException { void shouldWriteDynamicMappingSettings() throws JSONException {
String expected = "{\n" + // String expected = "{\n" + //
" \"dms\": {\n" + //
" \"dynamic\": \"false\",\n" + // " \"dynamic\": \"false\",\n" + //
" \"properties\": {\n" + // " \"properties\": {\n" + //
" \"author\": {\n" + // " \"author\": {\n" + //
@ -539,7 +535,6 @@ public class MappingBuilderTests extends MappingContextBaseTests {
" \"properties\": {}\n" + // " \"properties\": {}\n" + //
" }\n" + // " }\n" + //
" }\n" + // " }\n" + //
" }\n" + //
"}\n"; "}\n";
String mapping = getMappingBuilder().buildPropertyMapping(ConfigureDynamicMappingEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(ConfigureDynamicMappingEntity.class);
@ -555,7 +550,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "ignore-above-index", type = "ignore-above-type") @Document(indexName = "ignore-above-index")
static class IgnoreAboveEntity { static class IgnoreAboveEntity {
@Id private String id; @Id private String id;
@ -569,12 +564,12 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@SuppressWarnings("unused") @SuppressWarnings("unused")
static class FieldNameEntity { static class FieldNameEntity {
@Document(indexName = "fieldname-index", type = "fieldname-type") @Document(indexName = "fieldname-index")
static class IdEntity { static class IdEntity {
@Id @Field("id-property") private String id; @Id @Field("id-property") private String id;
} }
@Document(indexName = "fieldname-index", type = "fieldname-type") @Document(indexName = "fieldname-index")
static class TextEntity { static class TextEntity {
@Id @Field("id-property") private String id; @Id @Field("id-property") private String id;
@ -583,7 +578,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
private String textProperty; private String textProperty;
} }
@Document(indexName = "fieldname-index", type = "fieldname-type") @Document(indexName = "fieldname-index")
static class MappingEntity { static class MappingEntity {
@Id @Field("id-property") private String id; @Id @Field("id-property") private String id;
@ -592,7 +587,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
private byte[] mappingProperty; private byte[] mappingProperty;
} }
@Document(indexName = "fieldname-index", type = "fieldname-type") @Document(indexName = "fieldname-index")
static class GeoPointEntity { static class GeoPointEntity {
@Id @Field("id-property") private String id; @Id @Field("id-property") private String id;
@ -600,7 +595,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@Field("geopoint-property") private GeoPoint geoPoint; @Field("geopoint-property") private GeoPoint geoPoint;
} }
@Document(indexName = "fieldname-index", type = "fieldname-type") @Document(indexName = "fieldname-index")
static class CircularEntity { static class CircularEntity {
@Id @Field("id-property") private String id; @Id @Field("id-property") private String id;
@ -609,7 +604,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
private CircularEntity circularProperty; private CircularEntity circularProperty;
} }
@Document(indexName = "fieldname-index", type = "fieldname-type") @Document(indexName = "fieldname-index")
static class CompletionEntity { static class CompletionEntity {
@Id @Field("id-property") private String id; @Id @Field("id-property") private String id;
@ -618,7 +613,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
private Completion suggest; private Completion suggest;
} }
@Document(indexName = "fieldname-index", type = "fieldname-type") @Document(indexName = "fieldname-index")
static class MultiFieldEntity { static class MultiFieldEntity {
@Id @Field("id-property") private String id; @Id @Field("id-property") private String id;
@ -635,7 +630,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
* *
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
*/ */
@Document(indexName = "test-index-minimal", type = "mapping") @Document(indexName = "test-index-minimal")
static class MinimalChildEntity { static class MinimalChildEntity {
@Id private String id; @Id private String id;
@ -653,7 +648,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-book-mapping-builder", type = "book", shards = 1, replicas = 0, @Document(indexName = "test-index-book-mapping-builder", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class Book { static class Book {
@ -670,7 +665,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
* @author Stuart Stevenson * @author Stuart Stevenson
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = "test-index-simple-recursive-mapping-builder", type = "circular-object", shards = 1, @Document(indexName = "test-index-simple-recursive-mapping-builder",
replicas = 0, refreshInterval = "-1") replicas = 0, refreshInterval = "-1")
static class SimpleRecursiveEntity { static class SimpleRecursiveEntity {
@ -686,7 +681,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-copy-to-mapping-builder", type = "test", shards = 1, replicas = 0, refreshInterval = "-1") @Document(indexName = "test-copy-to-mapping-builder", replicas = 0, refreshInterval = "-1")
static class CopyToEntity { static class CopyToEntity {
@Id private String id; @Id private String id;
@ -706,7 +701,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-normalizer-mapping-builder", type = "test", shards = 1, replicas = 0, @Document(indexName = "test-index-normalizer-mapping-builder", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
@Setting(settingPath = "/settings/test-normalizer.json") @Setting(settingPath = "/settings/test-normalizer.json")
static class NormalizerEntity { static class NormalizerEntity {
@ -748,7 +743,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
/** /**
* @author Kevin Leturc * @author Kevin Leturc
*/ */
@Document(indexName = "test-index-sample-inherited-mapping-builder", type = "mapping", shards = 1, replicas = 0, @Document(indexName = "test-index-sample-inherited-mapping-builder", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class SampleInheritedEntity extends AbstractInheritedEntity { static class SampleInheritedEntity extends AbstractInheritedEntity {
@ -806,7 +801,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-stock-mapping-builder", type = "price", shards = 1, replicas = 0, @Document(indexName = "test-index-stock-mapping-builder", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class StockPrice { static class StockPrice {
@ -846,7 +841,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
/** /**
* @author Jakub Vavrik * @author Jakub Vavrik
*/ */
@Document(indexName = "test-index-recursive-mapping-mapping-builder", type = "mapping", shards = 1, replicas = 0, @Document(indexName = "test-index-recursive-mapping-mapping-builder", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class SampleTransientEntity { static class SampleTransientEntity {
@ -882,7 +877,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
} }
public void setSomeField(SampleTransientEntity.NestedEntity someField) { public void setSomeField(SampleTransientEntity.NestedEntity someField) {
this.someField = someField; NestedEntity.someField = someField;
} }
public Boolean getSomething() { public Boolean getSomething() {
@ -903,7 +898,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-geo-mapping-builder", type = "geo-test-index", shards = 1, replicas = 0, @Document(indexName = "test-index-geo-mapping-builder", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class GeoEntity { static class GeoEntity {
@ -927,7 +922,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
/** /**
* Created by akonczak on 21/08/2016. * Created by akonczak on 21/08/2016.
*/ */
@Document(indexName = "test-index-user-mapping-builder", type = "user") @Document(indexName = "test-index-user-mapping-builder")
static class User { static class User {
@Id private String id; @Id private String id;
@ -937,7 +932,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
/** /**
* Created by akonczak on 21/08/2016. * Created by akonczak on 21/08/2016.
*/ */
@Document(indexName = "test-index-group-mapping-builder", type = "group") @Document(indexName = "test-index-group-mapping-builder")
static class Group { static class Group {
@Id String id; @Id String id;
@ -945,7 +940,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@Field(type = FieldType.Nested, ignoreFields = { "groups" }) private Set<User> users = new HashSet<>(); @Field(type = FieldType.Nested, ignoreFields = { "groups" }) private Set<User> users = new HashSet<>();
} }
@Document(indexName = "test-index-field-mapping-parameters", type = "fmp") @Document(indexName = "test-index-field-mapping-parameters")
static class FieldMappingParameters { static class FieldMappingParameters {
@Field private String indexTrue; @Field private String indexTrue;
@Field(index = false) private String indexFalse; @Field(index = false) private String indexFalse;
@ -960,14 +955,14 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@Field(type = FieldType.Integer) private String type; @Field(type = FieldType.Integer) private String type;
@Field(type = FieldType.Date, format = DateFormat.custom, pattern = "YYYYMMDD") private LocalDate date; @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "YYYYMMDD") private LocalDate date;
@Field(analyzer = "ana", searchAnalyzer = "sana", normalizer = "norma") private String analyzers; @Field(analyzer = "ana", searchAnalyzer = "sana", normalizer = "norma") private String analyzers;
@Field(type = Keyword, docValues = true) private String docValuesTrue; @Field(type = Keyword) private String docValuesTrue;
@Field(type = Keyword, docValues = false) private String docValuesFalse; @Field(type = Keyword, docValues = false) private String docValuesFalse;
@Field(ignoreMalformed = true) private String ignoreMalformedTrue; @Field(ignoreMalformed = true) private String ignoreMalformedTrue;
@Field(ignoreMalformed = false) private String ignoreMalformedFalse; @Field() private String ignoreMalformedFalse;
@Field(indexOptions = IndexOptions.none) private String indexOptionsNone; @Field(indexOptions = IndexOptions.none) private String indexOptionsNone;
@Field(indexOptions = IndexOptions.positions) private String indexOptionsPositions; @Field(indexOptions = IndexOptions.positions) private String indexOptionsPositions;
@Field(indexPhrases = true) private String indexPhrasesTrue; @Field(indexPhrases = true) private String indexPhrasesTrue;
@Field(indexPhrases = false) private String indexPhrasesFalse; @Field() private String indexPhrasesFalse;
@Field(indexPrefixes = @IndexPrefixes) private String defaultIndexPrefixes; @Field(indexPrefixes = @IndexPrefixes) private String defaultIndexPrefixes;
@Field(indexPrefixes = @IndexPrefixes(minChars = 1, maxChars = 10)) private String customIndexPrefixes; @Field(indexPrefixes = @IndexPrefixes(minChars = 1, maxChars = 10)) private String customIndexPrefixes;
@Field private String normsTrue; @Field private String normsTrue;
@ -982,7 +977,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@Field(type = FieldType.Scaled_Float, scalingFactor = 100.0) Double scaledFloat; @Field(type = FieldType.Scaled_Float, scalingFactor = 100.0) Double scaledFloat;
} }
@Document(indexName = "test-index-configure-dynamic-mapping", type = "dms") @Document(indexName = "test-index-configure-dynamic-mapping")
@DynamicMapping(DynamicMappingValue.False) @DynamicMapping(DynamicMappingValue.False)
static class ConfigureDynamicMappingEntity { static class ConfigureDynamicMappingEntity {

View File

@ -42,28 +42,28 @@ import org.springframework.test.context.ContextConfiguration;
public class SimpleDynamicTemplatesMappingTests extends MappingContextBaseTests { public class SimpleDynamicTemplatesMappingTests extends MappingContextBaseTests {
@Test // DATAES-568 @Test // DATAES-568
public void testCorrectDynamicTemplatesMappings() throws IOException { public void testCorrectDynamicTemplatesMappings() {
String mapping = getMappingBuilder().buildPropertyMapping(SampleDynamicTemplatesEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(SampleDynamicTemplatesEntity.class);
String EXPECTED_MAPPING_ONE = "{\"test-dynamictemplatestype\":{\"dynamic_templates\":" String EXPECTED_MAPPING_ONE = "{\"dynamic_templates\":"
+ "[{\"with_custom_analyzer\":{" + "[{\"with_custom_analyzer\":{"
+ "\"mapping\":{\"type\":\"string\",\"analyzer\":\"standard_lowercase_asciifolding\"}," + "\"mapping\":{\"type\":\"string\",\"analyzer\":\"standard_lowercase_asciifolding\"},"
+ "\"path_match\":\"names.*\"}}]," + "\"properties\":{\"names\":{\"type\":\"object\"}}}}"; + "\"path_match\":\"names.*\"}}]," + "\"properties\":{\"names\":{\"type\":\"object\"}}}";
assertThat(mapping).isEqualTo(EXPECTED_MAPPING_ONE); assertThat(mapping).isEqualTo(EXPECTED_MAPPING_ONE);
} }
@Test // DATAES-568 @Test // DATAES-568
public void testCorrectDynamicTemplatesMappingsTwo() throws IOException { public void testCorrectDynamicTemplatesMappingsTwo() {
String mapping = getMappingBuilder().buildPropertyMapping(SampleDynamicTemplatesEntityTwo.class); String mapping = getMappingBuilder().buildPropertyMapping(SampleDynamicTemplatesEntityTwo.class);
String EXPECTED_MAPPING_TWO = "{\"test-dynamictemplatestype\":{\"dynamic_templates\":" String EXPECTED_MAPPING_TWO = "{\"dynamic_templates\":"
+ "[{\"with_custom_analyzer\":{" + "[{\"with_custom_analyzer\":{"
+ "\"mapping\":{\"type\":\"string\",\"analyzer\":\"standard_lowercase_asciifolding\"}," + "\"mapping\":{\"type\":\"string\",\"analyzer\":\"standard_lowercase_asciifolding\"},"
+ "\"path_match\":\"names.*\"}}," + "{\"participantA1_with_custom_analyzer\":{" + "\"path_match\":\"names.*\"}}," + "{\"participantA1_with_custom_analyzer\":{"
+ "\"mapping\":{\"type\":\"string\",\"analyzer\":\"standard_lowercase_asciifolding\"}," + "\"mapping\":{\"type\":\"string\",\"analyzer\":\"standard_lowercase_asciifolding\"},"
+ "\"path_match\":\"participantA1.*\"}}]," + "\"properties\":{\"names\":{\"type\":\"object\"}}}}"; + "\"path_match\":\"participantA1.*\"}}]," + "\"properties\":{\"names\":{\"type\":\"object\"}}}";
assertThat(mapping).isEqualTo(EXPECTED_MAPPING_TWO); assertThat(mapping).isEqualTo(EXPECTED_MAPPING_TWO);
} }
@ -71,27 +71,27 @@ public class SimpleDynamicTemplatesMappingTests extends MappingContextBaseTests
/** /**
* @author Petr Kukral * @author Petr Kukral
*/ */
@Document(indexName = "test-dynamictemplates", type = "test-dynamictemplatestype", indexStoreType = "memory", @Document(indexName = "test-dynamictemplates", indexStoreType = "memory",
shards = 1, replicas = 0, refreshInterval = "-1") replicas = 0, refreshInterval = "-1")
@DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings.json") @DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings.json")
static class SampleDynamicTemplatesEntity { static class SampleDynamicTemplatesEntity {
@Id private String id; @Id private String id;
@Field(type = FieldType.Object) private Map<String, String> names = new HashMap<String, String>(); @Field(type = FieldType.Object) private Map<String, String> names = new HashMap<>();
} }
/** /**
* @author Petr Kukral * @author Petr Kukral
*/ */
@Document(indexName = "test-dynamictemplates", type = "test-dynamictemplatestype", indexStoreType = "memory", @Document(indexName = "test-dynamictemplates", indexStoreType = "memory",
shards = 1, replicas = 0, refreshInterval = "-1") replicas = 0, refreshInterval = "-1")
@DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings_two.json") @DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings_two.json")
static class SampleDynamicTemplatesEntityTwo { static class SampleDynamicTemplatesEntityTwo {
@Id private String id; @Id private String id;
@Field(type = FieldType.Object) private Map<String, String> names = new HashMap<String, String>(); @Field(type = FieldType.Object) private Map<String, String> names = new HashMap<>();
} }
} }

View File

@ -38,13 +38,13 @@ import org.springframework.data.elasticsearch.annotations.FieldType;
*/ */
public class SimpleElasticsearchDateMappingTests extends MappingContextBaseTests { public class SimpleElasticsearchDateMappingTests extends MappingContextBaseTests {
private static final String EXPECTED_MAPPING = "{\"mapping\":{\"properties\":{\"message\":{\"store\":true," private static final String EXPECTED_MAPPING = "{\"properties\":{\"message\":{\"store\":true,"
+ "\"type\":\"text\",\"index\":false,\"analyzer\":\"standard\"},\"customFormatDate\":{\"type\":\"date\",\"format\":\"dd.MM.yyyy hh:mm\"}," + "\"type\":\"text\",\"index\":false,\"analyzer\":\"standard\"},\"customFormatDate\":{\"type\":\"date\",\"format\":\"dd.MM.yyyy hh:mm\"},"
+ "\"defaultFormatDate\":{\"type\":\"date\"},\"basicFormatDate\":{\"" + "\"defaultFormatDate\":{\"type\":\"date\"},\"basicFormatDate\":{\""
+ "type\":\"date\",\"format\":\"basic_date\"}}}}"; + "type\":\"date\",\"format\":\"basic_date\"}}}";
@Test // DATAES-568 @Test // DATAES-568
public void testCorrectDateMappings() throws IOException { public void testCorrectDateMappings() {
String mapping = getMappingBuilder().buildPropertyMapping(SampleDateMappingEntity.class); String mapping = getMappingBuilder().buildPropertyMapping(SampleDateMappingEntity.class);
@ -55,7 +55,7 @@ public class SimpleElasticsearchDateMappingTests extends MappingContextBaseTests
* @author Jakub Vavrik * @author Jakub Vavrik
*/ */
@Data @Data
@Document(indexName = "test-index-date-mapping-core", type = "mapping", shards = 1, replicas = 0, @Document(indexName = "test-index-date-mapping-core", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class SampleDateMappingEntity { static class SampleDateMappingEntity {

View File

@ -39,7 +39,7 @@ import org.springframework.util.ReflectionUtils;
public class SimpleElasticsearchPersistentEntityTests { public class SimpleElasticsearchPersistentEntityTests {
@Test @Test
public void shouldThrowExceptionGivenVersionPropertyIsNotLong() throws NoSuchFieldException, IntrospectionException { public void shouldThrowExceptionGivenVersionPropertyIsNotLong() {
// given // given
TypeInformation typeInformation = ClassTypeInformation.from(EntityWithWrongVersionType.class); TypeInformation typeInformation = ClassTypeInformation.from(EntityWithWrongVersionType.class);
SimpleElasticsearchPersistentEntity<EntityWithWrongVersionType> entity = new SimpleElasticsearchPersistentEntity<>( SimpleElasticsearchPersistentEntity<EntityWithWrongVersionType> entity = new SimpleElasticsearchPersistentEntity<>(
@ -51,8 +51,7 @@ public class SimpleElasticsearchPersistentEntityTests {
} }
@Test @Test
public void shouldThrowExceptionGivenMultipleVersionPropertiesArePresent() public void shouldThrowExceptionGivenMultipleVersionPropertiesArePresent() {
throws NoSuchFieldException, IntrospectionException {
// given // given
TypeInformation typeInformation = ClassTypeInformation.from(EntityWithMultipleVersionField.class); TypeInformation typeInformation = ClassTypeInformation.from(EntityWithMultipleVersionField.class);
SimpleElasticsearchPersistentEntity<EntityWithMultipleVersionField> entity = new SimpleElasticsearchPersistentEntity<>( SimpleElasticsearchPersistentEntity<EntityWithMultipleVersionField> entity = new SimpleElasticsearchPersistentEntity<>(

View File

@ -30,6 +30,7 @@ import java.lang.Long;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -41,6 +42,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score; import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit; import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
@ -65,14 +67,21 @@ public class CriteriaQueryTests {
private final IndexCoordinates index = IndexCoordinates.of("test-index-sample-core-query").withTypes("test-type"); private final IndexCoordinates index = IndexCoordinates.of("test-index-sample-core-query").withTypes("test-type");
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
indexOperations = operations.getIndexOperations();
operations.deleteIndex(SampleEntity.class); indexOperations.deleteIndex(SampleEntity.class);
operations.createIndex(SampleEntity.class); indexOperations.createIndex(SampleEntity.class);
operations.putMapping(SampleEntity.class); indexOperations.putMapping(SampleEntity.class);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
}
@AfterEach
void after() {
indexOperations.deleteIndex(SampleEntity.class);
} }
@Test @Test
@ -89,7 +98,7 @@ public class CriteriaQueryTests {
indexQuery.setId(documentId); indexQuery.setId(documentId);
indexQuery.setObject(sampleEntity); indexQuery.setObject(sampleEntity);
operations.index(indexQuery, index); operations.index(indexQuery, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery( CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("test").and("message").contains("some")); new Criteria("message").contains("test").and("message").contains("some"));
@ -132,7 +141,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery( CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("some").or("message").contains("test")); new Criteria("message").contains("some").or("message").contains("test"));
@ -163,7 +172,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery); indexQueries.add(indexQuery);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().and(new Criteria("message").contains("some"))); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().and(new Criteria("message").contains("some")));
// when // when
@ -194,7 +203,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery); indexQueries.add(indexQuery);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().or(new Criteria("message").contains("some"))); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().or(new Criteria("message").contains("some")));
// when // when
@ -223,7 +232,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery); indexQueries.add(indexQuery);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message"));
// when // when
@ -265,7 +274,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message"));
// when // when
@ -307,7 +316,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
Criteria criteria = new Criteria("message").endsWith("end"); Criteria criteria = new Criteria("message").endsWith("end");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria); CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
@ -349,7 +358,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
Criteria criteria = new Criteria("message").startsWith("start"); Criteria criteria = new Criteria("message").startsWith("start");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria); CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
@ -391,7 +400,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("contains")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("contains"));
// when // when
@ -432,7 +441,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").expression("+elasticsearch || test")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").expression("+elasticsearch || test"));
// when // when
@ -473,7 +482,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery( CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").startsWith("some").endsWith("search").contains("message").is("some message search")); new Criteria("message").startsWith("some").endsWith("search").contains("message").is("some message search"));
@ -515,7 +524,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("foo").not()); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("foo").not());
// when // when
@ -559,7 +568,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100, 150)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100, 150));
// when // when
@ -601,7 +610,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(350, null)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(350, null));
// when // when
@ -644,7 +653,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(null, 550)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(null, 550));
// when // when
@ -687,7 +696,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").lessThanEqual(750)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").lessThanEqual(750));
// when // when
@ -730,7 +739,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").greaterThanEqual(950)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").greaterThanEqual(950));
// when // when
@ -773,7 +782,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1));
// when // when
@ -794,7 +803,7 @@ public class CriteriaQueryTests {
indexQueries.add(buildIndex(SampleEntity.builder().id("3").message("ac").build())); indexQueries.add(buildIndex(SampleEntity.builder().id("3").message("ac").build()));
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
// when // when
CriteriaQuery criteriaQuery = new CriteriaQuery( CriteriaQuery criteriaQuery = new CriteriaQuery(
@ -821,7 +830,7 @@ public class CriteriaQueryTests {
indexQuery.setId(documentId); indexQuery.setId(documentId);
indexQuery.setObject(sampleEntity); indexQuery.setObject(sampleEntity);
operations.index(indexQuery, index); operations.index(indexQuery, index);
operations.refresh(SampleEntity.class); indexOperations.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("Hello World!")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("Hello World!"));
@ -837,7 +846,7 @@ public class CriteriaQueryTests {
@Getter @Getter
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Document(indexName = "test-index-sample-core-query", type = "test-type", shards = 1, replicas = 0, @Document(indexName = "test-index-sample-core-query", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {

View File

@ -112,7 +112,7 @@ class ClusterConnection implements ExtensionContext.Store.CloseableResource {
} }
@Override @Override
public void close() throws Exception { public void close() {
if (node != null) { if (node != null) {
LOGGER.debug("closing node"); LOGGER.debug("closing node");

View File

@ -24,7 +24,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration; import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients; import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration; import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.util.Assert;
/** /**
* Configuration for Spring Data Elasticsearch using * Configuration for Spring Data Elasticsearch using

View File

@ -21,7 +21,6 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import java.lang.annotation.Target;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
/** /**
* Wraps the {@link SpringDataElasticsearchExtension}. * Wraps the {@link SpringDataElasticsearchExtension}.

View File

@ -57,7 +57,7 @@ public class SpringDataElasticsearchExtension
private static final Lock initLock = new ReentrantLock(); private static final Lock initLock = new ReentrantLock();
@Override @Override
public void beforeAll(ExtensionContext extensionContext) throws Exception { public void beforeAll(ExtensionContext extensionContext) {
initLock.lock(); initLock.lock();
try { try {
ExtensionContext.Store store = getStore(extensionContext); ExtensionContext.Store store = getStore(extensionContext);

View File

@ -27,5 +27,6 @@ import org.springframework.data.repository.CrudRepository;
*/ */
public interface CdiProductRepository extends CrudRepository<CdiRepositoryTests.Product, String> { public interface CdiProductRepository extends CrudRepository<CdiRepositoryTests.Product, String> {
@Override
Optional<CdiRepositoryTests.Product> findById(String id); Optional<CdiRepositoryTests.Product> findById(String id);
} }

View File

@ -158,7 +158,7 @@ public class CdiRepositoryTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-product-cdi-repository", type = "test-product-type", shards = 1, replicas = 0, @Document(indexName = "test-index-product-cdi-repository", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class Product { static class Product {
@ -188,7 +188,7 @@ public class CdiRepositoryTests {
} }
@Data @Data
@Document(indexName = "test-index-person-cdi-repository", type = "user", shards = 1, replicas = 0, @Document(indexName = "test-index-person-cdi-repository", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class Person { static class Person {
@ -206,7 +206,7 @@ public class CdiRepositoryTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-book-cdi-repository", type = "book", shards = 1, replicas = 0, @Document(indexName = "test-index-book-cdi-repository", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class Book { static class Book {

View File

@ -25,7 +25,7 @@ import javax.inject.Qualifier;
/** /**
* @author Mark Paluch * @author Mark Paluch
* @see DATAES-234 * @see <a href="https://jira.spring.io/browse/DATAES-234">DATAES-234</a>
*/ */
@Qualifier @Qualifier
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@ -25,7 +25,7 @@ import javax.inject.Qualifier;
/** /**
* @author Mark Paluch * @author Mark Paluch
* @see DATAES-234 * @see <a href="https://jira.spring.io/browse/DATAES-234">DATAES-234</a>
*/ */
@Qualifier @Qualifier
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@ -19,7 +19,7 @@ import org.springframework.data.repository.CrudRepository;
/** /**
* @author Mark Paluch * @author Mark Paluch
* @see DATAES-234 * @see <a href="https://jira.spring.io/browse/DATAES-234">DATAES-234</a>
*/ */
@PersonDB @PersonDB
@OtherQualifier @OtherQualifier

View File

@ -19,7 +19,7 @@ import org.springframework.data.repository.Repository;
/** /**
* @author Mark Paluch * @author Mark Paluch
* @see DATAES-113 * @see <a href="https://jira.spring.io/browse/DATAES-113">DATAES-113</a>
*/ */
public interface SamplePersonRepository public interface SamplePersonRepository
extends Repository<CdiRepositoryTests.Person, Long>, SamplePersonRepositoryCustom { extends Repository<CdiRepositoryTests.Person, Long>, SamplePersonRepositoryCustom {

View File

@ -17,8 +17,8 @@
package org.springframework.data.elasticsearch.repositories.cdi; package org.springframework.data.elasticsearch.repositories.cdi;
/** /**
* @see DATAES-113
* @author Mark Paluch * @author Mark Paluch
* @see <a href="https://jira.spring.io/browse/DATAES-113">DATAES-113</a>
*/ */
interface SamplePersonRepositoryCustom { interface SamplePersonRepositoryCustom {

View File

@ -17,8 +17,8 @@
package org.springframework.data.elasticsearch.repositories.cdi; package org.springframework.data.elasticsearch.repositories.cdi;
/** /**
* @see DATAES-113
* @author Mark Paluch * @author Mark Paluch
* @see <a href="https://jira.spring.io/browse/DATAES-113">DATAES-113</a>
*/ */
class SamplePersonRepositoryImpl implements SamplePersonRepositoryCustom { class SamplePersonRepositoryImpl implements SamplePersonRepositoryCustom {

View File

@ -20,6 +20,7 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.Data; import lombok.Data;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -29,6 +30,7 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@ -52,10 +54,17 @@ public class ComplexCustomMethodRepositoryTests {
@Autowired private ComplexElasticsearchRepository complexRepository; @Autowired private ComplexElasticsearchRepository complexRepository;
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(operations, SampleEntity.class); indexOperations = operations.getIndexOperations();
IndexInitializer.init(indexOperations, SampleEntity.class);
}
@AfterEach
void after() {
indexOperations.deleteIndex(SampleEntity.class);
} }
@Test @Test
@ -71,8 +80,8 @@ public class ComplexCustomMethodRepositoryTests {
} }
@Data @Data
@Document(indexName = "test-index-sample-repositories-complex-custommethod-autowiring", type = "test-type", @Document(indexName = "test-index-sample-repositories-complex-custommethod-autowiring",
shards = 1, replicas = 0, refreshInterval = "-1") replicas = 0, refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {
@Id private String id; @Id private String id;

View File

@ -21,5 +21,5 @@ package org.springframework.data.elasticsearch.repositories.complex.custommethod
*/ */
public interface ComplexElasticsearchRepositoryCustom { public interface ComplexElasticsearchRepositoryCustom {
public String doSomethingSpecial(); String doSomethingSpecial();
} }

View File

@ -20,6 +20,7 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.Data; import lombok.Data;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -29,6 +30,7 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@ -51,10 +53,17 @@ public class ComplexCustomMethodRepositoryManualWiringTests {
@Autowired private ComplexElasticsearchRepositoryManualWiring complexRepository; @Autowired private ComplexElasticsearchRepositoryManualWiring complexRepository;
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(operations, SampleEntity.class); indexOperations = operations.getIndexOperations();
IndexInitializer.init(indexOperations, SampleEntity.class);
}
@AfterEach
void after() {
indexOperations.deleteIndex(SampleEntity.class);
} }
@Test @Test
@ -70,7 +79,7 @@ public class ComplexCustomMethodRepositoryManualWiringTests {
} }
@Data @Data
@Document(indexName = "test-index-sample-repository-manual-wiring", type = "test-type", shards = 1, replicas = 0, @Document(indexName = "test-index-sample-repository-manual-wiring", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {

View File

@ -32,6 +32,8 @@ import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
@ -44,10 +46,13 @@ import org.springframework.data.domain.Sort.Order;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.geo.GeoBox; import org.springframework.data.elasticsearch.core.geo.GeoBox;
import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.data.geo.Box; import org.springframework.data.geo.Box;
import org.springframework.data.geo.Distance; import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics; import org.springframework.data.geo.Metrics;
@ -70,6 +75,20 @@ public abstract class CustomMethodRepositoryBaseTests {
@Autowired private SampleStreamingCustomMethodRepository streamingRepository; @Autowired private SampleStreamingCustomMethodRepository streamingRepository;
@Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach
public void before() {
indexOperations = operations.getIndexOperations();
IndexInitializer.init(indexOperations, SampleEntity.class);
}
@AfterEach
void after() {
indexOperations.deleteIndex(SampleEntity.class);
}
@Test @Test
public void shouldExecuteCustomMethod() { public void shouldExecuteCustomMethod() {
@ -1367,7 +1386,7 @@ public abstract class CustomMethodRepositoryBaseTests {
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@Builder @Builder
@Document(indexName = "test-index-sample-repositories-custo-method", type = "test-type", shards = 1, replicas = 0, @Document(indexName = "test-index-sample-repositories-custo-method", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {

View File

@ -15,14 +15,10 @@
*/ */
package org.springframework.data.elasticsearch.repositories.custommethod; package org.springframework.data.elasticsearch.repositories.custommethod;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
/** /**
@ -39,11 +35,4 @@ public class CustomMethodRepositoryRestTests extends CustomMethodRepositoryBaseT
basePackages = { "org.springframework.data.elasticsearch.repositories.custommethod" }, basePackages = { "org.springframework.data.elasticsearch.repositories.custommethod" },
considerNestedRepositories = true) considerNestedRepositories = true)
static class Config {} static class Config {}
@Autowired private ElasticsearchRestTemplate elasticsearchTemplate;
@BeforeEach
public void before() {
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
}
} }

View File

@ -15,14 +15,10 @@
*/ */
package org.springframework.data.elasticsearch.repositories.custommethod; package org.springframework.data.elasticsearch.repositories.custommethod;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
/** /**
@ -40,10 +36,4 @@ public class CustomMethodRepositoryTests extends CustomMethodRepositoryBaseTests
considerNestedRepositories = true) considerNestedRepositories = true)
static class Config {} static class Config {}
@Autowired private ElasticsearchOperations operations;
@BeforeEach
public void before() {
IndexInitializer.init(operations, SampleEntity.class);
}
} }

View File

@ -31,6 +31,7 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version; import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
@ -57,16 +58,17 @@ public class DoubleIDRepositoryTests {
@Autowired private DoubleIDRepository repository; @Autowired private DoubleIDRepository repository;
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(operations, DoubleIDEntity.class); indexOperations = operations.getIndexOperations();
IndexInitializer.init(indexOperations, DoubleIDEntity.class);
} }
@AfterEach @AfterEach
public void after() { public void after() {
indexOperations.deleteIndex(DoubleIDEntity.class);
operations.deleteIndex(DoubleIDEntity.class);
} }
@Test @Test
@ -119,7 +121,7 @@ public class DoubleIDRepositoryTests {
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@Document(indexName = "test-index-double-keyed-entity", type = "double-keyed-entity", shards = 1, replicas = 0, @Document(indexName = "test-index-double-keyed-entity", replicas = 0,
refreshInterval = "-1") refreshInterval = "-1")
static class DoubleIDEntity { static class DoubleIDEntity {

Some files were not shown because too many files have changed in this diff Show More