Code cleanup (Java 17).

Original Pull Request #2271
Closes #2270
This commit is contained in:
Peter-Josef Meisch 2022-08-13 15:07:47 +02:00 committed by GitHub
parent b511756b2b
commit a4ed7300d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
120 changed files with 2986 additions and 3260 deletions

View File

@ -47,6 +47,19 @@ adjust your imports as well.
When working with the `NativeSearchQuery` class, you'll need to switch to the `NativeQuery` class, which can take a
`Query` instance comign from the new Elasticsearch client libraries. You'll find plenty of examples in the test code.
=== Conversion to Java 17 records
The following classes have been converted to `Record`, you might need to adjust the use of getter methods from
`getProp()` to `prop()`:
* `org.springframework.data.elasticsearch.core.AbstractReactiveElasticsearchTemplate.IndexResponseMetaData`
* `org.springframework.data.elasticsearch.core.ActiveShardCount`
* `org.springframework.data.elasticsearch.support.Version`
* `org.springframework.data.elasticsearch.support.ScoreDoc`
* `org.springframework.data.elasticsearch.core.query.ScriptData`
* `org.springframework.data.elasticsearch.core.query.SeqNoPrimaryTerm`
[[elasticsearch-migration-guide-4.4-5.0.new-clients]]
== New Elasticsearch client

View File

@ -17,8 +17,6 @@ package org.springframework.data.elasticsearch.client;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
@ -63,7 +61,7 @@ class DefaultClientConfiguration implements ClientConfiguration {
Function<WebClient, WebClient> webClientConfigurer, HttpClientConfigCallback httpClientConfigurer,
List<ClientConfigurationCallback<?>> clientConfigurers, Supplier<HttpHeaders> headersSupplier) {
this.hosts = Collections.unmodifiableList(new ArrayList<>(hosts));
this.hosts = List.copyOf(hosts);
this.headers = new HttpHeaders(headers);
this.useSsl = useSsl;
this.sslContext = sslContext;

View File

@ -18,6 +18,7 @@ package org.springframework.data.elasticsearch.client.elc;
import co.elastic.clients.ApiClient;
import co.elastic.clients.elasticsearch.cluster.ElasticsearchClusterClient;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.transport.Transport;
import java.io.IOException;
@ -32,7 +33,7 @@ import org.springframework.util.Assert;
* @author Peter-Josef Meisch
* @since 4.4
*/
public abstract class ChildTemplate<CLIENT extends ApiClient> {
public abstract class ChildTemplate<T extends Transport, CLIENT extends ApiClient<T, CLIENT>> {
protected final CLIENT client;
protected final RequestConverter requestConverter;

View File

@ -18,6 +18,7 @@ package org.springframework.data.elasticsearch.client.elc;
import co.elastic.clients.elasticsearch.cluster.ElasticsearchClusterClient;
import co.elastic.clients.elasticsearch.cluster.HealthRequest;
import co.elastic.clients.elasticsearch.cluster.HealthResponse;
import co.elastic.clients.transport.ElasticsearchTransport;
import org.springframework.data.elasticsearch.core.cluster.ClusterHealth;
import org.springframework.data.elasticsearch.core.cluster.ClusterOperations;
@ -29,7 +30,8 @@ import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverte
* @author Peter-Josef Meisch
* @since 4.4
*/
public class ClusterTemplate extends ChildTemplate<ElasticsearchClusterClient> implements ClusterOperations {
public class ClusterTemplate extends ChildTemplate<ElasticsearchTransport, ElasticsearchClusterClient>
implements ClusterOperations {
public ClusterTemplate(ElasticsearchClusterClient client, ElasticsearchConverter elasticsearchConverter) {
super(client, elasticsearchConverter);

View File

@ -130,37 +130,37 @@ class CriteriaFilterProcessor {
ObjectBuilder<? extends QueryVariant> queryBuilder = null;
switch (key) {
case WITHIN:
case WITHIN -> {
Assert.isTrue(value instanceof Object[], "Value of a geo distance filter should be an array of two values.");
queryBuilder = withinQuery(fieldName, (Object[]) value);
break;
case BBOX:
}
case BBOX -> {
Assert.isTrue(value instanceof Object[],
"Value of a boundedBy filter should be an array of one or two values.");
queryBuilder = boundingBoxQuery(fieldName, (Object[]) value);
break;
case GEO_INTERSECTS:
}
case GEO_INTERSECTS -> {
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_INTERSECTS filter must be a GeoJson object");
queryBuilder = geoJsonQuery(fieldName, (GeoJson<?>) value, "intersects");
break;
case GEO_IS_DISJOINT:
}
case GEO_IS_DISJOINT -> {
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_IS_DISJOINT filter must be a GeoJson object");
queryBuilder = geoJsonQuery(fieldName, (GeoJson<?>) value, "disjoint");
break;
case GEO_WITHIN:
}
case GEO_WITHIN -> {
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_WITHIN filter must be a GeoJson object");
queryBuilder = geoJsonQuery(fieldName, (GeoJson<?>) value, "within");
break;
case GEO_CONTAINS:
}
case GEO_CONTAINS -> {
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_CONTAINS filter must be a GeoJson object");
queryBuilder = geoJsonQuery(fieldName, (GeoJson<?>) value, "contains");
break;
}
}
return Optional.ofNullable(queryBuilder != null ? queryBuilder.build()._toQuery() : null);
}
private static ObjectBuilder<GeoDistanceQuery> withinQuery(String fieldName, Object[] values) {
private static ObjectBuilder<GeoDistanceQuery> withinQuery(String fieldName, Object... values) {
Assert.noNullElements(values, "Geo distance filter takes 2 not null elements array as parameter.");
Assert.isTrue(values.length == 2, "Geo distance filter takes a 2-elements array as parameter.");
@ -176,8 +176,7 @@ class CriteriaFilterProcessor {
.distance(dist) //
.distanceType(GeoDistanceType.Plane) //
.location(location -> {
if (values[0] instanceof GeoPoint) {
GeoPoint loc = (GeoPoint) values[0];
if (values[0]instanceof GeoPoint loc) {
location.latlon(latlon -> latlon.lat(loc.getLat()).lon(loc.getLon()));
} else if (values[0] instanceof Point) {
GeoPoint loc = GeoPoint.fromPoint((Point) values[0]);
@ -195,7 +194,7 @@ class CriteriaFilterProcessor {
});
}
private static ObjectBuilder<GeoBoundingBoxQuery> boundingBoxQuery(String fieldName, Object[] values) {
private static ObjectBuilder<GeoBoundingBoxQuery> boundingBoxQuery(String fieldName, Object... values) {
Assert.noNullElements(values, "Geo boundedBy filter takes a not null element array as parameter.");
@ -240,13 +239,12 @@ class CriteriaFilterProcessor {
)))));
}
private static void twoParameterBBox(GeoBoundingBoxQuery.Builder queryBuilder, Object[] values) {
private static void twoParameterBBox(GeoBoundingBoxQuery.Builder queryBuilder, Object... values) {
Assert.isTrue(allElementsAreOfType(values, GeoPoint.class) || allElementsAreOfType(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) {
GeoPoint topLeft = (GeoPoint) values[0];
if (values[0]instanceof GeoPoint topLeft) {
GeoPoint bottomRight = (GeoPoint) values[1];
queryBuilder.boundingBox(bb -> bb //
.tlbr(tlbr -> tlbr //
@ -329,12 +327,8 @@ class CriteriaFilterProcessor {
StringBuilder sb = new StringBuilder();
sb.append((int) distance.getValue());
switch ((Metrics) distance.getMetric()) {
case KILOMETERS:
sb.append("km");
break;
case MILES:
sb.append("mi");
break;
case KILOMETERS -> sb.append("km");
case MILES -> sb.append("mi");
}
return sb.toString();

View File

@ -288,8 +288,7 @@ class CriteriaQueryProcessor {
break;
case IN:
if (value instanceof Iterable) {
Iterable<?> iterable = (Iterable<?>) value;
if (value instanceof Iterable<?> iterable) {
if (isKeywordField) {
queryBuilder.bool(bb -> bb //
.must(mb -> mb //
@ -310,8 +309,7 @@ class CriteriaQueryProcessor {
}
break;
case NOT_IN:
if (value instanceof Iterable) {
Iterable<?> iterable = (Iterable<?>) value;
if (value instanceof Iterable<?> iterable) {
if (isKeywordField) {
queryBuilder.bool(bb -> bb //
.mustNot(mnb -> mnb //

View File

@ -101,12 +101,12 @@ final class DocumentAdapters {
EntityAsMap hitFieldsAsMap = fromFields.apply(hit.fields());
Map<String, List<Object>> documentFields = new LinkedHashMap<>();
hitFieldsAsMap.entrySet().forEach(entry -> {
if (entry.getValue() instanceof List) {
hitFieldsAsMap.forEach((key, value) -> {
if (value instanceof List) {
// noinspection unchecked
documentFields.put(entry.getKey(), (List<Object>) entry.getValue());
documentFields.put(key, (List<Object>) value);
} else {
documentFields.put(entry.getKey(), Collections.singletonList(entry.getValue()));
documentFields.put(key, Collections.singletonList(value));
}
});
@ -117,8 +117,7 @@ final class DocumentAdapters {
} else {
if (source instanceof EntityAsMap) {
document = Document.from((EntityAsMap) source);
} else if (source instanceof JsonData) {
JsonData jsonData = (JsonData) source;
} else if (source instanceof JsonData jsonData) {
document = Document.from(jsonData.to(EntityAsMap.class));
} else {

View File

@ -305,9 +305,9 @@ public final class ElasticsearchClients {
+ ((header.getName().equals("Authorization")) ? ": *****" : ": " + header.getValue()))
.collect(Collectors.joining(", ", "[", "]"));
if (request instanceof HttpEntityEnclosingRequest && ((HttpEntityEnclosingRequest) request).getEntity() != null) {
if (request instanceof HttpEntityEnclosingRequest entityRequest
&& ((HttpEntityEnclosingRequest) request).getEntity() != null) {
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
entity.writeTo(buffer);
@ -377,7 +377,6 @@ public final class ElasticsearchClients {
Assert.notNull(httpClientBuilderCallback, "httpClientBuilderCallback must not be null");
// noinspection NullableProblems
return httpClientBuilderCallback::apply;
}
}
@ -396,7 +395,6 @@ public final class ElasticsearchClients {
Assert.notNull(restClientBuilderCallback, "restClientBuilderCallback must not be null");
// noinspection NullableProblems
return restClientBuilderCallback::apply;
}
}

View File

@ -72,14 +72,14 @@ public class ElasticsearchExceptionTranslator implements PersistenceExceptionTra
return new OptimisticLockingFailureException("Cannot index a document due to seq_no+primary_term conflict", ex);
}
if (ex instanceof ElasticsearchException) {
ElasticsearchException elasticsearchException = (ElasticsearchException) ex;
if (ex instanceof ElasticsearchException elasticsearchException) {
ErrorResponse response = elasticsearchException.response();
if (response.status() == HttpStatus.NOT_FOUND.value()
&& "index_not_found_exception".equals(response.error().type())) {
// noinspection RegExpRedundantEscape
Pattern pattern = Pattern.compile(".*no such index \\[(.*)\\]");
String index = "";
Matcher matcher = pattern.matcher(response.error().reason());
@ -109,9 +109,7 @@ public class ElasticsearchExceptionTranslator implements PersistenceExceptionTra
Integer status = null;
String message = null;
if (exception instanceof ResponseException) {
ResponseException responseException = (ResponseException) exception;
if (exception instanceof ResponseException responseException) {
status = responseException.getResponse().getStatusLine().getStatusCode();
message = responseException.getMessage();
} else if (exception.getCause() != null) {

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.client.elc;
import static co.elastic.clients.util.ApiTypeHelper.*;
import static org.springframework.data.elasticsearch.client.elc.TypeUtils.*;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
@ -476,16 +475,7 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
/**
* value class combining the information needed for a single query in a multisearch request.
*/
static class MultiSearchQueryParameter {
final Query query;
final Class<?> clazz;
final IndexCoordinates index;
public MultiSearchQueryParameter(Query query, Class<?> clazz, IndexCoordinates index) {
this.query = query;
this.clazz = clazz;
this.index = index;
}
record MultiSearchQueryParameter(Query query, Class<?> clazz, IndexCoordinates index) {
}
// endregion

View File

@ -18,6 +18,7 @@ package org.springframework.data.elasticsearch.client.elc;
import static org.springframework.util.StringUtils.*;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import java.util.List;
@ -56,7 +57,8 @@ import org.springframework.util.Assert;
* @author Peter-Josef Meisch
* @since 4.4
*/
public class IndicesTemplate extends ChildTemplate<ElasticsearchIndicesClient> implements IndexOperations {
public class IndicesTemplate extends ChildTemplate<ElasticsearchTransport, ElasticsearchIndicesClient>
implements IndexOperations {
private static final Logger LOGGER = LoggerFactory.getLogger(IndicesTemplate.class);
@ -187,7 +189,6 @@ public class IndicesTemplate extends ChildTemplate<ElasticsearchIndicesClient> i
Assert.notNull(clazz, "clazz must not be null");
// load mapping specified in Mapping annotation if present
// noinspection DuplicatedCode
Mapping mappingAnnotation = AnnotatedElementUtils.findMergedAnnotation(clazz, Mapping.class);
if (mappingAnnotation != null) {

View File

@ -17,6 +17,7 @@ package org.springframework.data.elasticsearch.client.elc;
import co.elastic.clients.ApiClient;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.transport.Transport;
import reactor.core.publisher.Flux;
import org.reactivestreams.Publisher;
@ -29,18 +30,17 @@ import org.springframework.util.Assert;
* @author Peter-Josef Meisch
* @since 4.4
*/
public class ReactiveChildTemplate<CLIENT extends ApiClient> {
public class ReactiveChildTemplate<T extends Transport, CLIENT extends ApiClient<T, CLIENT>> {
protected final CLIENT client;
protected final ElasticsearchConverter elasticsearchConverter;
protected final RequestConverter requestConverter;
protected final ResponseConverter responseConverter;
private final JsonpMapper jsonpMapper;
protected final ElasticsearchExceptionTranslator exceptionTranslator;
public ReactiveChildTemplate(CLIENT client, ElasticsearchConverter elasticsearchConverter) {
this.client = client;
this.elasticsearchConverter = elasticsearchConverter;
jsonpMapper = client._transport().jsonpMapper();
JsonpMapper jsonpMapper = client._transport().jsonpMapper();
requestConverter = new RequestConverter(elasticsearchConverter, jsonpMapper);
responseConverter = new ResponseConverter(jsonpMapper);
exceptionTranslator = new ElasticsearchExceptionTranslator(jsonpMapper);

View File

@ -17,6 +17,7 @@ package org.springframework.data.elasticsearch.client.elc;
import co.elastic.clients.elasticsearch.cluster.HealthRequest;
import co.elastic.clients.elasticsearch.cluster.HealthResponse;
import co.elastic.clients.transport.ElasticsearchTransport;
import reactor.core.publisher.Mono;
import org.springframework.data.elasticsearch.client.erhlc.ReactiveClusterOperations;
@ -27,7 +28,8 @@ import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverte
* @author Peter-Josef Meisch
* @since 4.4
*/
public class ReactiveClusterTemplate extends ReactiveChildTemplate<ReactiveElasticsearchClusterClient>
public class ReactiveClusterTemplate
extends ReactiveChildTemplate<ElasticsearchTransport, ReactiveElasticsearchClusterClient>
implements ReactiveClusterOperations {
public ReactiveClusterTemplate(ReactiveElasticsearchClusterClient client,

View File

@ -327,8 +327,7 @@ public class ReactiveElasticsearchTemplate extends AbstractReactiveElasticsearch
Time scrollTimeout = searchRequest.scroll() != null ? searchRequest.scroll() : Time.of(t -> t.time("1m"));
Flux<ResponseBody<EntityAsMap>> searchResponses = Flux.usingWhen(Mono.fromSupplier(ScrollState::new), //
state -> {
return Mono
state -> Mono
.from(execute((ClientCallback<Publisher<ResponseBody<EntityAsMap>>>) client1 -> client1
.search(searchRequest, EntityAsMap.class))) //
.expand(entityAsMapSearchResponse -> {
@ -345,8 +344,8 @@ public class ReactiveElasticsearchTemplate extends AbstractReactiveElasticsearch
.of(sr -> sr.scrollId(state.getScrollId()).scroll(scrollTimeout));
return client1.scroll(scrollRequest, EntityAsMap.class);
}));
});
}, this::cleanupScroll, (state, ex) -> cleanupScroll(state), this::cleanupScroll);
}),
this::cleanupScroll, (state, ex) -> cleanupScroll(state), this::cleanupScroll);
return searchResponses.flatMapIterable(entityAsMapSearchResponse -> entityAsMapSearchResponse.hits().hits())
.map(entityAsMapHit -> DocumentAdapters.from(entityAsMapHit, jsonpMapper));

View File

@ -19,6 +19,7 @@ import static org.springframework.util.StringUtils.*;
import co.elastic.clients.elasticsearch._types.AcknowledgedResponseBase;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@ -53,7 +54,8 @@ import org.springframework.util.Assert;
/**
* @author Peter-Josef Meisch
*/
public class ReactiveIndicesTemplate extends ReactiveChildTemplate<ReactiveElasticsearchIndicesClient>
public class ReactiveIndicesTemplate
extends ReactiveChildTemplate<ElasticsearchTransport, ReactiveElasticsearchIndicesClient>
implements ReactiveIndexOperations {
@Nullable private final Class<?> boundClass;
@ -152,7 +154,7 @@ public class ReactiveIndicesTemplate extends ReactiveChildTemplate<ReactiveElast
@Override
public Mono<Void> refresh() {
return Mono.from(execute(client1 -> client1.refresh())).then();
return Mono.from(execute(ReactiveElasticsearchIndicesClient::refresh)).then();
}
@Override

View File

@ -32,7 +32,16 @@ import co.elastic.clients.elasticsearch._types.mapping.RuntimeFieldType;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch._types.query_dsl.Like;
import co.elastic.clients.elasticsearch.cluster.HealthRequest;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.DeleteByQueryRequest;
import co.elastic.clients.elasticsearch.core.DeleteRequest;
import co.elastic.clients.elasticsearch.core.GetRequest;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.MgetRequest;
import co.elastic.clients.elasticsearch.core.MsearchRequest;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.UpdateByQueryRequest;
import co.elastic.clients.elasticsearch.core.UpdateRequest;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.bulk.CreateOperation;
import co.elastic.clients.elasticsearch.core.bulk.IndexOperation;
@ -43,7 +52,6 @@ import co.elastic.clients.elasticsearch.core.search.Highlight;
import co.elastic.clients.elasticsearch.core.search.Rescore;
import co.elastic.clients.elasticsearch.core.search.SourceConfig;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.elasticsearch.indices.ExistsRequest;
import co.elastic.clients.elasticsearch.indices.update_aliases.Action;
import co.elastic.clients.json.JsonData;
import co.elastic.clients.json.JsonpDeserializer;
@ -176,8 +184,7 @@ class RequestConverter {
Action.Builder actionBuilder = new Action.Builder();
if (aliasAction instanceof AliasAction.Add) {
AliasAction.Add add = (AliasAction.Add) aliasAction;
if (aliasAction instanceof AliasAction.Add add) {
AliasActionParameters parameters = add.getParameters();
actionBuilder.add(addActionBuilder -> {
addActionBuilder //
@ -206,8 +213,7 @@ class RequestConverter {
});
}
if (aliasAction instanceof AliasAction.Remove) {
AliasAction.Remove remove = (AliasAction.Remove) aliasAction;
if (aliasAction instanceof AliasAction.Remove remove) {
AliasActionParameters parameters = remove.getParameters();
actionBuilder.remove(removeActionBuilder -> {
removeActionBuilder.indices(Arrays.asList(parameters.getIndices()));
@ -220,8 +226,7 @@ class RequestConverter {
});
}
if (aliasAction instanceof AliasAction.RemoveIndex) {
AliasAction.RemoveIndex removeIndex = (AliasAction.RemoveIndex) aliasAction;
if (aliasAction instanceof AliasAction.RemoveIndex removeIndex) {
AliasActionParameters parameters = removeIndex.getParameters();
actionBuilder.removeIndex(
removeIndexActionBuilder -> removeIndexActionBuilder.indices(Arrays.asList(parameters.getIndices())));
@ -429,7 +434,6 @@ class RequestConverter {
* so the code needs to be duplicated.
*/
@SuppressWarnings("DuplicatedCode")
public IndexRequest<?> documentIndexRequest(IndexQuery query, IndexCoordinates indexCoordinates,
@Nullable RefreshPolicy refreshPolicy) {
@ -469,12 +473,8 @@ class RequestConverter {
if (query.getOpType() != null) {
switch (query.getOpType()) {
case INDEX:
builder.opType(OpType.Index);
break;
case CREATE:
builder.opType(OpType.Create);
break;
case INDEX -> builder.opType(OpType.Index);
case CREATE -> builder.opType(OpType.Create);
}
}
@ -617,20 +617,18 @@ class RequestConverter {
Map<String, JsonData> params = new HashMap<>();
if (scriptData.getParams() != null) {
scriptData.getParams().forEach((key, value) -> {
params.put(key, JsonData.of(value, jsonpMapper));
});
if (scriptData.params() != null) {
scriptData.params().forEach((key, value) -> params.put(key, JsonData.of(value, jsonpMapper)));
}
return co.elastic.clients.elasticsearch._types.Script.of(sb -> {
if (scriptData.getType() == ScriptType.INLINE) {
if (scriptData.type() == ScriptType.INLINE) {
sb.inline(is -> is //
.lang(scriptData.getLanguage()) //
.source(scriptData.getScript()) //
.lang(scriptData.language()) //
.source(scriptData.script()) //
.params(params)); //
} else if (scriptData.getType() == ScriptType.STORED) {
} else if (scriptData.type() == ScriptType.STORED) {
sb.stored(ss -> ss //
.id(scriptData.getScript()) //
.id(scriptData.script()) //
.params(params) //
);
}
@ -653,7 +651,7 @@ class RequestConverter {
}
if (bulkOptions.getWaitForActiveShards() != null) {
builder.waitForActiveShards(wasb -> wasb.count(bulkOptions.getWaitForActiveShards().getValue()));
builder.waitForActiveShards(wasb -> wasb.count(bulkOptions.getWaitForActiveShards().value()));
}
if (bulkOptions.getPipeline() != null) {
@ -666,16 +664,14 @@ class RequestConverter {
List<BulkOperation> operations = queries.stream().map(query -> {
BulkOperation.Builder ob = new BulkOperation.Builder();
if (query instanceof IndexQuery) {
IndexQuery indexQuery = (IndexQuery) query;
if (query instanceof IndexQuery indexQuery) {
if (indexQuery.getOpType() == IndexQuery.OpType.CREATE) {
ob.create(bulkCreateOperation(indexQuery, indexCoordinates, refreshPolicy));
} else {
ob.index(bulkIndexOperation(indexQuery, indexCoordinates, refreshPolicy));
}
} else if (query instanceof UpdateQuery) {
UpdateQuery updateQuery = (UpdateQuery) query;
} else if (query instanceof UpdateQuery updateQuery) {
ob.update(bulkUpdateOperation(updateQuery, indexCoordinates, refreshPolicy));
}
return ob.build();
@ -724,8 +720,8 @@ class RequestConverter {
List<MultiGetOperation> multiGetOperations = query.getIdsWithRouting().stream()
.map(idWithRouting -> MultiGetOperation.of(mgo -> mgo //
.index(index.getIndexName()) //
.id(idWithRouting.getId()) //
.routing(idWithRouting.getRouting()) //
.id(idWithRouting.id()) //
.routing(idWithRouting.routing()) //
.source(sourceConfig)))
.collect(Collectors.toList());
@ -880,9 +876,7 @@ class RequestConverter {
Map<String, JsonData> params = new HashMap<>();
if (query.getParams() != null) {
query.getParams().forEach((key, value) -> {
params.put(key, JsonData.of(value, jsonpMapper));
});
query.getParams().forEach((key, value) -> params.put(key, JsonData.of(value, jsonpMapper)));
}
uqb.script(sb -> {
@ -1047,13 +1041,13 @@ class RequestConverter {
// normal search and msearch
return MsearchRequest.of(mrb -> {
multiSearchQueryParameters.forEach(param -> {
ElasticsearchPersistentEntity<?> persistentEntity = getPersistentEntity(param.clazz);
ElasticsearchPersistentEntity<?> persistentEntity = getPersistentEntity(param.clazz());
var query = param.query;
var query = param.query();
mrb.searches(sb -> sb //
.header(h -> {
h //
.index(Arrays.asList(param.index.getIndexNames())) //
.index(Arrays.asList(param.index().getIndexNames())) //
.routing(query.getRoute()) //
.searchType(searchType(query.getSearchType())) //
.requestCache(query.getRequestCache()) //
@ -1067,7 +1061,7 @@ class RequestConverter {
}) //
.body(bb -> {
bb //
.query(getQuery(query, param.clazz))//
.query(getQuery(query, param.clazz()))//
.seqNoPrimaryTerm(persistentEntity != null ? persistentEntity.hasSeqNoPrimaryTermProperty() : null) //
.version(true) //
.trackScores(query.getTrackScores()) //
@ -1118,9 +1112,7 @@ class RequestConverter {
bb.searchAfter(query.getSearchAfter().stream().map(Object::toString).collect(Collectors.toList()));
}
query.getRescorerQueries().forEach(rescorerQuery -> {
bb.rescore(getRescore(rescorerQuery));
});
query.getRescorerQueries().forEach(rescorerQuery -> bb.rescore(getRescore(rescorerQuery)));
if (!query.getRuntimeFields().isEmpty()) {
Map<String, List<RuntimeField>> runtimeMappings = new HashMap<>();
@ -1142,9 +1134,8 @@ class RequestConverter {
if (!isEmpty(query.getIndicesBoost())) {
Map<String, Double> boosts = new LinkedHashMap<>();
query.getIndicesBoost().forEach(indexBoost -> {
boosts.put(indexBoost.getIndexName(), (double) indexBoost.getBoost());
});
query.getIndicesBoost()
.forEach(indexBoost -> boosts.put(indexBoost.getIndexName(), (double) indexBoost.getBoost()));
// noinspection unchecked
bb.indicesBoost(boosts);
}
@ -1256,20 +1247,18 @@ class RequestConverter {
builder.searchAfter(query.getSearchAfter().stream().map(Object::toString).collect(Collectors.toList()));
}
query.getRescorerQueries().forEach(rescorerQuery -> {
builder.rescore(getRescore(rescorerQuery));
});
query.getRescorerQueries().forEach(rescorerQuery -> builder.rescore(getRescore(rescorerQuery)));
builder.requestCache(query.getRequestCache());
if (!query.getRuntimeFields().isEmpty()) {
Map<String, List<RuntimeField>> runtimeMappings = new HashMap<>();
query.getRuntimeFields().forEach(runtimeField -> {
runtimeMappings.put(runtimeField.getName(), Collections.singletonList(RuntimeField.of(rt -> rt //
query.getRuntimeFields()
.forEach(runtimeField -> runtimeMappings.put(runtimeField.getName(),
Collections.singletonList(RuntimeField.of(rt -> rt //
.type(RuntimeFieldType._DESERIALIZER.parse(runtimeField.getType())) //
.script(s -> s.inline(is -> is.source(runtimeField.getScript()))))));
});
.script(s -> s.inline(is -> is.source(runtimeField.getScript())))))));
builder.runtimeMappings(runtimeMappings);
}
@ -1288,9 +1277,8 @@ class RequestConverter {
if (!isEmpty(query.getIndicesBoost())) {
Map<String, Double> boosts = new LinkedHashMap<>();
query.getIndicesBoost().forEach(indexBoost -> {
boosts.put(indexBoost.getIndexName(), (double) indexBoost.getBoost());
});
query.getIndicesBoost()
.forEach(indexBoost -> boosts.put(indexBoost.getIndexName(), (double) indexBoost.getBoost()));
// noinspection unchecked
builder.indicesBoost(boosts);
}
@ -1341,8 +1329,7 @@ class RequestConverter {
Order.Mode mode = Order.DEFAULT_MODE;
String unmappedType = null;
if (order instanceof Order) {
Order o = (Order) order;
if (order instanceof Order o) {
mode = o.getMode();
unmappedType = o.getUnmappedType();
}
@ -1356,8 +1343,7 @@ class RequestConverter {
String fieldName = property != null ? property.getFieldName() : order.getProperty();
Order.Mode finalMode = mode;
if (order instanceof GeoDistanceOrder) {
GeoDistanceOrder geoDistanceOrder = (GeoDistanceOrder) order;
if (order instanceof GeoDistanceOrder geoDistanceOrder) {
return SortOptions.of(so -> so //
.geoDistance(gd -> gd //
@ -1398,9 +1384,8 @@ class RequestConverter {
@SuppressWarnings("DuplicatedCode")
private void prepareNativeSearch(NativeQuery query, SearchRequest.Builder builder) {
query.getScriptedFields().forEach(scriptedField -> {
builder.scriptFields(scriptedField.getFieldName(), sf -> sf.script(getScript(scriptedField.getScriptData())));
});
query.getScriptedFields().forEach(scriptedField -> builder.scriptFields(scriptedField.getFieldName(),
sf -> sf.script(getScript(scriptedField.getScriptData()))));
builder //
.suggest(query.getSuggester()) //
@ -1417,9 +1402,8 @@ class RequestConverter {
@SuppressWarnings("DuplicatedCode")
private void prepareNativeSearch(NativeQuery query, MultisearchBody.Builder builder) {
query.getScriptedFields().forEach(scriptedField -> {
builder.scriptFields(scriptedField.getFieldName(), sf -> sf.script(getScript(scriptedField.getScriptData())));
});
query.getScriptedFields().forEach(scriptedField -> builder.scriptFields(scriptedField.getFieldName(),
sf -> sf.script(getScript(scriptedField.getScriptData()))));
builder //
.suggest(query.getSuggester()) //
@ -1449,8 +1433,7 @@ class RequestConverter {
esQuery = CriteriaQueryProcessor.createQuery(((CriteriaQuery) query).getCriteria());
} else if (query instanceof StringQuery) {
esQuery = QueryBuilders.wrapperQueryAsQuery(((StringQuery) query).getSource());
} else if (query instanceof NativeQuery) {
NativeQuery nativeQuery = (NativeQuery) query;
} else if (query instanceof NativeQuery nativeQuery) {
if (nativeQuery.getQuery() != null) {
esQuery = nativeQuery.getQuery();
@ -1584,20 +1567,12 @@ class RequestConverter {
.getVersionType();
if (entityVersionType != null) {
switch (entityVersionType) {
case INTERNAL:
versionType = VersionType.Internal;
break;
case EXTERNAL:
versionType = VersionType.External;
break;
case EXTERNAL_GTE:
versionType = VersionType.ExternalGte;
break;
case FORCE:
versionType = VersionType.Force;
break;
}
versionType = switch (entityVersionType) {
case INTERNAL -> VersionType.Internal;
case EXTERNAL -> VersionType.External;
case EXTERNAL_GTE -> VersionType.ExternalGte;
case FORCE -> VersionType.Force;
};
}
}
@ -1636,15 +1611,11 @@ class RequestConverter {
return null;
}
switch (refreshPolicy) {
case IMMEDIATE:
return true;
case WAIT_UNTIL:
return null;
case NONE:
default:
return false;
}
return switch (refreshPolicy) {
case IMMEDIATE -> true;
case WAIT_UNTIL -> null;
case NONE -> false;
};
}
// endregion

View File

@ -65,7 +65,6 @@ class SearchDocumentResponseBuilder {
* @param jsonpMapper to map JsonData objects
* @return the SearchDocumentResponse
*/
@SuppressWarnings("DuplicatedCode")
public static <T> SearchDocumentResponse from(ResponseBody<EntityAsMap> responseBody,
SearchDocumentResponse.EntityCreator<T> entityCreator, JsonpMapper jsonpMapper) {
@ -105,16 +104,11 @@ class SearchDocumentResponseBuilder {
TotalHits responseTotalHits = hitsMetadata.total();
if (responseTotalHits != null) {
totalHits = responseTotalHits.value();
switch (responseTotalHits.relation().jsonValue()) {
case "eq":
totalHitsRelation = TotalHitsRelation.EQUAL_TO.name();
break;
case "gte":
totalHitsRelation = TotalHitsRelation.GREATER_THAN_OR_EQUAL_TO.name();
break;
default:
totalHitsRelation = TotalHitsRelation.OFF.name();
}
totalHitsRelation = switch (responseTotalHits.relation().jsonValue()) {
case "eq" -> TotalHitsRelation.EQUAL_TO.name();
case "gte" -> TotalHitsRelation.GREATER_THAN_OR_EQUAL_TO.name();
default -> TotalHitsRelation.OFF.name();
};
} else {
totalHits = hitsMetadata.hits().size();
totalHitsRelation = "OFF";
@ -151,20 +145,19 @@ class SearchDocumentResponseBuilder {
if (!suggestionsES.isEmpty()) {
// take the type from the first entry
switch (suggestionsES.get(0)._kind()) {
case Term: {
case Term -> {
suggestions.add(getTermSuggestion(name, suggestionsES));
break;
}
case Phrase: {
case Phrase -> {
suggestions.add(getPhraseSuggestion(name, suggestionsES));
break;
}
case Completion: {
case Completion -> {
suggestions.add(getCompletionSuggestion(name, suggestionsES, entityCreator));
break;
}
default:
break;
default -> {}
}
}
});
@ -182,10 +175,8 @@ class SearchDocumentResponseBuilder {
var termSuggest = suggestionES.term();
var termSuggestOptions = termSuggest.options();
List<TermSuggestion.Entry.Option> options = new ArrayList<>();
termSuggestOptions.forEach(optionES -> {
options.add(new TermSuggestion.Entry.Option(optionES.text(), null, optionES.score(), null,
Math.toIntExact(optionES.freq())));
});
termSuggestOptions.forEach(optionES -> options.add(new TermSuggestion.Entry.Option(optionES.text(), null,
optionES.score(), null, Math.toIntExact(optionES.freq()))));
entries.add(new TermSuggestion.Entry(termSuggest.text(), termSuggest.offset(), termSuggest.length(), options));
});
return new TermSuggestion(name, suggestionsES.size(), entries, null);
@ -198,9 +189,8 @@ class SearchDocumentResponseBuilder {
var phraseSuggest = suggestionES.phrase();
var phraseSuggestOptions = phraseSuggest.options();
List<PhraseSuggestion.Entry.Option> options = new ArrayList<>();
phraseSuggestOptions.forEach(optionES -> {
options.add(new PhraseSuggestion.Entry.Option(optionES.text(), optionES.highlighted(), null, null));
});
phraseSuggestOptions.forEach(optionES -> options
.add(new PhraseSuggestion.Entry.Option(optionES.text(), optionES.highlighted(), null, null)));
entries.add(new PhraseSuggestion.Entry(phraseSuggest.text(), phraseSuggest.offset(), phraseSuggest.length(),
options, null));
});

View File

@ -49,64 +49,38 @@ final class TypeUtils {
static BoundaryScanner boundaryScanner(@Nullable String value) {
if (value != null) {
switch (value.toLowerCase()) {
case "chars":
return BoundaryScanner.Chars;
case "sentence":
return BoundaryScanner.Sentence;
case "word":
return BoundaryScanner.Word;
default:
return null;
}
return switch (value.toLowerCase()) {
case "chars" -> BoundaryScanner.Chars;
case "sentence" -> BoundaryScanner.Sentence;
case "word" -> BoundaryScanner.Word;
default -> null;
};
}
return null;
}
static Conflicts conflicts(ReindexRequest.Conflicts conflicts) {
switch (conflicts) {
case ABORT:
return Conflicts.Abort;
case PROCEED:
return Conflicts.Proceed;
}
throw new IllegalArgumentException("Cannot map conflicts value " + conflicts.name());
return switch (conflicts) {
case ABORT -> Conflicts.Abort;
case PROCEED -> Conflicts.Proceed;
};
}
@Nullable
static DistanceUnit distanceUnit(String unit) {
switch (unit.toLowerCase()) {
case "in":
case "inch":
return DistanceUnit.Inches;
case "yd":
case "yards":
return DistanceUnit.Yards;
case "ft":
case "feet":
return DistanceUnit.Feet;
case "km":
case "kilometers":
return DistanceUnit.Kilometers;
case "nm":
case "nmi":
return DistanceUnit.NauticMiles;
case "mm":
case "millimeters":
return DistanceUnit.Millimeters;
case "cm":
case "centimeters":
return DistanceUnit.Centimeters;
case "mi":
case "miles":
return DistanceUnit.Miles;
case "m":
case "meters":
return DistanceUnit.Meters;
}
return null;
return switch (unit.toLowerCase()) {
case "in", "inch" -> DistanceUnit.Inches;
case "yd", "yards" -> DistanceUnit.Yards;
case "ft", "feet" -> DistanceUnit.Feet;
case "km", "kilometers" -> DistanceUnit.Kilometers;
case "nm", "nmi" -> DistanceUnit.NauticMiles;
case "mm", "millimeters" -> DistanceUnit.Millimeters;
case "cm", "centimeters" -> DistanceUnit.Centimeters;
case "mi", "miles" -> DistanceUnit.Miles;
case "m", "meters" -> DistanceUnit.Meters;
default -> null;
};
}
@Nullable
@ -124,28 +98,22 @@ final class TypeUtils {
@Nullable
static GeoDistanceType geoDistanceType(GeoDistanceOrder.DistanceType distanceType) {
switch (distanceType) {
case arc:
return GeoDistanceType.Arc;
case plane:
return GeoDistanceType.Plane;
}
return switch (distanceType) {
case arc -> GeoDistanceType.Arc;
case plane -> GeoDistanceType.Plane;
};
return null;
}
@Nullable
static HighlighterFragmenter highlighterFragmenter(@Nullable String value) {
if (value != null) {
switch (value.toLowerCase()) {
case "simple":
return HighlighterFragmenter.Simple;
case "span":
return HighlighterFragmenter.Span;
default:
return null;
}
return switch (value.toLowerCase()) {
case "simple" -> HighlighterFragmenter.Simple;
case "span" -> HighlighterFragmenter.Span;
default -> null;
};
}
return null;
@ -167,16 +135,12 @@ final class TypeUtils {
static HighlighterType highlighterType(@Nullable String value) {
if (value != null) {
switch (value.toLowerCase()) {
case "unified":
return HighlighterType.Unified;
case "plain":
return HighlighterType.Plain;
case "fvh":
return HighlighterType.FastVector;
default:
return null;
}
return switch (value.toLowerCase()) {
case "unified" -> HighlighterType.Unified;
case "plain" -> HighlighterType.Plain;
case "fvh" -> HighlighterType.FastVector;
default -> null;
};
}
return null;
@ -186,14 +150,11 @@ final class TypeUtils {
static HighlighterEncoder highlighterEncoder(@Nullable String value) {
if (value != null) {
switch (value.toLowerCase()) {
case "default":
return HighlighterEncoder.Default;
case "html":
return HighlighterEncoder.Html;
default:
return null;
}
return switch (value.toLowerCase()) {
case "default" -> HighlighterEncoder.Default;
case "html" -> HighlighterEncoder.Html;
default -> null;
};
}
return null;
@ -215,12 +176,10 @@ final class TypeUtils {
static OpType opType(@Nullable IndexQuery.OpType opType) {
if (opType != null) {
switch (opType) {
case INDEX:
return OpType.Index;
case CREATE:
return OpType.Create;
}
return switch (opType) {
case INDEX -> OpType.Index;
case CREATE -> OpType.Create;
};
}
return null;
}
@ -231,15 +190,11 @@ final class TypeUtils {
return Refresh.False;
}
switch (refreshPolicy) {
case IMMEDIATE:
return Refresh.True;
case WAIT_UNTIL:
return Refresh.WaitFor;
case NONE:
default:
return Refresh.False;
}
return switch (refreshPolicy) {
case IMMEDIATE -> Refresh.True;
case WAIT_UNTIL -> Refresh.WaitFor;
case NONE -> Refresh.False;
};
}
@Nullable
@ -249,20 +204,14 @@ final class TypeUtils {
return null;
}
switch (result) {
case Created:
return UpdateResponse.Result.CREATED;
case Updated:
return UpdateResponse.Result.UPDATED;
case Deleted:
return UpdateResponse.Result.DELETED;
case NotFound:
return UpdateResponse.Result.NOT_FOUND;
case NoOp:
return UpdateResponse.Result.NOOP;
}
return switch (result) {
case Created -> UpdateResponse.Result.CREATED;
case Updated -> UpdateResponse.Result.UPDATED;
case Deleted -> UpdateResponse.Result.DELETED;
case NotFound -> UpdateResponse.Result.NOT_FOUND;
case NoOp -> UpdateResponse.Result.NOOP;
};
return null;
}
@Nullable
@ -272,22 +221,15 @@ final class TypeUtils {
return null;
}
switch (scoreMode) {
case Default:
return null;
case Avg:
return ScoreMode.Avg;
case Max:
return ScoreMode.Max;
case Min:
return ScoreMode.Min;
case Total:
return ScoreMode.Total;
case Multiply:
return ScoreMode.Multiply;
}
return switch (scoreMode) {
case Default -> null;
case Avg -> ScoreMode.Avg;
case Max -> ScoreMode.Max;
case Min -> ScoreMode.Min;
case Total -> ScoreMode.Total;
case Multiply -> ScoreMode.Multiply;
};
return null;
}
@Nullable
@ -297,14 +239,11 @@ final class TypeUtils {
return null;
}
switch (searchType) {
case QUERY_THEN_FETCH:
return SearchType.QueryThenFetch;
case DFS_QUERY_THEN_FETCH:
return SearchType.DfsQueryThenFetch;
}
return switch (searchType) {
case QUERY_THEN_FETCH -> SearchType.QueryThenFetch;
case DFS_QUERY_THEN_FETCH -> SearchType.DfsQueryThenFetch;
};
return null;
}
@Nullable
@ -320,18 +259,13 @@ final class TypeUtils {
@Nullable
static SortMode sortMode(Order.Mode mode) {
switch (mode) {
case min:
return SortMode.Min;
case max:
return SortMode.Max;
case median:
return SortMode.Median;
case avg:
return SortMode.Avg;
}
return switch (mode) {
case min -> SortMode.Min;
case max -> SortMode.Max;
case median -> SortMode.Median;
case avg -> SortMode.Avg;
};
return null;
}
@Nullable
@ -359,16 +293,12 @@ final class TypeUtils {
@Nullable org.springframework.data.elasticsearch.annotations.Document.VersionType versionType) {
if (versionType != null) {
switch (versionType) {
case INTERNAL:
return VersionType.Internal;
case EXTERNAL:
return VersionType.External;
case EXTERNAL_GTE:
return VersionType.ExternalGte;
case FORCE:
return VersionType.Force;
}
return switch (versionType) {
case INTERNAL -> VersionType.Internal;
case EXTERNAL -> VersionType.External;
case EXTERNAL_GTE -> VersionType.ExternalGte;
case FORCE -> VersionType.Force;
};
}
return null;

View File

@ -105,37 +105,37 @@ class CriteriaFilterProcessor {
QueryBuilder filter = null;
switch (key) {
case WITHIN:
case WITHIN -> {
Assert.isTrue(value instanceof Object[], "Value of a geo distance filter should be an array of two values.");
filter = withinQuery(fieldName, (Object[]) value);
break;
case BBOX:
}
case BBOX -> {
Assert.isTrue(value instanceof Object[],
"Value of a boundedBy filter should be an array of one or two values.");
filter = boundingBoxQuery(fieldName, (Object[]) value);
break;
case GEO_INTERSECTS:
}
case GEO_INTERSECTS -> {
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_INTERSECTS filter must be a GeoJson object");
filter = geoJsonQuery(fieldName, (GeoJson<?>) value, "intersects");
break;
case GEO_IS_DISJOINT:
}
case GEO_IS_DISJOINT -> {
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_IS_DISJOINT filter must be a GeoJson object");
filter = geoJsonQuery(fieldName, (GeoJson<?>) value, "disjoint");
break;
case GEO_WITHIN:
}
case GEO_WITHIN -> {
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_WITHIN filter must be a GeoJson object");
filter = geoJsonQuery(fieldName, (GeoJson<?>) value, "within");
break;
case GEO_CONTAINS:
}
case GEO_CONTAINS -> {
Assert.isTrue(value instanceof GeoJson<?>, "value of a GEO_CONTAINS filter must be a GeoJson object");
filter = geoJsonQuery(fieldName, (GeoJson<?>) value, "contains");
break;
}
}
return filter;
}
private QueryBuilder withinQuery(String fieldName, Object[] valArray) {
private QueryBuilder withinQuery(String fieldName, Object... valArray) {
GeoDistanceQueryBuilder filter = QueryBuilders.geoDistanceQuery(fieldName);
@ -154,8 +154,7 @@ class CriteriaFilterProcessor {
dist.append((String) valArray[1]);
}
if (valArray[0] instanceof GeoPoint) {
GeoPoint loc = (GeoPoint) valArray[0];
if (valArray[0]instanceof GeoPoint loc) {
filter.point(loc.getLat(), loc.getLon()).distance(dist.toString()).geoDistance(GeoDistance.PLANE);
} else if (valArray[0] instanceof Point) {
GeoPoint loc = GeoPoint.fromPoint((Point) valArray[0]);
@ -174,7 +173,7 @@ class CriteriaFilterProcessor {
return filter;
}
private QueryBuilder boundingBoxQuery(String fieldName, Object[] valArray) {
private QueryBuilder boundingBoxQuery(String fieldName, Object... valArray) {
Assert.noNullElements(valArray, "Geo boundedBy filter takes a not null element array as parameter.");
@ -217,12 +216,8 @@ class CriteriaFilterProcessor {
Metrics metric = (Metrics) distance.getMetric();
switch (metric) {
case KILOMETERS:
sb.append("km");
break;
case MILES:
sb.append("mi");
break;
case KILOMETERS -> sb.append("km");
case MILES -> sb.append("mi");
}
}
@ -250,11 +245,10 @@ class CriteriaFilterProcessor {
return true;
}
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)");
if (values[0] instanceof GeoPoint) {
GeoPoint topLeft = (GeoPoint) values[0];
if (values[0]instanceof GeoPoint topLeft) {
GeoPoint bottomRight = (GeoPoint) values[1];
filter.setCorners(topLeft.getLat(), topLeft.getLon(), bottomRight.getLat(), bottomRight.getLon());
} else {

View File

@ -175,17 +175,10 @@ class CriteriaQueryProcessor {
// operations without a value
switch (key) {
case EXISTS:
query = existsQuery(fieldName);
break;
case EMPTY:
query = boolQuery().must(existsQuery(fieldName)).mustNot(wildcardQuery(fieldName, "*"));
break;
case NOT_EMPTY:
query = wildcardQuery(fieldName, "*");
break;
default:
break;
case EXISTS -> query = existsQuery(fieldName);
case EMPTY -> query = boolQuery().must(existsQuery(fieldName)).mustNot(wildcardQuery(fieldName, "*"));
case NOT_EMPTY -> query = wildcardQuery(fieldName, "*");
default -> {}
}
if (query != null) {
@ -238,8 +231,7 @@ class CriteriaQueryProcessor {
query = matchQuery(fieldName, value).operator(org.elasticsearch.index.query.Operator.AND);
break;
case IN:
if (value instanceof Iterable) {
Iterable<?> iterable = (Iterable<?>) value;
if (value instanceof Iterable<?> iterable) {
if (isKeywordField) {
query = boolQuery().must(termsQuery(fieldName, toStringList(iterable)));
} else {
@ -248,8 +240,7 @@ class CriteriaQueryProcessor {
}
break;
case NOT_IN:
if (value instanceof Iterable) {
Iterable<?> iterable = (Iterable<?>) value;
if (value instanceof Iterable<?> iterable) {
if (isKeywordField) {
query = boolQuery().mustNot(termsQuery(fieldName, toStringList(iterable)));
} else {

View File

@ -717,10 +717,9 @@ public final class DocumentAdapters {
if (this == o) {
return true;
}
if (!(o instanceof SearchDocumentAdapter)) {
if (!(o instanceof SearchDocumentAdapter that)) {
return false;
}
SearchDocumentAdapter that = (SearchDocumentAdapter) o;
return Float.compare(that.score, score) == 0 && delegate.equals(that.delegate);
}

View File

@ -56,17 +56,14 @@ public class ElasticsearchExceptionTranslator implements PersistenceExceptionTra
return new OptimisticLockingFailureException("Cannot index a document due to seq_no+primary_term conflict", ex);
}
if (ex instanceof ElasticsearchException) {
ElasticsearchException elasticsearchException = (ElasticsearchException) ex;
if (ex instanceof ElasticsearchException elasticsearchException) {
if (!indexAvailable(elasticsearchException)) {
return new NoSuchIndexException(ObjectUtils.nullSafeToString(elasticsearchException.getMetadata("es.index")),
ex);
}
if (elasticsearchException instanceof ElasticsearchStatusException) {
ElasticsearchStatusException elasticsearchStatusException = (ElasticsearchStatusException) elasticsearchException;
if (elasticsearchException instanceof ElasticsearchStatusException elasticsearchStatusException) {
return new RestStatusException(elasticsearchStatusException.status().getStatus(),
elasticsearchStatusException.getMessage(), elasticsearchStatusException);
}
@ -74,11 +71,9 @@ public class ElasticsearchExceptionTranslator implements PersistenceExceptionTra
return new UncategorizedElasticsearchException(ex.getMessage(), ex);
}
if (ex instanceof RestStatusException) {
RestStatusException restStatusException = (RestStatusException) ex;
if (ex instanceof RestStatusException restStatusException) {
Throwable cause = restStatusException.getCause();
if (cause instanceof ElasticsearchException) {
ElasticsearchException elasticsearchException = (ElasticsearchException) cause;
if (cause instanceof ElasticsearchException elasticsearchException) {
if (!indexAvailable(elasticsearchException)) {
return new NoSuchIndexException(ObjectUtils.nullSafeToString(elasticsearchException.getMetadata("es.index")),
@ -104,16 +99,14 @@ public class ElasticsearchExceptionTranslator implements PersistenceExceptionTra
Integer status = null;
String message = null;
if (exception instanceof ElasticsearchStatusException) {
if (exception instanceof ElasticsearchStatusException statusException) {
ElasticsearchStatusException statusException = (ElasticsearchStatusException) exception;
status = statusException.status().getStatus();
message = statusException.getMessage();
}
if (exception instanceof RestStatusException) {
if (exception instanceof RestStatusException statusException) {
RestStatusException statusException = (RestStatusException) exception;
status = statusException.getStatus();
message = statusException.getMessage();
}
@ -123,9 +116,7 @@ public class ElasticsearchExceptionTranslator implements PersistenceExceptionTra
&& message.contains("version conflict, required seqNo");
}
if (exception instanceof VersionConflictEngineException) {
VersionConflictEngineException versionConflictEngineException = (VersionConflictEngineException) exception;
if (exception instanceof VersionConflictEngineException versionConflictEngineException) {
return versionConflictEngineException.getMessage() != null
&& versionConflictEngineException.getMessage().contains("version conflict, required seqNo");

View File

@ -133,9 +133,8 @@ public class HighlightQueryBuilder {
builder.highlighterType(parameters.getType());
}
if (builder instanceof HighlightBuilder && parameters instanceof HighlightParameters) {
HighlightBuilder highlightBuilder = (HighlightBuilder) builder;
HighlightParameters highlightParameters = (HighlightParameters) parameters;
if (builder instanceof HighlightBuilder highlightBuilder
&& parameters instanceof HighlightParameters highlightParameters) {
if (StringUtils.hasLength(highlightParameters.getEncoder())) {
highlightBuilder.encoder(highlightParameters.getEncoder());
@ -146,9 +145,8 @@ public class HighlightQueryBuilder {
}
}
if (builder instanceof HighlightBuilder.Field && parameters instanceof HighlightFieldParameters) {
HighlightBuilder.Field field = (HighlightBuilder.Field) builder;
HighlightFieldParameters fieldParameters = (HighlightFieldParameters) parameters;
if (builder instanceof HighlightBuilder.Field field
&& parameters instanceof HighlightFieldParameters fieldParameters) {
if ((fieldParameters).getFragmentOffset() > -1) {
field.fragmentOffset(fieldParameters.getFragmentOffset());

View File

@ -816,7 +816,7 @@ public class RequestConverters {
}
public static Request indexCreate(org.elasticsearch.client.indices.CreateIndexRequest createIndexRequest) {
String endpoint = RequestConverters.endpoint(new String[] { createIndexRequest.index() });
String endpoint = RequestConverters.endpoint(createIndexRequest.index());
Request request = new Request(HttpMethod.PUT.name(), endpoint);
Params parameters = new Params(request);
@ -1048,7 +1048,7 @@ public class RequestConverters {
return new EndpointBuilder().addPathPart(index, type, id).addPathPartAsIs(endpoint).build();
}
static String endpoint(String[] indices) {
static String endpoint(String... indices) {
return new EndpointBuilder().addCommaSeparatedPathParts(indices).build();
}
@ -1061,7 +1061,7 @@ public class RequestConverters {
.addPathPartAsIs(endpoint).build();
}
static String endpoint(String[] indices, String endpoint, String[] suffixes) {
static String endpoint(String[] indices, String endpoint, String... suffixes) {
return new EndpointBuilder().addCommaSeparatedPathParts(indices).addPathPartAsIs(endpoint)
.addCommaSeparatedPathParts(suffixes).build();
}
@ -1129,7 +1129,7 @@ public class RequestConverters {
return this;
}
Params withFields(String[] fields) {
Params withFields(String... fields) {
if (fields != null && fields.length > 0) {
return putParam("fields", String.join(",", fields));
}
@ -1190,7 +1190,7 @@ public class RequestConverters {
return putParam("routing", routing);
}
Params withStoredFields(String[] storedFields) {
Params withStoredFields(String... storedFields) {
if (storedFields != null && storedFields.length > 0) {
return putParam("stored_fields", String.join(",", storedFields));
}
@ -1313,14 +1313,14 @@ public class RequestConverters {
return putParam("wait_for_completion", waitForCompletion.toString());
}
Params withNodes(String[] nodes) {
Params withNodes(String... nodes) {
if (nodes != null && nodes.length > 0) {
return putParam("nodes", String.join(",", nodes));
}
return this;
}
Params withActions(String[] actions) {
Params withActions(String... actions) {
if (actions != null && actions.length > 0) {
return putParam("actions", String.join(",", actions));
}
@ -1423,7 +1423,7 @@ public class RequestConverters {
return this;
}
EndpointBuilder addCommaSeparatedPathParts(String[] parts) {
EndpointBuilder addCommaSeparatedPathParts(String... parts) {
addPathPart(String.join(",", parts));
return this;
}

View File

@ -166,8 +166,7 @@ class RequestFactory {
IndicesAliasesRequest.AliasActions aliasActionsES = null;
if (aliasAction instanceof AliasAction.Add) {
AliasAction.Add add = (AliasAction.Add) aliasAction;
if (aliasAction instanceof AliasAction.Add add) {
IndicesAliasesRequest.AliasActions addES = IndicesAliasesRequest.AliasActions.add();
AliasActionParameters parameters = add.getParameters();
@ -193,8 +192,7 @@ class RequestFactory {
}
aliasActionsES = addES;
} else if (aliasAction instanceof AliasAction.Remove) {
AliasAction.Remove remove = (AliasAction.Remove) aliasAction;
} else if (aliasAction instanceof AliasAction.Remove remove) {
IndicesAliasesRequest.AliasActions removeES = IndicesAliasesRequest.AliasActions.remove();
AliasActionParameters parameters = remove.getParameters();
@ -202,8 +200,7 @@ class RequestFactory {
removeES.aliases(parameters.getAliases());
aliasActionsES = removeES;
} else if (aliasAction instanceof AliasAction.RemoveIndex) {
AliasAction.RemoveIndex removeIndex = (AliasAction.RemoveIndex) aliasAction;
} else if (aliasAction instanceof AliasAction.RemoveIndex removeIndex) {
IndicesAliasesRequest.AliasActions removeIndexES = IndicesAliasesRequest.AliasActions.removeIndex();
AliasActionParameters parameters = removeIndex.getParameters();
@ -235,7 +232,7 @@ class RequestFactory {
}
if (bulkOptions.getWaitForActiveShards() != null) {
bulkRequest.waitForActiveShards(ActiveShardCount.from(bulkOptions.getWaitForActiveShards().getValue()));
bulkRequest.waitForActiveShards(ActiveShardCount.from(bulkOptions.getWaitForActiveShards().value()));
}
if (bulkOptions.getPipeline() != null) {
@ -590,9 +587,9 @@ class RequestFactory {
String indexName = index.getIndexName();
for (Query.IdWithRouting idWithRouting : searchQuery.getIdsWithRouting()) {
MultiGetRequest.Item item = new MultiGetRequest.Item(indexName, idWithRouting.getId());
if (idWithRouting.getRouting() != null) {
item = item.routing(idWithRouting.getRouting());
MultiGetRequest.Item item = new MultiGetRequest.Item(indexName, idWithRouting.id());
if (idWithRouting.routing() != null) {
item = item.routing(idWithRouting.routing());
}
// note: multiGet does not have fields, need to set sourceContext to filter
@ -653,6 +650,7 @@ class RequestFactory {
}
if (query.getOpType() != null) {
switch (query.getOpType()) {
case INDEX:
indexRequest.opType(DocWriteRequest.OpType.INDEX);
@ -677,8 +675,7 @@ class RequestFactory {
if (highlightBuilder == null) {
if (query instanceof NativeSearchQuery) {
NativeSearchQuery searchQuery = (NativeSearchQuery) query;
if (query instanceof NativeSearchQuery searchQuery) {
if ((searchQuery.getHighlightFields() != null && searchQuery.getHighlightFields().length > 0)
|| searchQuery.getHighlightBuilder() != null) {
@ -868,9 +865,8 @@ class RequestFactory {
if (!query.getRuntimeFields().isEmpty()) {
Map<String, Object> runtimeMappings = new HashMap<>();
query.getRuntimeFields().forEach(runtimeField -> {
runtimeMappings.put(runtimeField.getName(), runtimeField.getMapping());
});
query.getRuntimeFields()
.forEach(runtimeField -> runtimeMappings.put(runtimeField.getName(), runtimeField.getMapping()));
sourceBuilder.runtimeMappings(runtimeMappings);
}
@ -925,8 +921,7 @@ class RequestFactory {
query.getSort().forEach(order -> sourceBuilder.sort(getSortBuilder(order, entity)));
}
if (query instanceof NativeSearchQuery) {
NativeSearchQuery nativeSearchQuery = (NativeSearchQuery) query;
if (query instanceof NativeSearchQuery nativeSearchQuery) {
List<SortBuilder<?>> sorts = nativeSearchQuery.getElasticsearchSorts();
if (sorts != null) {
sorts.forEach(sourceBuilder::sort);
@ -940,8 +935,7 @@ class RequestFactory {
Order.Mode mode = Order.DEFAULT_MODE;
String unmappedType = null;
if (order instanceof Order) {
Order o = (Order) order;
if (order instanceof Order o) {
mode = o.getMode();
unmappedType = o.getUnmappedType();
}
@ -956,8 +950,7 @@ class RequestFactory {
: null;
String fieldName = property != null ? property.getFieldName() : order.getProperty();
if (order instanceof GeoDistanceOrder) {
GeoDistanceOrder geoDistanceOrder = (GeoDistanceOrder) order;
if (order instanceof GeoDistanceOrder geoDistanceOrder) {
GeoDistanceSortBuilder sort = SortBuilders.geoDistanceSort(fieldName, geoDistanceOrder.getGeoPoint().getLat(),
geoDistanceOrder.getGeoPoint().getLon());
@ -1171,14 +1164,11 @@ class RequestFactory {
private QueryBuilder getQuery(Query query) {
QueryBuilder elasticsearchQuery;
if (query instanceof NativeSearchQuery) {
NativeSearchQuery searchQuery = (NativeSearchQuery) query;
if (query instanceof NativeSearchQuery searchQuery) {
elasticsearchQuery = searchQuery.getQuery();
} else if (query instanceof CriteriaQuery) {
CriteriaQuery criteriaQuery = (CriteriaQuery) query;
} else if (query instanceof CriteriaQuery criteriaQuery) {
elasticsearchQuery = new CriteriaQueryProcessor().createQuery(criteriaQuery.getCriteria());
} else if (query instanceof StringQuery) {
StringQuery stringQuery = (StringQuery) query;
} else if (query instanceof StringQuery stringQuery) {
elasticsearchQuery = wrapperQuery(stringQuery.getSource());
} else {
throw new IllegalArgumentException("unhandled Query implementation " + query.getClass().getName());
@ -1191,11 +1181,9 @@ class RequestFactory {
private QueryBuilder getFilter(Query query) {
QueryBuilder elasticsearchFilter;
if (query instanceof NativeSearchQuery) {
NativeSearchQuery searchQuery = (NativeSearchQuery) query;
if (query instanceof NativeSearchQuery searchQuery) {
elasticsearchFilter = searchQuery.getFilter();
} else if (query instanceof CriteriaQuery) {
CriteriaQuery criteriaQuery = (CriteriaQuery) query;
} else if (query instanceof CriteriaQuery criteriaQuery) {
elasticsearchFilter = new CriteriaFilterProcessor().createFilter(criteriaQuery.getCriteria());
} else if (query instanceof StringQuery) {
elasticsearchFilter = null;
@ -1207,15 +1195,11 @@ class RequestFactory {
}
public static WriteRequest.RefreshPolicy toElasticsearchRefreshPolicy(RefreshPolicy refreshPolicy) {
switch (refreshPolicy) {
case IMMEDIATE:
return WriteRequest.RefreshPolicy.IMMEDIATE;
case WAIT_UNTIL:
return WriteRequest.RefreshPolicy.WAIT_UNTIL;
case NONE:
default:
return WriteRequest.RefreshPolicy.NONE;
}
return switch (refreshPolicy) {
case IMMEDIATE -> WriteRequest.RefreshPolicy.IMMEDIATE;
case WAIT_UNTIL -> WriteRequest.RefreshPolicy.WAIT_UNTIL;
case NONE -> WriteRequest.RefreshPolicy.NONE;
};
}
@Nullable

View File

@ -128,8 +128,7 @@ public final class RestClients {
for (ClientConfiguration.ClientConfigurationCallback<?> clientConfigurer : clientConfiguration
.getClientConfigurers()) {
if (clientConfigurer instanceof RestClientConfigurationCallback) {
RestClientConfigurationCallback restClientConfigurationCallback = (RestClientConfigurationCallback) clientConfigurer;
if (clientConfigurer instanceof RestClientConfigurationCallback restClientConfigurationCallback) {
clientBuilder = restClientConfigurationCallback.configure(clientBuilder);
}
}
@ -199,9 +198,9 @@ public final class RestClients {
context.setAttribute(RestClients.LOG_ID_ATTRIBUTE, logId);
}
if (request instanceof HttpEntityEnclosingRequest && ((HttpEntityEnclosingRequest) request).getEntity() != null) {
if (request instanceof HttpEntityEnclosingRequest entityRequest
&& ((HttpEntityEnclosingRequest) request).getEntity() != null) {
HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
entity.writeTo(buffer);

View File

@ -129,8 +129,7 @@ public class SearchDocumentResponseBuilder {
for (org.elasticsearch.search.suggest.Suggest.Suggestion<? extends org.elasticsearch.search.suggest.Suggest.Suggestion.Entry<? extends org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option>> suggestionES : suggestES) {
if (suggestionES instanceof org.elasticsearch.search.suggest.term.TermSuggestion) {
org.elasticsearch.search.suggest.term.TermSuggestion termSuggestionES = (org.elasticsearch.search.suggest.term.TermSuggestion) suggestionES;
if (suggestionES instanceof org.elasticsearch.search.suggest.term.TermSuggestion termSuggestionES) {
List<TermSuggestion.Entry> entries = new ArrayList<>();
for (org.elasticsearch.search.suggest.term.TermSuggestion.Entry entryES : termSuggestionES) {
@ -150,8 +149,7 @@ public class SearchDocumentResponseBuilder {
suggestFrom(termSuggestionES.getSort())));
}
if (suggestionES instanceof org.elasticsearch.search.suggest.phrase.PhraseSuggestion) {
org.elasticsearch.search.suggest.phrase.PhraseSuggestion phraseSuggestionES = (org.elasticsearch.search.suggest.phrase.PhraseSuggestion) suggestionES;
if (suggestionES instanceof org.elasticsearch.search.suggest.phrase.PhraseSuggestion phraseSuggestionES) {
List<PhraseSuggestion.Entry> entries = new ArrayList<>();
for (org.elasticsearch.search.suggest.phrase.PhraseSuggestion.Entry entryES : phraseSuggestionES) {
@ -169,8 +167,7 @@ public class SearchDocumentResponseBuilder {
suggestions.add(new PhraseSuggestion(phraseSuggestionES.getName(), phraseSuggestionES.getSize(), entries));
}
if (suggestionES instanceof org.elasticsearch.search.suggest.completion.CompletionSuggestion) {
org.elasticsearch.search.suggest.completion.CompletionSuggestion completionSuggestionES = (org.elasticsearch.search.suggest.completion.CompletionSuggestion) suggestionES;
if (suggestionES instanceof org.elasticsearch.search.suggest.completion.CompletionSuggestion completionSuggestionES) {
List<CompletionSuggestion.Entry<T>> entries = new ArrayList<>();
for (org.elasticsearch.search.suggest.completion.CompletionSuggestion.Entry entryES : completionSuggestionES) {

View File

@ -235,8 +235,7 @@ public interface WebClientProvider {
for (ClientConfiguration.ClientConfigurationCallback<?> clientConfigurer : clientConfiguration
.getClientConfigurers()) {
if (clientConfigurer instanceof ReactiveRestClients.WebClientConfigurationCallback) {
ReactiveRestClients.WebClientConfigurationCallback webClientConfigurationCallback = (ReactiveRestClients.WebClientConfigurationCallback) clientConfigurer;
if (clientConfigurer instanceof ReactiveRestClients.WebClientConfigurationCallback webClientConfigurationCallback) {
webClient = webClientConfigurationCallback.configure(webClient);
}
}

View File

@ -15,8 +15,6 @@
*/
package org.springframework.data.elasticsearch.client.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@ -52,7 +50,7 @@ public class ScrollState {
public List<String> getScrollIds() {
synchronized (lock) {
return Collections.unmodifiableList(new ArrayList<>(pastIds));
return List.copyOf(pastIds);
}
}

View File

@ -598,8 +598,7 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
protected void maybeCallbackBeforeConvertWithQuery(Object query, IndexCoordinates index) {
if (query instanceof IndexQuery) {
IndexQuery indexQuery = (IndexQuery) query;
if (query instanceof IndexQuery indexQuery) {
Object queryObject = indexQuery.getObject();
if (queryObject != null) {
@ -640,8 +639,7 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
protected void maybeCallbackAfterSaveWithQuery(Object query, IndexCoordinates index) {
if (query instanceof IndexQuery) {
IndexQuery indexQuery = (IndexQuery) query;
if (query instanceof IndexQuery indexQuery) {
Object queryObject = indexQuery.getObject();
if (queryObject != null) {
@ -683,8 +681,7 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
for (int i = 0; i < queries.size(); i++) {
Object query = queries.get(i);
if (query instanceof IndexQuery) {
IndexQuery indexQuery = (IndexQuery) query;
if (query instanceof IndexQuery indexQuery) {
Object queryObject = indexQuery.getObject();
if (queryObject != null) {

View File

@ -173,9 +173,8 @@ abstract public class AbstractReactiveElasticsearchTemplate
return getVendor() //
.zipWith(getRuntimeLibraryVersion()) //
.zipWith(getClusterVersion()) //
.doOnNext(objects -> {
VersionInfo.logVersions(objects.getT1().getT1(), objects.getT1().getT2(), objects.getT2());
}).then();
.doOnNext(objects -> VersionInfo.logVersions(objects.getT1().getT1(), objects.getT1().getT2(), objects.getT2()))
.then();
}
// endregion
@ -228,8 +227,8 @@ abstract public class AbstractReactiveElasticsearchTemplate
SeqNoPrimaryTerm seqNoPrimaryTerm = entity.getSeqNoPrimaryTerm();
if (seqNoPrimaryTerm != null) {
query.setSeqNo(seqNoPrimaryTerm.getSequenceNumber());
query.setPrimaryTerm(seqNoPrimaryTerm.getPrimaryTerm());
query.setSeqNo(seqNoPrimaryTerm.sequenceNumber());
query.setPrimaryTerm(seqNoPrimaryTerm.primaryTerm());
usingSeqNo = true;
}
}
@ -316,10 +315,10 @@ abstract public class AbstractReactiveElasticsearchTemplate
T savedEntity = it.getT1();
IndexResponseMetaData indexResponseMetaData = it.getT2();
return updateIndexedObject(savedEntity, IndexedObjectInformation.of( //
indexResponseMetaData.getId(), //
indexResponseMetaData.getSeqNo(), //
indexResponseMetaData.getPrimaryTerm(), //
indexResponseMetaData.getVersion()));
indexResponseMetaData.id(), //
indexResponseMetaData.seqNo(), //
indexResponseMetaData.primaryTerm(), //
indexResponseMetaData.version()));
}).flatMap(saved -> maybeCallAfterSave(saved, index));
}
@ -624,34 +623,7 @@ abstract public class AbstractReactiveElasticsearchTemplate
/**
* Value class to capture client independent information from a response to an index request.
*/
public static class IndexResponseMetaData {
private final String id;
private final long seqNo;
private final long primaryTerm;
private final long version;
public IndexResponseMetaData(String id, long seqNo, long primaryTerm, long version) {
this.id = id;
this.seqNo = seqNo;
this.primaryTerm = primaryTerm;
this.version = version;
}
public String getId() {
return id;
}
public long getSeqNo() {
return seqNo;
}
public long getPrimaryTerm() {
return primaryTerm;
}
public long getVersion() {
return version;
}
public record IndexResponseMetaData(String id, long seqNo, long primaryTerm, long version) {
}
// endregion
@ -670,7 +642,8 @@ abstract public class AbstractReactiveElasticsearchTemplate
}
public List<IndexQuery> indexQueries() {
return entities.stream().map(value -> getIndexQuery(value)).collect(Collectors.toList());
return entities.stream().map(AbstractReactiveElasticsearchTemplate.this::getIndexQuery)
.collect(Collectors.toList());
}
public T entityAt(long index) {

View File

@ -20,7 +20,7 @@ package org.springframework.data.elasticsearch.core;
*
* @author Peter-Josef Meisch
*/
public class ActiveShardCount {
public record ActiveShardCount(int value) {
private static final int ACTIVE_SHARD_COUNT_DEFAULT = -2;
private static final int ALL_ACTIVE_SHARDS = -1;
@ -28,14 +28,4 @@ public class ActiveShardCount {
public static final ActiveShardCount ALL = new ActiveShardCount(ALL_ACTIVE_SHARDS);
public static final ActiveShardCount NONE = new ActiveShardCount(0);
public static final ActiveShardCount ONE = new ActiveShardCount(1);
private final int value;
public ActiveShardCount(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}

View File

@ -191,12 +191,10 @@ public class Range<T> {
return true;
}
if (!(o instanceof Range)) {
if (!(o instanceof Range<?> range)) {
return false;
}
Range<?> range = (Range<?>) o;
if (!ObjectUtils.nullSafeEquals(lowerBound, range.lowerBound)) {
return false;
}
@ -375,12 +373,10 @@ public class Range<T> {
return true;
}
if (!(o instanceof Bound)) {
if (!(o instanceof Bound<?> bound)) {
return false;
}
Bound<?> bound = (Bound<?>) o;
if (inclusive != bound.inclusive)
return false;

View File

@ -125,7 +125,7 @@ public class SearchHitMapping<T> {
Assert.notNull(searchDocument, "searchDocument is null");
Assert.notNull(content, "content is null");
return new SearchHit<T>(searchDocument.getIndex(), //
return new SearchHit<>(searchDocument.getIndex(), //
searchDocument.hasId() ? searchDocument.getId() : null, //
searchDocument.getRouting(), //
searchDocument.getScore(), //
@ -210,7 +210,7 @@ public class SearchHitMapping<T> {
SearchDocument searchDocument = searchHit.getContent();
Object targetObject = converter.read(targetType, searchDocument);
convertedSearchHits.add(new SearchHit<Object>(searchDocument.getIndex(), //
convertedSearchHits.add(new SearchHit<>(searchDocument.getIndex(), //
searchDocument.getId(), //
searchDocument.getRouting(), //
searchDocument.getScore(), //

View File

@ -67,8 +67,7 @@ public final class SearchHitSupport {
return ((Stream<?>) result).map(SearchHitSupport::unwrapSearchHits);
}
if (result instanceof SearchHits<?>) {
SearchHits<?> searchHits = (SearchHits<?>) result;
if (result instanceof SearchHits<?> searchHits) {
return unwrapSearchHits(searchHits.getSearchHits());
}
@ -76,16 +75,14 @@ public final class SearchHitSupport {
return unwrapSearchHitsIterator((SearchHitsIterator<?>) result);
}
if (result instanceof SearchPage<?>) {
SearchPage<?> searchPage = (SearchPage<?>) result;
if (result instanceof SearchPage<?> searchPage) {
List<?> content = (List<?>) SearchHitSupport.unwrapSearchHits(searchPage.getSearchHits());
return new PageImpl<>(content, searchPage.getPageable(), searchPage.getTotalElements());
}
if (ReactiveWrappers.isAvailable(ReactiveWrappers.ReactiveLibrary.PROJECT_REACTOR)) {
if (result instanceof Flux) {
Flux<?> flux = (Flux<?>) result;
if (result instanceof Flux<?> flux) {
return flux.map(SearchHitSupport::unwrapSearchHits);
}
}
@ -95,7 +92,7 @@ public final class SearchHitSupport {
private static CloseableIterator<?> unwrapSearchHitsIterator(SearchHitsIterator<?> iterator) {
return new CloseableIterator<Object>() {
return new CloseableIterator<>() {
@Override
public boolean hasNext() {
return iterator.hasNext();

View File

@ -59,7 +59,7 @@ abstract class StreamQueries {
long totalHits = searchHits.getTotalHits();
TotalHitsRelation totalHitsRelation = searchHits.getTotalHitsRelation();
return new SearchHitsIterator<T>() {
return new SearchHitsIterator<>() {
private volatile AtomicInteger currentCount = new AtomicInteger();
private volatile Iterator<SearchHit<T>> currentScrollHits = searchHits.iterator();

View File

@ -87,8 +87,7 @@ final public class ElasticsearchDateConverter {
Assert.notNull(accessor, "accessor must not be null");
if (accessor instanceof Instant) {
Instant instant = (Instant) accessor;
if (accessor instanceof Instant instant) {
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC"));
return dateFormatter.format(zonedDateTime);
}

View File

@ -171,24 +171,16 @@ public class GeoConverters {
String type = GeoConverters.getGeoJsonType(source);
switch (type) {
case "point":
return MapToGeoJsonPointConverter.INSTANCE.convert(source);
case "multipoint":
return MapToGeoJsonMultiPointConverter.INSTANCE.convert(source);
case "linestring":
return MapToGeoJsonLineStringConverter.INSTANCE.convert(source);
case "multilinestring":
return MapToGeoJsonMultiLineStringConverter.INSTANCE.convert(source);
case "polygon":
return MapToGeoJsonPolygonConverter.INSTANCE.convert(source);
case "multipolygon":
return MapToGeoJsonMultiPolygonConverter.INSTANCE.convert(source);
case "geometrycollection":
return MapToGeoJsonGeometryCollectionConverter.INSTANCE.convert(source);
default:
throw new IllegalArgumentException("unknown GeoJson type " + type);
}
return switch (type) {
case "point" -> MapToGeoJsonPointConverter.INSTANCE.convert(source);
case "multipoint" -> MapToGeoJsonMultiPointConverter.INSTANCE.convert(source);
case "linestring" -> MapToGeoJsonLineStringConverter.INSTANCE.convert(source);
case "multilinestring" -> MapToGeoJsonMultiLineStringConverter.INSTANCE.convert(source);
case "polygon" -> MapToGeoJsonPolygonConverter.INSTANCE.convert(source);
case "multipolygon" -> MapToGeoJsonMultiPolygonConverter.INSTANCE.convert(source);
case "geometrycollection" -> MapToGeoJsonGeometryCollectionConverter.INSTANCE.convert(source);
default -> throw new IllegalArgumentException("unknown GeoJson type " + type);
};
}
}
// endregion

View File

@ -335,8 +335,7 @@ public class MappingElasticsearchConverter
ElasticsearchPropertyValueProvider valueProvider = new ElasticsearchPropertyValueProvider(accessor, evaluator);
R result = readProperties(targetEntity, instance, valueProvider);
if (source instanceof Document) {
Document document = (Document) source;
if (source instanceof Document document) {
if (document.hasId()) {
ElasticsearchPersistentProperty idProperty = targetEntity.getIdProperty();
PersistentPropertyAccessor<R> propertyAccessor = new ConvertingPropertyAccessor<>(
@ -368,8 +367,7 @@ public class MappingElasticsearchConverter
}
}
if (source instanceof SearchDocument) {
SearchDocument searchDocument = (SearchDocument) source;
if (source instanceof SearchDocument searchDocument) {
populateScriptFields(targetEntity, result, searchDocument);
}
@ -1321,10 +1319,9 @@ public class MappingElasticsearchConverter
String fieldName = property.getFieldName();
if (target instanceof Document) {
if (target instanceof Document document) {
// nested objects may have properties like 'id' which are recognized as isIdProperty() but they are not
// Documents
Document document = (Document) target;
if (property.isIdProperty() && document.hasId()) {
Object id = null;

View File

@ -258,10 +258,9 @@ public class SearchDocumentAdapter implements SearchDocument {
if (this == o) {
return true;
}
if (!(o instanceof SearchDocumentAdapter)) {
if (!(o instanceof SearchDocumentAdapter that)) {
return false;
}
SearchDocumentAdapter that = (SearchDocumentAdapter) o;
return Float.compare(that.score, score) == 0 && delegate.equals(that.delegate);
}

View File

@ -33,7 +33,7 @@ public class GeoJsonMultiPolygon implements GeoJson<Iterable<GeoJsonPolygon>> {
public static final String TYPE = "MultiPolygon";
private List<GeoJsonPolygon> coordinates = new ArrayList<GeoJsonPolygon>();
private List<GeoJsonPolygon> coordinates = new ArrayList<>();
private GeoJsonMultiPolygon(List<GeoJsonPolygon> polygons) {
this.coordinates.addAll(polygons);

View File

@ -596,7 +596,7 @@ public class MappingBuilder {
}
}
private boolean isAnyPropertyAnnotatedWithField(@Nullable ElasticsearchPersistentEntity entity) {
private boolean isAnyPropertyAnnotatedWithField(@Nullable ElasticsearchPersistentEntity<?> entity) {
return entity != null && entity.getPersistentProperty(Field.class) != null;
}

View File

@ -318,19 +318,11 @@ public final class MappingParameters {
if (StringUtils.hasLength(nullValue)) {
switch (nullValueType) {
case Integer:
objectNode.put(FIELD_PARAM_NULL_VALUE, Integer.valueOf(nullValue));
break;
case Long:
objectNode.put(FIELD_PARAM_NULL_VALUE, Long.valueOf(nullValue));
break;
case Double:
objectNode.put(FIELD_PARAM_NULL_VALUE, Double.valueOf(nullValue));
break;
case String:
default:
objectNode.put(FIELD_PARAM_NULL_VALUE, nullValue);
break;
case Integer -> objectNode.put(FIELD_PARAM_NULL_VALUE, Integer.valueOf(nullValue));
case Long -> objectNode.put(FIELD_PARAM_NULL_VALUE, Long.valueOf(nullValue));
case Double -> objectNode.put(FIELD_PARAM_NULL_VALUE, Double.valueOf(nullValue));
case String -> objectNode.put(FIELD_PARAM_NULL_VALUE, nullValue);
default -> objectNode.put(FIELD_PARAM_NULL_VALUE, nullValue);
}
}

View File

@ -114,8 +114,7 @@ public class Settings extends DefaultStringObjectMap<Settings> {
*/
static private Stream<Map.Entry<String, Object>> doFlatten(Map.Entry<String, Object> entry) {
if (entry.getValue() instanceof Map<?, ?>) {
Map<?, ?> nested = (Map<?, ?>) entry.getValue();
if (entry.getValue()instanceof Map<?, ?> nested) {
// noinspection unchecked
return nested.entrySet().stream() //

View File

@ -86,7 +86,7 @@ public class TemplateData {
private TemplateDataBuilder() {}
public TemplateDataBuilder withIndexPatterns(String[] indexPatterns) {
public TemplateDataBuilder withIndexPatterns(String... indexPatterns) {
this.indexPatterns = indexPatterns;
return this;
}

View File

@ -68,10 +68,9 @@ public class JoinField<ID> {
if (this == obj) {
return true;
}
if (!(obj instanceof JoinField)) {
if (!(obj instanceof JoinField<?> other)) {
return false;
}
JoinField other = (JoinField) obj;
return Objects.equals(name, other.name) && Objects.equals(parent, other.parent);
}
}

View File

@ -15,8 +15,6 @@
*/
package org.springframework.data.elasticsearch.core.mapping;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@ -35,15 +33,9 @@ public class ElasticsearchSimpleTypes {
static final Set<Class<?>> AUTOGENERATED_ID_TYPES;
static {
Set<Class<?>> classes = new HashSet<>();
classes.add(String.class);
AUTOGENERATED_ID_TYPES = Collections.unmodifiableSet(classes);
AUTOGENERATED_ID_TYPES = Set.of(String.class);
Set<Class<?>> simpleTypes = new HashSet<>();
simpleTypes.add(Document.class);
simpleTypes.add(Map.class);
ELASTICSEARCH_SIMPLE_TYPES = Collections.unmodifiableSet(simpleTypes);
ELASTICSEARCH_SIMPLE_TYPES = Set.of(Document.class, Map.class);
}
private static final Set<Class<?>> ELASTICSEARCH_SIMPLE_TYPES;

View File

@ -39,7 +39,7 @@ public class IndexCoordinates {
return new IndexCoordinates(indexNames);
}
private IndexCoordinates(String[] indexNames) {
private IndexCoordinates(String... indexNames) {
Assert.notEmpty(indexNames, "indexNames may not be null or empty");
this.indexNames = indexNames;
}

View File

@ -261,16 +261,10 @@ public class SimpleElasticsearchPersistentProperty extends
// register converters for built-in formats
for (DateFormat dateFormat : dateFormats) {
switch (dateFormat) {
case weekyear:
case weekyear_week:
case weekyear_week_day:
LOGGER.warn(String.format(
case weekyear, weekyear_week, weekyear_week_day -> LOGGER.warn(String.format(
"No default converter available for '%s' and date format '%s'. Use a custom converter instead.",
actualType.getName(), dateFormat.name()));
break;
default:
converters.add(ElasticsearchDateConverter.of(dateFormat));
break;
default -> converters.add(ElasticsearchDateConverter.of(dateFormat));
}
}

View File

@ -71,8 +71,8 @@ public class IndexQueryBuilder {
}
public IndexQueryBuilder withSeqNoPrimaryTerm(SeqNoPrimaryTerm seqNoPrimaryTerm) {
this.seqNo = seqNoPrimaryTerm.getSequenceNumber();
this.primaryTerm = seqNoPrimaryTerm.getPrimaryTerm();
this.seqNo = seqNoPrimaryTerm.sequenceNumber();
this.primaryTerm = seqNoPrimaryTerm.primaryTerm();
return this;
}

View File

@ -451,25 +451,13 @@ public interface Query {
*
* @since 4.3
*/
final class IdWithRouting {
private final String id;
@Nullable private final String routing;
public IdWithRouting(String id, @Nullable String routing) {
record IdWithRouting(String id, @Nullable String routing) {
public IdWithRouting {
Assert.notNull(id, "id must not be null");
this.id = id;
this.routing = routing;
}
public String getId() {
return id;
}
@Nullable
public String getRouting() {
return routing;
}
}
}

View File

@ -26,45 +26,6 @@ import org.springframework.lang.Nullable;
* @author Peter-Josef Meisch
* @since 4.4
*/
public final class ScriptData {
@Nullable private final ScriptType type;
@Nullable private final String language;
@Nullable private final String script;
@Nullable private final String scriptName;
@Nullable private final Map<String, Object> params;
public ScriptData(@Nullable ScriptType type, @Nullable String language, @Nullable String script,
public record ScriptData(@Nullable ScriptType type, @Nullable String language, @Nullable String script,
@Nullable String scriptName, @Nullable Map<String, Object> params) {
this.type = type;
this.language = language;
this.script = script;
this.scriptName = scriptName;
this.params = params;
}
@Nullable
public ScriptType getType() {
return type;
}
@Nullable
public String getLanguage() {
return language;
}
@Nullable
public String getScript() {
return script;
}
@Nullable
public String getScriptName() {
return scriptName;
}
@Nullable
public Map<String, Object> getParams() {
return params;
}
}

View File

@ -15,8 +15,6 @@
*/
package org.springframework.data.elasticsearch.core.query;
import java.util.Objects;
/**
* <p>
* A container for seq_no and primary_term values. When an entity class contains a field of this type, it will be
@ -42,10 +40,7 @@ import java.util.Objects;
* @author Roman Puchkovskiy
* @since 4.0
*/
public final class SeqNoPrimaryTerm {
private final long sequenceNumber;
private final long primaryTerm;
public record SeqNoPrimaryTerm(long sequenceNumber, long primaryTerm) {
/**
* Creates an instance of SeqNoPrimaryTerm with the given seq_no and primary_term. The passed values are validated:
* sequenceNumber must be non-negative, primaryTerm must be positive. If validation fails, an IllegalArgumentException
@ -55,7 +50,7 @@ public final class SeqNoPrimaryTerm {
* @param primaryTerm primary_term, must be positive
* @throws IllegalArgumentException if seq_no or primary_term is not valid
*/
public SeqNoPrimaryTerm(long sequenceNumber, long primaryTerm) {
public SeqNoPrimaryTerm {
if (sequenceNumber < 0) {
throw new IllegalArgumentException("seq_no should not be negative, but it's " + sequenceNumber);
}
@ -63,37 +58,10 @@ public final class SeqNoPrimaryTerm {
throw new IllegalArgumentException("primary_term should be positive, but it's " + primaryTerm);
}
this.sequenceNumber = sequenceNumber;
this.primaryTerm = primaryTerm;
}
public long getSequenceNumber() {
return sequenceNumber;
}
public long getPrimaryTerm() {
return primaryTerm;
}
@Override
public String toString() {
return "SeqNoPrimaryTerm{" + "sequenceNumber=" + sequenceNumber + ", primaryTerm=" + primaryTerm + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SeqNoPrimaryTerm that = (SeqNoPrimaryTerm) o;
return sequenceNumber == that.sequenceNumber && primaryTerm == that.primaryTerm;
}
@Override
public int hashCode() {
return Objects.hash(sequenceNumber, primaryTerm);
}
}

View File

@ -119,12 +119,12 @@ public class UpdateQuery {
@Nullable
public String getScript() {
return scriptData != null ? scriptData.getScript() : null;
return scriptData != null ? scriptData.script() : null;
}
@Nullable
public Map<String, Object> getParams() {
return scriptData != null ? scriptData.getParams() : null;
return scriptData != null ? scriptData.params() : null;
}
@Nullable
@ -139,7 +139,7 @@ public class UpdateQuery {
@Nullable
public String getLang() {
return scriptData != null ? scriptData.getLanguage() : null;
return scriptData != null ? scriptData.language() : null;
}
@Nullable
@ -249,12 +249,12 @@ public class UpdateQuery {
@Nullable
public ScriptType getScriptType() {
return scriptData != null ? scriptData.getType() : null;
return scriptData != null ? scriptData.type() : null;
}
@Nullable
public String getScriptName() {
return scriptData != null ? scriptData.getScriptName() : null;
return scriptData != null ? scriptData.scriptName() : null;
}
/**

View File

@ -194,12 +194,12 @@ public abstract class HighlightCommonParameters {
return (SELF) this;
}
public SELF withPreTags(String[] preTags) {
public SELF withPreTags(String... preTags) {
this.preTags = preTags;
return (SELF) this;
}
public SELF withPostTags(String[] postTags) {
public SELF withPostTags(String... postTags) {
this.postTags = postTags;
return (SELF) this;
}

View File

@ -51,7 +51,7 @@ public class HighlightFieldParameters extends HighlightCommonParameters {
return this;
}
public HighlightFieldParametersBuilder withMatchedFields(String[] matchedFields) {
public HighlightFieldParametersBuilder withMatchedFields(String... matchedFields) {
this.matchedFields = matchedFields;
return this;
}

View File

@ -29,10 +29,10 @@ import org.springframework.lang.Nullable;
*/
public class DefaultRoutingResolver implements RoutingResolver {
private final MappingContext<? extends ElasticsearchPersistentEntity, ? extends ElasticsearchPersistentProperty> mappingContext;
private final MappingContext<? extends ElasticsearchPersistentEntity<?>, ? extends ElasticsearchPersistentProperty> mappingContext;
public DefaultRoutingResolver(
MappingContext<? extends ElasticsearchPersistentEntity, ? extends ElasticsearchPersistentProperty> mappingContext) {
MappingContext<? extends ElasticsearchPersistentEntity<?>, ? extends ElasticsearchPersistentProperty> mappingContext) {
this.mappingContext = mappingContext;
}

View File

@ -27,7 +27,6 @@ import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersiste
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.ByQueryResponse;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.elasticsearch.core.query.SourceFilter;
import org.springframework.data.elasticsearch.repository.query.ReactiveElasticsearchQueryExecution.ResultProcessingConverter;
import org.springframework.data.elasticsearch.repository.query.ReactiveElasticsearchQueryExecution.ResultProcessingExecution;
import org.springframework.data.mapping.context.MappingContext;
@ -133,8 +132,7 @@ abstract class AbstractReactiveElasticsearchRepositoryQuery implements Repositor
return (query, type, targetType, indexCoordinates) -> operations.search(query.setPageable(accessor.getPageable()),
type, targetType, indexCoordinates);
} else {
return (query, type, targetType, indexCoordinates) -> operations.search(query, type, targetType,
indexCoordinates);
return operations::search;
}
}

View File

@ -35,7 +35,7 @@ class ElasticsearchParametersParameterAccessor extends ParametersParameterAccess
* @param method must not be {@literal null}.
* @param values must not be {@literal null}.
*/
ElasticsearchParametersParameterAccessor(ElasticsearchQueryMethod method, Object[] values) {
ElasticsearchParametersParameterAccessor(ElasticsearchQueryMethod method, Object... values) {
super(method.getParameters(), values);
this.values = Arrays.asList(values);

View File

@ -38,7 +38,7 @@ class ReactiveElasticsearchParametersParameterAccessor extends ElasticsearchPara
* @param method must not be {@literal null}.
* @param values must not be {@literal null}.
*/
ReactiveElasticsearchParametersParameterAccessor(ReactiveElasticsearchQueryMethod method, Object[] values) {
ReactiveElasticsearchParametersParameterAccessor(ReactiveElasticsearchQueryMethod method, Object... values) {
super(method, values);
this.subscriptions = new ArrayList<>(values.length);

View File

@ -308,7 +308,7 @@ public class SimpleElasticsearchRepository<T, ID> implements ElasticsearchReposi
Assert.notNull(ids, "ids can't be null.");
return StreamUtils.createStreamFromIterator(ids.iterator()).map(id -> stringIdRepresentation(id))
return StreamUtils.createStreamFromIterator(ids.iterator()).map(this::stringIdRepresentation)
.collect(Collectors.toList());
}

View File

@ -204,7 +204,7 @@ public class SimpleReactiveElasticsearchRepository<T, ID> implements ReactiveEla
return Flux.fromIterable(ids) //
.map(this::convertId) //
.collectList() //
.map(idList -> operations.idsQuery(idList)) //
.map(operations::idsQuery) //
.flatMap(
query -> operations.delete(query, entityInformation.getJavaType(), entityInformation.getIndexCoordinates())) //
.then(doRefresh());
@ -225,7 +225,7 @@ public class SimpleReactiveElasticsearchRepository<T, ID> implements ReactiveEla
.map(entityInformation::getRequiredId) //
.map(this::convertId) //
.collectList() //
.map(idList -> operations.idsQuery(idList))
.map(operations::idsQuery)
.flatMap(
query -> operations.delete(query, entityInformation.getJavaType(), entityInformation.getIndexCoordinates())) //
.then(doRefresh());

View File

@ -21,29 +21,5 @@ import org.springframework.lang.Nullable;
* @author Peter-Josef Meisch
* @since 4.3
*/
public class ScoreDoc {
private final double score;
@Nullable private final Integer doc;
@Nullable private final Integer shardIndex;
public ScoreDoc(double score, @Nullable Integer doc, @Nullable Integer shardIndex) {
this.score = score;
this.doc = doc;
this.shardIndex = shardIndex;
}
public double getScore() {
return score;
}
@Nullable
public Integer getDoc() {
return doc;
}
@Nullable
public Integer getShardIndex() {
return shardIndex;
}
public record ScoreDoc(double score, @Nullable Integer doc, @Nullable Integer shardIndex) {
}

View File

@ -26,28 +26,17 @@ import org.springframework.util.Assert;
* @author Peter-Josef Meisch
* @since 4.3
*/
public class Version {
public record Version(int major, int minor, int revision) {
private static final Pattern PATTERN = Pattern.compile("^(\\d+)(\\.(\\d+))?(\\.(\\d+))?.*$");
private final int major;
private final int minor;
private final int revision;
public Version(int major, int minor, int revision) {
this.major = major;
this.minor = minor;
this.revision = revision;
}
@Override
public String toString() {
return "" + major + "." + minor + "." + revision;
return major + "." + minor + '.' + revision;
}
/**
* Creates a version from a String that matches {@link #PATTERN}; major, minor and revision numbers separated by dots
* with optional trailing characters. A missing revision is treated as 0.
* Creates a version from a String that matches {@link #PATTERN}; major, minor and revision numbers separated by dots with optional trailing characters. A missing revision is treated as 0.
*
* @param s the String to parse
* @return the Version
@ -69,16 +58,4 @@ public class Version {
return new Version(major, minor, revision);
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getRevision() {
return revision;
}
}

View File

@ -110,7 +110,7 @@ public final class VersionInfo {
}
private static boolean differInMajorOrMinor(Version version1, Version version2) {
return version1.getMajor() != version2.getMajor() || version1.getMinor() != version2.getMinor();
return version1.major() != version2.major() || version1.minor() != version2.minor();
}
private VersionInfo() {}

View File

@ -162,7 +162,7 @@ public abstract class NestedObjectIntegrationTests {
assertThat(mapping).isNotNull();
Map<String, Object> propertyMap = (Map<String, Object>) mapping.get("properties");
assertThat(propertyMap).isNotNull();
Map bestCarsAttributes = (Map) propertyMap.get("bestCars");
Map<String, Object> bestCarsAttributes = (Map<String, Object>) propertyMap.get("bestCars");
assertThat(bestCarsAttributes.get("include_in_parent")).isNotNull();
}

View File

@ -32,13 +32,13 @@ import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AliasFor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.index.MappingBuilder;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.lang.Nullable;
/**
@ -78,38 +78,40 @@ public class ComposableAnnotationsUnitTest {
@DisplayName("should use composed Field annotations in MappingBuilder")
void shouldUseComposedFieldAnnotationsInMappingBuilder() throws JSONException {
String expected = "{\n" + //
" \"properties\": {\n" + //
" \"_class\": {\n" + //
" \"type\": \"keyword\",\n" + //
" \"index\": false,\n" + //
" \"doc_values\": false\n" + //
" },\n" + //
" \"null-value\": {\n" + //
" \"null_value\": \"NULL\"\n" + //
" },\n" + //
" \"theDate\": {\n" + //
" \"type\": \"date\",\n" + //
" \"format\": \"date\"\n" + //
" },\n" + //
" \"multiField\": {\n" + //
" \"type\": \"text\",\n" + //
" \"fields\": {\n" + //
" \"keyword\": {\n" + //
" \"type\": \"keyword\"\n" + //
" }\n" + //
" }\n" + //
" },\n" + //
" \"suggest\": {\n" + //
" \"type\": \"completion\",\n" + //
" \"max_input_length\": 50,\n" + //
" \"preserve_position_increments\": true,\n" + //
" \"preserve_separators\": true,\n" + //
" \"search_analyzer\": \"myAnalyzer\",\n" + //
" \"analyzer\": \"myAnalyzer\"\n" + //
" }\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"properties": {
"_class": {
"type": "keyword",
"index": false,
"doc_values": false
},
"null-value": {
"null_value": "NULL"
},
"theDate": {
"type": "date",
"format": "date"
},
"multiField": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
},
"suggest": {
"type": "completion",
"max_input_length": 50,
"preserve_position_increments": true,
"preserve_separators": true,
"search_analyzer": "myAnalyzer",
"analyzer": "myAnalyzer"
}
}
}
"""; //
String mapping = mappingBuilder.buildPropertyMapping(ComposedAnnotationEntity.class);

View File

@ -187,20 +187,22 @@ public class RestClientsTest {
String urlPattern = "^/index/_doc/42(\\?.*)?$";
stubFor(put(urlMatching(urlPattern)) //
.willReturn(jsonResponse("{\n" + //
" \"_id\": \"42\",\n" + //
" \"_index\": \"test\",\n" + //
" \"_primary_term\": 1,\n" + //
" \"_seq_no\": 0,\n" + //
" \"_shards\": {\n" + //
" \"failed\": 0,\n" + //
" \"successful\": 1,\n" + //
" \"total\": 2\n" + //
" },\n" + //
" \"_type\": \"_doc\",\n" + //
" \"_version\": 1,\n" + //
" \"result\": \"created\"\n" + //
"}\n" //
.willReturn(jsonResponse("""
{
"_id": "42",
"_index": "test",
"_primary_term": 1,
"_seq_no": 0,
"_shards": {
"failed": 0,
"successful": 1,
"total": 2
},
"_type": "_doc",
"_version": 1,
"result": "created"
}
""" //
, 201) //
.withHeader("Content-Type", "application/vnd.elasticsearch+json;compatible-with=7") //
.withHeader("X-Elastic-Product", "Elasticsearch")));
@ -238,23 +240,24 @@ public class RestClientsTest {
private StubMapping stubForElasticsearchVersionCheck() {
return stubFor(get(urlEqualTo("/")) //
.willReturn(okJson("{\n" + //
" \"cluster_name\": \"docker-cluster\",\n" + //
" \"cluster_uuid\": \"nKasrfHjRo6ge0eBmMUuAQ\",\n" + //
" \"name\": \"c1a6e517d001\",\n" + //
" \"tagline\": \"You Know, for Search\",\n" + //
" \"version\": {\n" + //
" \"build_date\": \"2021-08-26T09:01:05.390870785Z\",\n" + //
" \"build_flavor\": \"default\",\n" + //
" \"build_hash\": \"66b55ebfa59c92c15db3f69a335d500018b3331e\",\n" + //
" \"build_snapshot\": false,\n" + //
" \"build_type\": \"docker\",\n" + //
" \"lucene_version\": \"8.9.0\",\n" + //
" \"minimum_index_compatibility_version\": \"6.0.0-beta1\",\n" + //
" \"minimum_wire_compatibility_version\": \"6.8.0\",\n" + //
" \"number\": \"7.14.1\"\n" + //
" }\n" + //
"}") //
.willReturn(okJson("""
{
"cluster_name": "docker-cluster",
"cluster_uuid": "nKasrfHjRo6ge0eBmMUuAQ",
"name": "c1a6e517d001",
"tagline": "You Know, for Search",
"version": {
"build_date": "2021-08-26T09:01:05.390870785Z",
"build_flavor": "default",
"build_hash": "66b55ebfa59c92c15db3f69a335d500018b3331e",
"build_snapshot": false,
"build_type": "docker",
"lucene_version": "8.9.0",
"minimum_index_compatibility_version": "6.0.0-beta1",
"minimum_wire_compatibility_version": "6.8.0",
"number": "7.14.1"
}
}""") //
.withHeader("Content-Type", "application/json; charset=UTF-8") //
.withHeader("X-Elastic-Product", "Elasticsearch")));
}

View File

@ -18,15 +18,14 @@ package org.springframework.data.elasticsearch.client.elc;
import static org.skyscreamer.jsonassert.JSONAssert.*;
import static org.springframework.data.elasticsearch.client.elc.JsonUtils.*;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import java.time.LocalDate;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.assertj.core.api.SoftAssertions;
import org.json.JSONException;
import org.junit.jupiter.api.BeforeEach;
@ -449,7 +448,6 @@ public class CriteriaQueryMappingUnitTests {
// endregion
// region helper functions
// endregion
// region test entities

View File

@ -20,6 +20,7 @@ import static org.springframework.data.elasticsearch.client.elc.JsonUtils.*;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import org.json.JSONException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@ -396,32 +397,31 @@ class CriteriaQueryProcessorUnitTests {
@DisplayName("should build query for empty property")
void shouldBuildQueryForEmptyProperty() throws JSONException {
String expected = "{\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"exists\" : {\n" + //
" \"field\" : \"lastName\"" + //
" }\n" + //
" }\n" + //
" ],\n" + //
" \"must_not\" : [\n" + //
" {\n" + //
" \"wildcard\" : {\n" + //
" \"lastName\" : {\n" + //
" \"wildcard\" : \"*\"" + //
" }\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}"; //
String expected = """
{
"bool" : {
"must" : [
{
"bool" : {
"must" : [
{
"exists" : {
"field" : "lastName" }
}
],
"must_not" : [
{
"wildcard" : {
"lastName" : {
"wildcard" : "*" }
}
}
]
}
}
]
}
}"""; //
Criteria criteria = new Criteria("lastName").empty();
@ -434,19 +434,21 @@ class CriteriaQueryProcessorUnitTests {
@DisplayName("should build query for non-empty property")
void shouldBuildQueryForNonEmptyProperty() throws JSONException {
String expected = "{\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"wildcard\" : {\n" + //
" \"lastName\" : {\n" + //
" \"wildcard\" : \"*\"\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"bool" : {
"must" : [
{
"wildcard" : {
"lastName" : {
"wildcard" : "*"
}
}
}
]
}
}
"""; //
Criteria criteria = new Criteria("lastName").notEmpty();

View File

@ -267,29 +267,33 @@ public class DevTests {
indicesClient.delete(drb -> drb.index(index));
}
String jsonSettings = "{\n" + //
" \"index\": {\n" + //
" \"number_of_shards\": \"1\",\n" + //
" \"number_of_replicas\": \"0\",\n" + //
" \"analysis\": {\n" + //
" \"analyzer\": {\n" + //
" \"emailAnalyzer\": {\n" + //
" \"type\": \"custom\",\n" + //
" \"tokenizer\": \"uax_url_email\"\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
"}\n";
String jsonSettings = """
{
"index": {
"number_of_shards": "1",
"number_of_replicas": "0",
"analysis": {
"analyzer": {
"emailAnalyzer": {
"type": "custom",
"tokenizer": "uax_url_email"
}
}
}
}
}
""";
String jsonMapping = "{\n" + //
" \"properties\": {\n" + //
" \"email\": {\n" + //
" \"type\": \"text\",\n" + //
" \"analyzer\": \"emailAnalyzer\"\n" + //
" }\n" + //
" }\n" + //
"}\n";
String jsonMapping = """
{
"properties": {
"email": {
"type": "text",
"analyzer": "emailAnalyzer"
}
}
}
""";
indicesClient.create(crb -> crb //
.index(index) //

View File

@ -129,61 +129,62 @@ public class CriteriaQueryMappingUnitTests {
);
// mapped field name and converted parameter
String expected = "{\n" + //
" \"bool\" : {\n" + //
" \"should\" : [\n" + //
" {\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"range\" : {\n" + //
" \"birth-date\" : {\n" + //
" \"from\" : \"09.11.1989\",\n" + //
" \"to\" : \"09.11.1990\",\n" + //
" \"include_lower\" : true,\n" + //
" \"include_upper\" : true,\n" + //
" \"boost\" : 1.0\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
" ],\n" + //
" \"adjust_pure_negative\" : true,\n" + //
" \"boost\" : 1.0\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"query_string\" : {\n" + //
" \"query\" : \"28.12.2019\",\n" + //
" \"fields\" : [\n" + //
" \"birth-date^1.0\"\n" + //
" ],\n" + //
" \"type\" : \"best_fields\",\n" + //
" \"default_operator\" : \"and\",\n" + //
" \"max_determinized_states\" : 10000,\n" + //
" \"enable_position_increments\" : true,\n" + //
" \"fuzziness\" : \"AUTO\",\n" + //
" \"fuzzy_prefix_length\" : 0,\n" + //
" \"fuzzy_max_expansions\" : 50,\n" + //
" \"phrase_slop\" : 0,\n" + //
" \"escape\" : false,\n" + //
" \"auto_generate_synonyms_phrase_query\" : true,\n" + //
" \"fuzzy_transpositions\" : true,\n" + //
" \"boost\" : 1.0\n" + //
" }\n" + //
" }\n" + //
" ],\n" + //
" \"adjust_pure_negative\" : true,\n" + //
" \"boost\" : 1.0\n" + //
" }\n" + //
" }\n" + //
" ],\n" + //
" \"adjust_pure_negative\" : true,\n" + //
" \"boost\" : 1.0\n" + //
" }\n" + //
"}"; //
String expected = """
{
"bool" : {
"should" : [
{
"bool" : {
"must" : [
{
"range" : {
"birth-date" : {
"from" : "09.11.1989",
"to" : "09.11.1990",
"include_lower" : true,
"include_upper" : true,
"boost" : 1.0
}
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
},
{
"bool" : {
"must" : [
{
"query_string" : {
"query" : "28.12.2019",
"fields" : [
"birth-date^1.0"
],
"type" : "best_fields",
"default_operator" : "and",
"max_determinized_states" : 10000,
"enable_position_increments" : true,
"fuzziness" : "AUTO",
"fuzzy_prefix_length" : 0,
"fuzzy_max_expansions" : 50,
"phrase_slop" : 0,
"escape" : false,
"auto_generate_synonyms_phrase_query" : true,
"fuzzy_transpositions" : true,
"boost" : 1.0
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}"""; //
mappingElasticsearchConverter.updateQuery(criteriaQuery, Person.class);
String queryString = new CriteriaQueryProcessor().createQuery(criteriaQuery.getCriteria()).toString();
@ -201,61 +202,62 @@ public class CriteriaQueryMappingUnitTests {
);
// mapped field name and converted parameter
String expected = "{\n" + //
" \"bool\" : {\n" + //
" \"should\" : [\n" + //
" {\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"range\" : {\n" + //
" \"birth-date\" : {\n" + //
" \"from\" : \"09.11.1989\",\n" + //
" \"to\" : \"09.11.1990\",\n" + //
" \"include_lower\" : true,\n" + //
" \"include_upper\" : true,\n" + //
" \"boost\" : 1.0\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
" ],\n" + //
" \"adjust_pure_negative\" : true,\n" + //
" \"boost\" : 1.0\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"query_string\" : {\n" + //
" \"query\" : \"383745721653\",\n" + //
" \"fields\" : [\n" + //
" \"created-date^1.0\"\n" + //
" ],\n" + //
" \"type\" : \"best_fields\",\n" + //
" \"default_operator\" : \"and\",\n" + //
" \"max_determinized_states\" : 10000,\n" + //
" \"enable_position_increments\" : true,\n" + //
" \"fuzziness\" : \"AUTO\",\n" + //
" \"fuzzy_prefix_length\" : 0,\n" + //
" \"fuzzy_max_expansions\" : 50,\n" + //
" \"phrase_slop\" : 0,\n" + //
" \"escape\" : false,\n" + //
" \"auto_generate_synonyms_phrase_query\" : true,\n" + //
" \"fuzzy_transpositions\" : true,\n" + //
" \"boost\" : 1.0\n" + //
" }\n" + //
" }\n" + //
" ],\n" + //
" \"adjust_pure_negative\" : true,\n" + //
" \"boost\" : 1.0\n" + //
" }\n" + //
" }\n" + //
" ],\n" + //
" \"adjust_pure_negative\" : true,\n" + //
" \"boost\" : 1.0\n" + //
" }\n" + //
"}"; //
String expected = """
{
"bool" : {
"should" : [
{
"bool" : {
"must" : [
{
"range" : {
"birth-date" : {
"from" : "09.11.1989",
"to" : "09.11.1990",
"include_lower" : true,
"include_upper" : true,
"boost" : 1.0
}
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
},
{
"bool" : {
"must" : [
{
"query_string" : {
"query" : "383745721653",
"fields" : [
"created-date^1.0"
],
"type" : "best_fields",
"default_operator" : "and",
"max_determinized_states" : 10000,
"enable_position_increments" : true,
"fuzziness" : "AUTO",
"fuzzy_prefix_length" : 0,
"fuzzy_max_expansions" : 50,
"phrase_slop" : 0,
"escape" : false,
"auto_generate_synonyms_phrase_query" : true,
"fuzzy_transpositions" : true,
"boost" : 1.0
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}
],
"adjust_pure_negative" : true,
"boost" : 1.0
}
}"""; //
mappingElasticsearchConverter.updateQuery(criteriaQuery, Person.class);
String queryString = new CriteriaQueryProcessor().createQuery(criteriaQuery.getCriteria()).toString();
@ -272,43 +274,45 @@ public class CriteriaQueryMappingUnitTests {
.between(LocalDate.of(1989, 11, 9), LocalDate.of(1990, 11, 9)) //
.or("birthDate").is(LocalDate.of(2019, 12, 28))));
String expected = "{\n" + //
" \"bool\": {\n" + //
" \"must\": [\n" + //
" {\n" + //
" \"match\": {\n" + //
" \"first-name\": {\n" + //
" \"query\": \"John\"\n" + //
" }\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"bool\": {\n" + //
" \"should\": [\n" + //
" {\n" + //
" \"range\": {\n" + //
" \"birth-date\": {\n" + //
" \"from\": \"09.11.1989\",\n" + //
" \"to\": \"09.11.1990\",\n" + //
" \"include_lower\": true,\n" + //
" \"include_upper\": true\n" + //
" }\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"28.12.2019\",\n" + //
" \"fields\": [\n" + //
" \"birth-date^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"bool": {
"must": [
{
"match": {
"first-name": {
"query": "John"
}
}
},
{
"bool": {
"should": [
{
"range": {
"birth-date": {
"from": "09.11.1989",
"to": "09.11.1990",
"include_lower": true,
"include_upper": true
}
}
},
{
"query_string": {
"query": "28.12.2019",
"fields": [
"birth-date^1.0"
]
}
}
]
}
}
]
}
}
"""; //
mappingElasticsearchConverter.updateQuery(criteriaQuery, Person.class);
String queryString = new CriteriaQueryProcessor().createQuery(criteriaQuery.getCriteria()).toString();
@ -340,25 +344,27 @@ public class CriteriaQueryMappingUnitTests {
@DisplayName("should map names and value in nested entities")
void shouldMapNamesAndValueInNestedEntities() throws JSONException {
String expected = "{\n" + //
" \"bool\": {\n" + //
" \"must\": [\n" + //
" {\n" + //
" \"nested\": {\n" + //
" \"query\": {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"03.10.1999\",\n" + //
" \"fields\": [\n" + //
" \"per-sons.birth-date^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" \"path\": \"per-sons\"\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"bool": {
"must": [
{
"nested": {
"query": {
"query_string": {
"query": "03.10.1999",
"fields": [
"per-sons.birth-date^1.0"
]
}
},
"path": "per-sons"
}
}
]
}
}
"""; //
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("persons.birthDate").is(LocalDate.of(1999, 10, 3)));
mappingElasticsearchConverter.updateQuery(criteriaQuery, House.class);
@ -371,25 +377,27 @@ public class CriteriaQueryMappingUnitTests {
@DisplayName("should map names and value in nested entities with sub-fields")
void shouldMapNamesAndValueInNestedEntitiesWithSubfields() throws JSONException {
String expected = "{\n" + //
" \"bool\": {\n" + //
" \"must\": [\n" + //
" {\n" + //
" \"nested\": {\n" + //
" \"query\": {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"Foobar\",\n" + //
" \"fields\": [\n" + //
" \"per-sons.nick-name.keyword^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" \"path\": \"per-sons\"\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"bool": {
"must": [
{
"nested": {
"query": {
"query_string": {
"query": "Foobar",
"fields": [
"per-sons.nick-name.keyword^1.0"
]
}
},
"path": "per-sons"
}
}
]
}
}
"""; //
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("persons.nickName.keyword").is("Foobar"));
mappingElasticsearchConverter.updateQuery(criteriaQuery, House.class);
@ -402,20 +410,22 @@ public class CriteriaQueryMappingUnitTests {
@DisplayName("should map names and value in object entities")
void shouldMapNamesAndValueInObjectEntities() throws JSONException {
String expected = "{\n" + //
" \"bool\": {\n" + //
" \"must\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"03.10.1999\",\n" + //
" \"fields\": [\n" + //
" \"per-sons.birth-date^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"bool": {
"must": [
{
"query_string": {
"query": "03.10.1999",
"fields": [
"per-sons.birth-date^1.0"
]
}
}
]
}
}
"""; //
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("persons.birthDate").is(LocalDate.of(1999, 10, 3)));
mappingElasticsearchConverter.updateQuery(criteriaQuery, ObjectWithPerson.class);

View File

@ -33,28 +33,29 @@ class CriteriaQueryProcessorUnitTests {
@Test // DATAES-706
void shouldProcessTwoCriteriaWithAnd() throws JSONException {
String expected = "{\n" + //
" \"bool\": {\n" + //
" \"must\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"value1\",\n" + //
" \"fields\": [\n" + //
" \"field1^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"value2\",\n" + //
" \"fields\": [\n" + //
" \"field2^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}"; //
String expected = """
{
"bool": {
"must": [
{
"query_string": {
"query": "value1",
"fields": [
"field1^1.0"
]
}
},
{
"query_string": {
"query": "value2",
"fields": [
"field2^1.0"
]
}
}
]
}
}"""; //
Criteria criteria = new Criteria("field1").is("value1").and("field2").is("value2");
@ -66,28 +67,29 @@ class CriteriaQueryProcessorUnitTests {
@Test // DATAES-706
void shouldProcessTwoCriteriaWithOr() throws JSONException {
String expected = "{\n" + //
" \"bool\": {\n" + //
" \"should\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"value1\",\n" + //
" \"fields\": [\n" + //
" \"field1^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"value2\",\n" + //
" \"fields\": [\n" + //
" \"field2^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}"; //
String expected = """
{
"bool": {
"should": [
{
"query_string": {
"query": "value1",
"fields": [
"field1^1.0"
]
}
},
{
"query_string": {
"query": "value2",
"fields": [
"field2^1.0"
]
}
}
]
}
}"""; //
Criteria criteria = new Criteria("field1").is("value1").or("field2").is("value2");
@ -99,46 +101,48 @@ class CriteriaQueryProcessorUnitTests {
@Test // DATAES-706
void shouldProcessMixedCriteriaWithOrAnd() throws JSONException {
String expected = "{\n" + //
" \"bool\": {\n" + //
" \"must\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"value1\",\n" + //
" \"fields\": [\n" + //
" \"field1^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"value3\",\n" + //
" \"fields\": [\n" + //
" \"field3^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ],\n" + //
" \"should\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"value2\",\n" + //
" \"fields\": [\n" + //
" \"field2^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"value4\",\n" + //
" \"fields\": [\n" + //
" \"field4^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"bool": {
"must": [
{
"query_string": {
"query": "value1",
"fields": [
"field1^1.0"
]
}
},
{
"query_string": {
"query": "value3",
"fields": [
"field3^1.0"
]
}
}
],
"should": [
{
"query_string": {
"query": "value2",
"fields": [
"field2^1.0"
]
}
},
{
"query_string": {
"query": "value4",
"fields": [
"field4^1.0"
]
}
}
]
}
}
"""; //
Criteria criteria = new Criteria("field1").is("value1") //
.or("field2").is("value2") //
@ -153,42 +157,43 @@ class CriteriaQueryProcessorUnitTests {
@Test // DATAES-706
void shouldAddSubQuery() throws JSONException {
String expected = "{\n" + //
" \"bool\": {\n" + //
" \"must\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"Miller\",\n" + //
" \"fields\": [\n" + //
" \"lastName^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"bool\": {\n" + //
" \"should\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"John\",\n" + //
" \"fields\": [\n" + //
" \"firstName^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"Jack\",\n" + //
" \"fields\": [\n" + //
" \"firstName^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}"; //
String expected = """
{
"bool": {
"must": [
{
"query_string": {
"query": "Miller",
"fields": [
"lastName^1.0"
]
}
},
{
"bool": {
"should": [
{
"query_string": {
"query": "John",
"fields": [
"firstName^1.0"
]
}
},
{
"query_string": {
"query": "Jack",
"fields": [
"firstName^1.0"
]
}
}
]
}
}
]
}
}"""; //
Criteria criteria = new Criteria("lastName").is("Miller")
.subCriteria(new Criteria().or("firstName").is("John").or("firstName").is("Jack"));
@ -201,84 +206,85 @@ class CriteriaQueryProcessorUnitTests {
@Test // DATAES-706
void shouldProcessNestedSubCriteria() throws JSONException {
String expected = "{\n" + //
" \"bool\": {\n" + //
" \"should\": [\n" + //
" {\n" + //
" \"bool\": {\n" + //
" \"must\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"Miller\",\n" + //
" \"fields\": [\n" + //
" \"lastName^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"bool\": {\n" + //
" \"should\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"Jack\",\n" + //
" \"fields\": [\n" + //
" \"firstName^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"John\",\n" + //
" \"fields\": [\n" + //
" \"firstName^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"bool\": {\n" + //
" \"must\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"Smith\",\n" + //
" \"fields\": [\n" + //
" \"lastName^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"bool\": {\n" + //
" \"should\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"Emma\",\n" + //
" \"fields\": [\n" + //
" \"firstName^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"Lucy\",\n" + //
" \"fields\": [\n" + //
" \"firstName^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}"; //
String expected = """
{
"bool": {
"should": [
{
"bool": {
"must": [
{
"query_string": {
"query": "Miller",
"fields": [
"lastName^1.0"
]
}
},
{
"bool": {
"should": [
{
"query_string": {
"query": "Jack",
"fields": [
"firstName^1.0"
]
}
},
{
"query_string": {
"query": "John",
"fields": [
"firstName^1.0"
]
}
}
]
}
}
]
}
},
{
"bool": {
"must": [
{
"query_string": {
"query": "Smith",
"fields": [
"lastName^1.0"
]
}
},
{
"bool": {
"should": [
{
"query_string": {
"query": "Emma",
"fields": [
"firstName^1.0"
]
}
},
{
"query_string": {
"query": "Lucy",
"fields": [
"firstName^1.0"
]
}
}
]
}
}
]
}
}
]
}
}"""; //
Criteria criteria = Criteria.or()
.subCriteria(new Criteria("lastName").is("Miller")
@ -294,20 +300,22 @@ class CriteriaQueryProcessorUnitTests {
@Test // DATAES-706
void shouldBuildMatchQuery() throws JSONException {
String expected = "{\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"match\" : {\n" + //
" \"field1\" : {\n" + //
" \"query\" : \"value1 value2\",\n" + //
" \"operator\" : \"OR\"\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"bool" : {
"must" : [
{
"match" : {
"field1" : {
"query" : "value1 value2",
"operator" : "OR"
}
}
}
]
}
}
"""; //
Criteria criteria = new Criteria("field1").matches("value1 value2");
@ -319,20 +327,22 @@ class CriteriaQueryProcessorUnitTests {
@Test // DATAES-706
void shouldBuildMatchAllQuery() throws JSONException {
String expected = "{\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"match\" : {\n" + //
" \"field1\" : {\n" + //
" \"query\" : \"value1 value2\",\n" + //
" \"operator\" : \"AND\"\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"bool" : {
"must" : [
{
"match" : {
"field1" : {
"query" : "value1 value2",
"operator" : "AND"
}
}
}
]
}
}
"""; //
Criteria criteria = new Criteria("field1").matchesAll("value1 value2");
@ -345,25 +355,26 @@ class CriteriaQueryProcessorUnitTests {
@DisplayName("should build nested query")
void shouldBuildNestedQuery() throws JSONException {
String expected = "{\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"nested\" : {\n" + //
" \"query\" : {\n" + //
" \"query_string\" : {\n" + //
" \"query\" : \"murphy\",\n" + //
" \"fields\" : [\n" + //
" \"houses.inhabitants.lastName^1.0\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" \"path\" : \"houses.inhabitants\"\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}"; //
String expected = """
{
"bool" : {
"must" : [
{
"nested" : {
"query" : {
"query_string" : {
"query" : "murphy",
"fields" : [
"houses.inhabitants.lastName^1.0"
]
}
},
"path" : "houses.inhabitants"
}
}
]
}
}"""; //
Criteria criteria = new Criteria("houses.inhabitants.lastName").is("murphy");
criteria.getField().setPath("houses.inhabitants");
@ -377,32 +388,31 @@ class CriteriaQueryProcessorUnitTests {
@DisplayName("should build query for empty property")
void shouldBuildQueryForEmptyProperty() throws JSONException {
String expected = "{\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"exists\" : {\n" + //
" \"field\" : \"lastName\"" + //
" }\n" + //
" }\n" + //
" ],\n" + //
" \"must_not\" : [\n" + //
" {\n" + //
" \"wildcard\" : {\n" + //
" \"lastName\" : {\n" + //
" \"wildcard\" : \"*\"" + //
" }\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}"; //
String expected = """
{
"bool" : {
"must" : [
{
"bool" : {
"must" : [
{
"exists" : {
"field" : "lastName" }
}
],
"must_not" : [
{
"wildcard" : {
"lastName" : {
"wildcard" : "*" }
}
}
]
}
}
]
}
}"""; //
Criteria criteria = new Criteria("lastName").empty();
@ -415,19 +425,21 @@ class CriteriaQueryProcessorUnitTests {
@DisplayName("should build query for non-empty property")
void shouldBuildQueryForNonEmptyProperty() throws JSONException {
String expected = "{\n" + //
" \"bool\" : {\n" + //
" \"must\" : [\n" + //
" {\n" + //
" \"wildcard\" : {\n" + //
" \"lastName\" : {\n" + //
" \"wildcard\" : \"*\"\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"bool" : {
"must" : [
{
"wildcard" : {
"lastName" : {
"wildcard" : "*"
}
}
}
]
}
}
"""; //
Criteria criteria = new Criteria("lastName").notEmpty();

View File

@ -889,9 +889,8 @@ public class ReactiveElasticsearchClientIntegrationTests {
client.indices().getMapping(getMappingsRequest) //
.as(StepVerifier::create) //
.consumeNextWith(it -> {
assertThat(it.mappings().get(INDEX_I).getSourceAsMap()).isEqualTo(jsonMap);
}).verifyComplete();
.consumeNextWith(it -> assertThat(it.mappings().get(INDEX_I).getSourceAsMap()).isEqualTo(jsonMap))
.verifyComplete();
}
@Test // #1640
@ -1067,9 +1066,7 @@ public class ReactiveElasticsearchClientIntegrationTests {
client.indices().putMapping(putMappingRequest).block();
client.indices().getFieldMapping(request -> request.indices(INDEX_I).fields("message1")).as(StepVerifier::create)
.consumeNextWith(it -> {
assertThat(it.mappings().get(INDEX_I).keySet().size()).isZero();
}).verifyComplete();
.consumeNextWith(it -> assertThat(it.mappings().get(INDEX_I).keySet().size()).isZero()).verifyComplete();
}
@Test // #1640

View File

@ -170,9 +170,8 @@ public class ReactiveElasticsearchClientUnitTests {
@Test // DATAES-488
public void getShouldHitGetEndpoint() {
hostProvider.when(HOST).receive(clientResponse -> {
when(clientResponse.statusCode()).thenReturn(HttpStatus.ACCEPTED, HttpStatus.NOT_FOUND);
});
hostProvider.when(HOST).receive(
clientResponse -> when(clientResponse.statusCode()).thenReturn(HttpStatus.ACCEPTED, HttpStatus.NOT_FOUND));
hostProvider.when(HOST) //
.receiveGetByIdNotFound();
@ -234,9 +233,8 @@ public class ReactiveElasticsearchClientUnitTests {
verify(hostProvider.client(HOST)).method(HttpMethod.POST);
hostProvider.when(HOST).exchange(requestBodyUriSpec -> {
verify(requestBodyUriSpec).body(any(Publisher.class), any(Class.class));
});
hostProvider.when(HOST)
.exchange(requestBodyUriSpec -> verify(requestBodyUriSpec).body(any(Publisher.class), any(Class.class)));
URI uri = hostProvider.when(HOST).captureUri();
assertThat(uri.getRawPath()).isEqualTo("/_mget");
@ -370,9 +368,8 @@ public class ReactiveElasticsearchClientUnitTests {
.verifyComplete();
verify(hostProvider.client(HOST)).method(HttpMethod.PUT);
hostProvider.when(HOST).exchange(requestBodyUriSpec -> {
verify(requestBodyUriSpec).contentType(MediaType.APPLICATION_JSON);
});
hostProvider.when(HOST)
.exchange(requestBodyUriSpec -> verify(requestBodyUriSpec).contentType(MediaType.APPLICATION_JSON));
URI uri = hostProvider.when(HOST).captureUri();
assertThat(uri.getRawPath()).isEqualTo("/twitter/_doc/10/_create");
@ -389,9 +386,8 @@ public class ReactiveElasticsearchClientUnitTests {
.verifyComplete();
verify(hostProvider.client(HOST)).method(HttpMethod.PUT);
hostProvider.when(HOST).exchange(requestBodyUriSpec -> {
verify(requestBodyUriSpec).contentType(MediaType.APPLICATION_JSON);
});
hostProvider.when(HOST)
.exchange(requestBodyUriSpec -> verify(requestBodyUriSpec).contentType(MediaType.APPLICATION_JSON));
URI uri = hostProvider.when(HOST).captureUri();
assertThat(uri.getRawPath()).isEqualTo("/twitter/_doc/10");
@ -444,9 +440,8 @@ public class ReactiveElasticsearchClientUnitTests {
.verifyComplete();
verify(hostProvider.client(HOST)).method(HttpMethod.POST);
hostProvider.when(HOST).exchange(requestBodyUriSpec -> {
verify(requestBodyUriSpec).contentType(MediaType.APPLICATION_JSON);
});
hostProvider.when(HOST)
.exchange(requestBodyUriSpec -> verify(requestBodyUriSpec).contentType(MediaType.APPLICATION_JSON));
URI uri = hostProvider.when(HOST).captureUri();
assertThat(uri.getRawPath()).isEqualTo("/twitter/doc/1/_update");
@ -689,9 +684,7 @@ public class ReactiveElasticsearchClientUnitTests {
.expectNextCount(4) //
.verifyComplete();
hostProvider.when(HOST).receive(response -> {
verify(response, times(4)).body(any());
});
hostProvider.when(HOST).receive(response -> verify(response, times(4)).body(any()));
}
@Test // DATAES-510
@ -711,9 +704,7 @@ public class ReactiveElasticsearchClientUnitTests {
.expectNextCount(2) //
.verifyError();
hostProvider.when(HOST).receive(response -> {
verify(response, times(3)).body(any());
});
hostProvider.when(HOST).receive(response -> verify(response, times(3)).body(any()));
}
@Test // DATAES-684

View File

@ -302,91 +302,92 @@ class RequestFactoryTests {
aliasActions.add(new AliasAction.Add(AliasActionParameters.builder().withIndices("index5").withAliases("alias5")
.withFilterQuery(query, Person.class).build()));
String expected = "{\n" + //
" \"actions\": [\n" + //
" {\n" + //
" \"add\": {\n" + //
" \"indices\": [\n" + //
" \"index1\",\n" + //
" \"index2\"\n" + //
" ],\n" + //
" \"aliases\": [\n" + //
" \"alias1\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"remove\": {\n" + //
" \"indices\": [\n" + //
" \"index3\"\n" + //
" ],\n" + //
" \"aliases\": [\n" + //
" \"alias1\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"remove_index\": {\n" + //
" \"indices\": [\n" + //
" \"index3\"\n" + //
" ]\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"add\": {\n" + //
" \"indices\": [\n" + //
" \"index4\"\n" + //
" ],\n" + //
" \"aliases\": [\n" + //
" \"alias4\"\n" + //
" ],\n" + //
" \"routing\": \"routing\",\n" + //
" \"index_routing\": \"indexRouting\",\n" + //
" \"search_routing\": \"searchRouting\",\n" + //
" \"is_write_index\": true,\n" + //
" \"is_hidden\": true\n" + //
" }\n" + //
" },\n" + //
" {\n" + //
" \"add\": {\n" + //
" \"indices\": [\n" + //
" \"index5\"\n" + //
" ],\n" + //
" \"aliases\": [\n" + //
" \"alias5\"\n" + //
" ],\n" + //
" \"filter\": {\n" + //
" \"bool\": {\n" + //
" \"must\": [\n" + //
" {\n" + //
" \"query_string\": {\n" + //
" \"query\": \"Smith\",\n" + //
" \"fields\": [\n" + //
" \"last-name^1.0\"\n" + //
" ],\n" + //
" \"type\": \"best_fields\",\n" + //
" \"default_operator\": \"and\",\n" + //
" \"max_determinized_states\": 10000,\n" + //
" \"enable_position_increments\": true,\n" + //
" \"fuzziness\": \"AUTO\",\n" + //
" \"fuzzy_prefix_length\": 0,\n" + //
" \"fuzzy_max_expansions\": 50,\n" + //
" \"phrase_slop\": 0,\n" + //
" \"escape\": false,\n" + //
" \"auto_generate_synonyms_phrase_query\": true,\n" + //
" \"fuzzy_transpositions\": true,\n" + //
" \"boost\": 1.0\n" + //
" }\n" + //
" }\n" + //
" ],\n" + //
" \"adjust_pure_negative\": true,\n" + //
" \"boost\": 1.0\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
" ]\n" + //
"}"; //
String expected = """
{
"actions": [
{
"add": {
"indices": [
"index1",
"index2"
],
"aliases": [
"alias1"
]
}
},
{
"remove": {
"indices": [
"index3"
],
"aliases": [
"alias1"
]
}
},
{
"remove_index": {
"indices": [
"index3"
]
}
},
{
"add": {
"indices": [
"index4"
],
"aliases": [
"alias4"
],
"routing": "routing",
"index_routing": "indexRouting",
"search_routing": "searchRouting",
"is_write_index": true,
"is_hidden": true
}
},
{
"add": {
"indices": [
"index5"
],
"aliases": [
"alias5"
],
"filter": {
"bool": {
"must": [
{
"query_string": {
"query": "Smith",
"fields": [
"last-name^1.0"
],
"type": "best_fields",
"default_operator": "and",
"max_determinized_states": 10000,
"enable_position_increments": true,
"fuzziness": "AUTO",
"fuzzy_prefix_length": 0,
"fuzzy_max_expansions": 50,
"phrase_slop": 0,
"escape": false,
"auto_generate_synonyms_phrase_query": true,
"fuzzy_transpositions": true,
"boost": 1.0
}
}
],
"adjust_pure_negative": true,
"boost": 1.0
}
}
}
}
]
}"""; //
IndicesAliasesRequest indicesAliasesRequest = requestFactory.indicesAliasesRequest(aliasActions);
@ -399,37 +400,39 @@ class RequestFactoryTests {
// DATAES-612
void shouldCreatePutIndexTemplateRequest() throws JSONException, IOException {
String expected = "{\n" + //
" \"index_patterns\": [\n" + //
" \"test-*\"\n" + //
" ],\n" + //
" \"order\": 42,\n" + //
" \"version\": 7,\n" + //
" \"settings\": {\n" + //
" \"index\": {\n" + //
" \"number_of_replicas\": \"2\",\n" + //
" \"number_of_shards\": \"3\",\n" + //
" \"refresh_interval\": \"7s\",\n" + //
" \"store\": {\n" + //
" \"type\": \"oops\"\n" + //
" }\n" + //
" }\n" + //
" },\n" + //
" \"mappings\": {\n" + //
" \"properties\": {\n" + //
" \"price\": {\n" + //
" \"type\": \"double\"\n" + //
" }\n" + //
" }\n" + //
" },\n" + //
" \"aliases\":{\n" + //
" \"alias1\": {},\n" + //
" \"alias2\": {},\n" + //
" \"alias3\": {\n" + //
" \"routing\": \"11\"\n" + //
" }\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"index_patterns": [
"test-*"
],
"order": 42,
"version": 7,
"settings": {
"index": {
"number_of_replicas": "2",
"number_of_shards": "3",
"refresh_interval": "7s",
"store": {
"type": "oops"
}
}
},
"mappings": {
"properties": {
"price": {
"type": "double"
}
}
},
"aliases":{
"alias1": {},
"alias2": {},
"alias3": {
"routing": "11"
}
}
}
"""; //
org.springframework.data.elasticsearch.core.document.Document settings = org.springframework.data.elasticsearch.core.document.Document
.create();
@ -535,56 +538,77 @@ class RequestFactoryTests {
converter.updateQuery(query, Person.class);
String expected = '{' + //
" \"query\": {" + //
" \"bool\": {" + //
" \"must\": [" + //
" {" + //
" \"query_string\": {" + //
" \"query\": \"Smith\"," + //
" \"fields\": [" + //
" \"last-name^1.0\"" + //
" ]" + //
" }" + //
" }" + //
" ]" + //
" }" + //
" }," + //
" \"rescore\": [{\n" + " \"window_size\" : 100,\n" + " \"query\" : {\n"
+ " \"rescore_query\" : {\n" + " \"match_phrase\" : {\n" + " \"message\" : {\n"
+ " \"query\" : \"the quick brown\",\n" + " \"slop\" : 2\n"
+ " }\n" + " }\n" + " },\n" + " \"query_weight\" : 0.7,\n"
+ " \"rescore_query_weight\" : 1.2\n" + " }\n" + " }," + " {\n" + " \"window_size\": 50,\n"
+ " \"query\": {\n" + " \"rescore_query\": {\n" + " \"function_score\": {\n"
+ " \"query\": {\n" + " \"match_all\": {\n"
+ " \"boost\": 1.0\n" + " }\n"
+ " },\n" + " \"functions\": [\n"
+ " {\n" + " \"filter\": {\n"
+ " \"exists\": {\n"
+ " \"field\": \"someField\",\n"
+ " \"boost\": 1.0\n" + " }\n"
+ " },\n" + " \"weight\": 5.022317,\n"
+ " \"gauss\": {\n" + " \"someField\": {\n"
+ " \"origin\": 0.0,\n"
+ " \"scale\": 100000.0,\n"
+ " \"decay\": 0.683\n" + " },\n"
+ " \"multi_value_mode\": \"MIN\"\n" + " }\n"
+ " },\n" + " {\n"
+ " \"filter\": {\n" + " \"exists\": {\n"
+ " \"field\": \"anotherField\",\n"
+ " \"boost\": 1.0\n" + " }\n"
+ " },\n" + " \"weight\": 4.170836,\n"
+ " \"gauss\": {\n" + " \"anotherField\": {\n"
+ " \"origin\": \"202102\",\n"
+ " \"scale\": \"31536000s\",\n"
+ " \"decay\": 0.683\n" + " },\n"
+ " \"multi_value_mode\": \"MIN\"\n" + " }\n"
+ " }\n" + " ],\n"
+ " \"score_mode\": \"sum\",\n" + " \"boost_mode\": \"avg\",\n"
+ " \"max_boost\": 50.0,\n" + " \"boost\": 1.5\n"
+ " }\n" + " },\n" + " \"query_weight\": 2.0,"
+ " \"rescore_query_weight\": 5.0," + " \"score_mode\": \"multiply\"" + " }\n" + " }\n" + " ]\n"
+ '}';
String expected = """
{ "query": { "bool": { "must": [ { "query_string": { "query": "Smith", "fields": [ "last-name^1.0" ] } } ] } }, "rescore": [{
"window_size" : 100,
"query" : {
"rescore_query" : {
"match_phrase" : {
"message" : {
"query" : "the quick brown",
"slop" : 2
}
}
},
"query_weight" : 0.7,
"rescore_query_weight" : 1.2
}
}, {
"window_size": 50,
"query": {
"rescore_query": {
"function_score": {
"query": {
"match_all": {
"boost": 1.0
}
},
"functions": [
{
"filter": {
"exists": {
"field": "someField",
"boost": 1.0
}
},
"weight": 5.022317,
"gauss": {
"someField": {
"origin": 0.0,
"scale": 100000.0,
"decay": 0.683
},
"multi_value_mode": "MIN"
}
},
{
"filter": {
"exists": {
"field": "anotherField",
"boost": 1.0
}
},
"weight": 4.170836,
"gauss": {
"anotherField": {
"origin": "202102",
"scale": "31536000s",
"decay": 0.683
},
"multi_value_mode": "MIN"
}
}
],
"score_mode": "sum",
"boost_mode": "avg",
"max_boost": 50.0,
"boost": 1.5
}
},
"query_weight": 2.0, "rescore_query_weight": 5.0, "score_mode": "multiply" }
}
]
}""";
String searchRequest = requestFactory.searchRequest(query, Person.class, IndexCoordinates.of("persons")).source()
.toString();
@ -644,32 +668,33 @@ class RequestFactoryTests {
@Test
// #1529
void shouldCreateReindexRequest() throws IOException, JSONException {
final String expected = "{\n" + //
" \"source\":{\n" + //
" \"remote\":{\n" + //
" \"username\":\"admin\",\n" + //
" \"password\":\"password\",\n" + //
" \"host\":\"http://localhost:9200/elasticsearch\",\n" + //
" \"socket_timeout\":\"30s\",\n" + //
" \"connect_timeout\":\"30s\"\n" + //
" },\n" + //
" \"index\":[\"source_1\",\"source_2\"],\n" + //
" \"size\":5,\n" + //
" \"query\":{\"match_all\":{}},\n" + //
" \"_source\":{\"includes\":[\"name\"],\"excludes\":[]},\n" + //
" \"slice\":{\"id\":1,\"max\":20}\n" + //
" },\n" + //
" \"dest\":{\n" + //
" \"index\":\"destination\",\n" + //
" \"routing\":\"routing\",\n" + //
" \"op_type\":\"create\",\n" + //
" \"pipeline\":\"pipeline\",\n" + //
" \"version_type\":\"external\"\n" + //
" },\n" + //
" \"max_docs\":10,\n" + //
" \"script\":{\"source\":\"Math.max(1,2)\",\"lang\":\"java\"},\n" + //
" \"conflicts\":\"proceed\"\n" + //
"}";
final String expected = """
{
"source":{
"remote":{
"username":"admin",
"password":"password",
"host":"http://localhost:9200/elasticsearch",
"socket_timeout":"30s",
"connect_timeout":"30s"
},
"index":["source_1","source_2"],
"size":5,
"query":{"match_all":{}},
"_source":{"includes":["name"],"excludes":[]},
"slice":{"id":1,"max":20}
},
"dest":{
"index":"destination",
"routing":"routing",
"op_type":"create",
"pipeline":"pipeline",
"version_type":"external"
},
"max_docs":10,
"script":{"source":"Math.max(1,2)","lang":"java"},
"conflicts":"proceed"
}""";
Remote remote = Remote.builder("http", "localhost", 9200).withPathPrefix("elasticsearch").withUsername("admin")
.withPassword("password").withConnectTimeout(Duration.ofSeconds(30)).withSocketTimeout(Duration.ofSeconds(30))
@ -692,17 +717,18 @@ class RequestFactoryTests {
@Test
// #1529
void shouldAllowSourceQueryForReindexWithoutRemote() throws IOException, JSONException {
final String expected = "{\n" + //
" \"source\":{\n" + //
" \"index\":[\"source\"],\n" + //
" \"query\":{\"match_all\":{}}\n" + //
" },\n" + //
" \"dest\":{\n" + //
" \"index\":\"destination\",\n" + //
" \"op_type\":\"index\",\n" + //
" \"version_type\":\"internal\"\n" + //
" }\n" + //
"}";
final String expected = """
{
"source":{
"index":["source"],
"query":{"match_all":{}}
},
"dest":{
"index":"destination",
"op_type":"index",
"version_type":"internal"
}
}""";
ReindexRequest reindexRequest = ReindexRequest
.builder(IndexCoordinates.of("source"), IndexCoordinates.of("destination"))

View File

@ -56,7 +56,7 @@ public abstract class AuditingIntegrationTests {
}
public static AuditorAware<String> auditorProvider() {
return new AuditorAware<String>() {
return new AuditorAware<>() {
int count = 0;
@Override

View File

@ -57,7 +57,7 @@ public abstract class AuditingReactiveIntegrationTest {
}
public static ReactiveAuditorAware<String> auditorProvider() {
return new ReactiveAuditorAware<String>() {
return new ReactiveAuditorAware<>() {
int count = 0;
@Override

View File

@ -19,7 +19,6 @@ import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.client.elc.QueryBuilders.*;
import static org.springframework.data.elasticsearch.utils.IndexBuilder.*;
import co.elastic.clients.elasticsearch._types.SortOptionsBuilders;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.FunctionBoostMode;
@ -81,20 +80,15 @@ public class ElasticsearchELCIntegrationTests extends ElasticsearchIntegrationTe
operations.bulkIndex(indexQueries, IndexCoordinates.of(indexNameProvider.indexName()));
NativeQuery query = NativeQuery.builder()
.withSort(b -> b.field(fb -> fb.field("message").order(SortOrder.Asc))).build();
NativeQuery query = NativeQuery.builder().withSort(b -> b.field(fb -> fb.field("message").order(SortOrder.Asc)))
.build();
SearchHits<SampleEntity> searchHits = operations.search(query, SampleEntity.class,
IndexCoordinates.of(indexNameProvider.indexName()));
assertThat(searchHits.getSearchHits()) //
.satisfiesExactly(e -> {
assertThat(e.getId()).isEqualTo("1");
}, e -> {
assertThat(e.getId()).isEqualTo("3");
}, e -> {
assertThat(e.getId()).isEqualTo("2");
});
.satisfiesExactly(e -> assertThat(e.getId()).isEqualTo("1"), e -> assertThat(e.getId()).isEqualTo("3"),
e -> assertThat(e.getId()).isEqualTo("2"));
}
@Override

View File

@ -39,7 +39,6 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@ -1722,9 +1721,7 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
SearchHits<SampleEntity> searchHits = operations.search(query, SampleEntity.class);
searchHits.forEach(searchHit -> {
assertThat(searchHit.getIndex()).isEqualTo(indexName);
});
searchHits.forEach(searchHit -> assertThat(searchHit.getIndex()).isEqualTo(indexName));
}
@Test
@ -1868,6 +1865,7 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
// then
Query searchQuery = operations.matchAllQuery();
// noinspection rawtypes
SearchHits<Map> searchHits = operations.search(searchQuery, Map.class,
IndexCoordinates.of(indexNameProvider.indexName()));
@ -2216,20 +2214,21 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
@Test // DATAES-71
public void shouldCreateIndexWithGivenSettings() {
String settings = "{\n" //
+ " \"index\": {\n" //
+ " \"number_of_shards\": \"1\",\n" //
+ " \"number_of_replicas\": \"0\",\n" //
+ " \"analysis\": {\n" //
+ " \"analyzer\": {\n" //
+ " \"emailAnalyzer\": {\n" //
+ " \"type\": \"custom\",\n" //
+ " \"tokenizer\": \"uax_url_email\"\n" //
+ " }\n" //
+ " }\n" //
+ " }\n" //
+ " }\n" //
+ '}'; //
String settings = """
{
"index": {
"number_of_shards": "1",
"number_of_replicas": "0",
"analysis": {
"analyzer": {
"emailAnalyzer": {
"type": "custom",
"tokenizer": "uax_url_email"
}
}
}
}
}"""; //
indexOperations.delete();
indexOperations.create(parse(settings));
@ -2258,20 +2257,21 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
@Test // DATAES-88
public void shouldCreateIndexWithGivenClassAndSettings() {
String settings = "{\n" //
+ " \"index\": {\n" //
+ " \"number_of_shards\": \"1\",\n" //
+ " \"number_of_replicas\": \"0\",\n" //
+ " \"analysis\": {\n" //
+ " \"analyzer\": {\n" //
+ " \"emailAnalyzer\": {\n" //
+ " \"type\": \"custom\",\n" //
+ " \"tokenizer\": \"uax_url_email\"\n" //
+ " }\n" //
+ " }\n" //
+ " }\n" //
+ " }\n" //
+ '}'; //
String settings = """
{
"index": {
"number_of_shards": "1",
"number_of_replicas": "0",
"analysis": {
"analyzer": {
"emailAnalyzer": {
"type": "custom",
"tokenizer": "uax_url_email"
}
}
}
}
}"""; //
indexOperations.delete();
indexOperations.create(parse(settings));
@ -2822,11 +2822,9 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
assertThat(sortValues.get(0)).isInstanceOf(String.class).isEqualTo("thousands");
// transport client returns Long, RestHighlevelClient Integer, new ElasticsearchClient String
java.lang.Object o = sortValues.get(1);
if (o instanceof Integer) {
Integer i = (Integer) o;
if (o instanceof Integer i) {
assertThat(o).isInstanceOf(Integer.class).isEqualTo(1000);
} else if (o instanceof Long) {
Long l = (Long) o;
} else if (o instanceof Long l) {
assertThat(o).isInstanceOf(Long.class).isEqualTo(1000L);
} else if (o instanceof String) {
assertThat(o).isInstanceOf(String.class).isEqualTo("1000");
@ -3015,9 +3013,7 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
Iterable<OptimisticEntity> saved = operations.save(Arrays.asList(original1, original2));
saved.forEach(optimisticEntity -> {
assertThatSeqNoPrimaryTermIsFilled(optimisticEntity);
});
saved.forEach(this::assertThatSeqNoPrimaryTermIsFilled);
}
@Test // DATAES-799
@ -3033,10 +3029,10 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
private void assertThatSeqNoPrimaryTermIsFilled(OptimisticEntity retrieved) {
assertThat(retrieved.seqNoPrimaryTerm).isNotNull();
assertThat(retrieved.seqNoPrimaryTerm.getSequenceNumber()).isNotNull();
assertThat(retrieved.seqNoPrimaryTerm.getSequenceNumber()).isNotNegative();
assertThat(retrieved.seqNoPrimaryTerm.getPrimaryTerm()).isNotNull();
assertThat(retrieved.seqNoPrimaryTerm.getPrimaryTerm()).isPositive();
assertThat(retrieved.seqNoPrimaryTerm.sequenceNumber()).isNotNull();
assertThat(retrieved.seqNoPrimaryTerm.sequenceNumber()).isNotNegative();
assertThat(retrieved.seqNoPrimaryTerm.primaryTerm()).isNotNull();
assertThat(retrieved.seqNoPrimaryTerm.primaryTerm()).isPositive();
}
@Test // DATAES-799
@ -3197,15 +3193,12 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
Query query = getQueryForParentId("answer", qId1, null);
SearchHits<SampleJoinEntity> hits = operations.search(query, SampleJoinEntity.class);
List<String> hitIds = hits.getSearchHits().stream()
.map(sampleJoinEntitySearchHit -> sampleJoinEntitySearchHit.getId()).collect(Collectors.toList());
List<String> hitIds = hits.getSearchHits().stream().map(SearchHit::getId).collect(Collectors.toList());
assertThat(hitIds.size()).isEqualTo(2);
assertThat(hitIds.containsAll(Arrays.asList(aId1, aId2))).isTrue();
hits.forEach(searchHit -> {
assertThat(searchHit.getRouting()).isEqualTo(qId1);
});
hits.forEach(searchHit -> assertThat(searchHit.getRouting()).isEqualTo(qId1));
}
private void shouldUpdateEntityWithJoinFields(String qId1, String qId2, String aId1, String aId2) throws Exception {
@ -3225,23 +3218,13 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
SearchHits<SampleJoinEntity> updatedHits = operations.search(getQueryForParentId("answer", qId2, null),
SampleJoinEntity.class);
List<String> hitIds = updatedHits.getSearchHits().stream().map(new Function<SearchHit<SampleJoinEntity>, String>() {
@Override
public String apply(SearchHit<SampleJoinEntity> sampleJoinEntitySearchHit) {
return sampleJoinEntitySearchHit.getId();
}
}).collect(Collectors.toList());
List<String> hitIds = updatedHits.getSearchHits().stream().map(SearchHit::getId).collect(Collectors.toList());
assertThat(hitIds.size()).isEqualTo(1);
assertThat(hitIds.get(0)).isEqualTo(aId2);
updatedHits = operations.search(getQueryForParentId("answer", qId1, null), SampleJoinEntity.class);
hitIds = updatedHits.getSearchHits().stream().map(new Function<SearchHit<SampleJoinEntity>, String>() {
@Override
public String apply(SearchHit<SampleJoinEntity> sampleJoinEntitySearchHit) {
return sampleJoinEntitySearchHit.getId();
}
}).collect(Collectors.toList());
hitIds = updatedHits.getSearchHits().stream().map(SearchHit::getId).collect(Collectors.toList());
assertThat(hitIds.size()).isEqualTo(1);
assertThat(hitIds.get(0)).isEqualTo(aId1);
}
@ -3254,12 +3237,11 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
SearchHits<SampleJoinEntity> deletedHits = operations.search(getQueryForParentId("answer", qId2, null),
SampleJoinEntity.class);
List<String> hitIds = deletedHits.getSearchHits().stream()
.map(sampleJoinEntitySearchHit -> sampleJoinEntitySearchHit.getId()).collect(Collectors.toList());
List<String> hitIds = deletedHits.getSearchHits().stream().map(SearchHit::getId).collect(Collectors.toList());
assertThat(hitIds.size()).isEqualTo(0);
}
private org.springframework.data.elasticsearch.core.document.Document toDocument(JoinField joinField) {
private org.springframework.data.elasticsearch.core.document.Document toDocument(JoinField<?> joinField) {
org.springframework.data.elasticsearch.core.document.Document document = create();
document.put("name", joinField.getName());
document.put("parent", joinField.getParent());
@ -3487,9 +3469,10 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
@DisplayName("should index document from source with version")
void shouldIndexDocumentFromSourceWithVersion() {
String source = "{\n" + //
" \"answer\": 42\n" + //
"}";
String source = """
{
"answer": 42
}""";
IndexQuery query = new IndexQueryBuilder() //
.withId("42") //
.withSource(source) //
@ -3506,9 +3489,7 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
Sort.Order order = new Sort.Order(Sort.Direction.ASC, "unmappedField");
Query query = operations.matchAllQuery().addSort(Sort.by(order));
assertThatThrownBy(() -> {
operations.search(query, SampleEntity.class);
});
assertThatThrownBy(() -> operations.search(query, SampleEntity.class));
}
@Test // #1945
@ -3680,17 +3661,17 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
return false;
if (available != that.available)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
if (!Objects.equals(id, that.id))
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
if (!Objects.equals(type, that.type))
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
if (!Objects.equals(message, that.message))
return false;
if (scriptedRate != null ? !scriptedRate.equals(that.scriptedRate) : that.scriptedRate != null)
if (!Objects.equals(scriptedRate, that.scriptedRate))
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
if (!Objects.equals(location, that.location))
return false;
return version != null ? version.equals(that.version) : that.version == null;
return Objects.equals(version, that.version);
}
@Override
@ -4392,7 +4373,7 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
return false;
if (!text.equals(that.text))
return false;
return seqNoPrimaryTerm != null ? seqNoPrimaryTerm.equals(that.seqNoPrimaryTerm) : that.seqNoPrimaryTerm == null;
return Objects.equals(seqNoPrimaryTerm, that.seqNoPrimaryTerm);
}
@Override
@ -4450,7 +4431,7 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
return false;
if (!id.equals(that.id))
return false;
return scriptedRate != null ? scriptedRate.equals(that.scriptedRate) : that.scriptedRate == null;
return Objects.equals(scriptedRate, that.scriptedRate);
}
@Override

View File

@ -23,6 +23,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchResponse;
@ -478,9 +479,9 @@ abstract class ElasticsearchTemplateCallbackTests {
Person person = (Person) o;
if (id != null ? !id.equals(person.id) : person.id != null)
if (!Objects.equals(id, person.id))
return false;
return firstname != null ? firstname.equals(person.firstname) : person.firstname == null;
return Objects.equals(firstname, person.firstname);
}
@Override

View File

@ -35,6 +35,7 @@ import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
@ -186,16 +187,12 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
operations.save(map, IndexCoordinates.of(indexNameProvider.indexName())) //
.as(StepVerifier::create) //
.consumeNextWith(actual -> {
assertThat(map).containsKey("id");
}).verifyComplete();
.consumeNextWith(actual -> assertThat(map).containsKey("id")).verifyComplete();
}
@Test // DATAES-504
public void insertShouldErrorOnNullEntity() {
assertThatThrownBy(() -> {
operations.save(null);
}).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> operations.save(null)).isInstanceOf(IllegalArgumentException.class);
}
@Test // DATAES-519, DATAES-767, DATAES-822
@ -247,9 +244,7 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
@Test // DATAES-504
public void getByIdShouldErrorForNullId() {
assertThatThrownBy(() -> {
operations.get(null, SampleEntity.class);
}).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> operations.get(null, SampleEntity.class)).isInstanceOf(IllegalArgumentException.class);
}
@Test // DATAES-504
@ -369,9 +364,7 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
operations.search(query, SampleEntity.class) //
.map(SearchHit::getContent) //
.as(StepVerifier::create) //
.assertNext(next -> {
assertThat(next.getMessage()).isEqualTo("test message");
}) //
.assertNext(next -> assertThat(next.getMessage()).isEqualTo("test message")) //
.verifyComplete();
}
@ -494,9 +487,7 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
operations.aggregate(query, SampleEntity.class) //
.as(StepVerifier::create) //
.consumeNextWith(aggregationContainer -> {
assertThatAggregationsAreCorrect(aggregationContainer);
}).verifyComplete();
.consumeNextWith(this::assertThatAggregationsAreCorrect).verifyComplete();
}
protected abstract <A extends AggregationContainer<?>> void assertThatAggregationsAreCorrect(A aggregationContainer);
@ -603,9 +594,7 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
operations.delete(query, SampleEntity.class) //
.as(StepVerifier::create) //
.consumeNextWith(byQueryResponse -> {
assertThat(byQueryResponse.getDeleted()).isEqualTo(0L);
}).verifyComplete();
.consumeNextWith(byQueryResponse -> assertThat(byQueryResponse.getDeleted()).isEqualTo(0L)).verifyComplete();
}
@Test // DATAES-547
@ -721,11 +710,9 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
assertThat(sortValues).hasSize(1);
// old client returns Integer, new ElasticsearchClient String
java.lang.Object o = sortValues.get(0);
if (o instanceof Integer) {
Integer i = (Integer) o;
if (o instanceof Integer i) {
assertThat(o).isInstanceOf(Integer.class).isEqualTo(42);
} else if (o instanceof Long) {
Long l = (Long) o;
} else if (o instanceof Long l) {
assertThat(o).isInstanceOf(Long.class).isEqualTo(42L);
} else if (o instanceof String) {
assertThat(o).isInstanceOf(String.class).isEqualTo("42");
@ -849,10 +836,10 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
private void assertThatSeqNoPrimaryTermIsFilled(OptimisticEntity retrieved) {
assertThat(retrieved.seqNoPrimaryTerm).isNotNull();
assertThat(retrieved.seqNoPrimaryTerm.getSequenceNumber()).isNotNull();
assertThat(retrieved.seqNoPrimaryTerm.getSequenceNumber()).isNotNegative();
assertThat(retrieved.seqNoPrimaryTerm.getPrimaryTerm()).isNotNull();
assertThat(retrieved.seqNoPrimaryTerm.getPrimaryTerm()).isPositive();
assertThat(retrieved.seqNoPrimaryTerm.sequenceNumber()).isNotNull();
assertThat(retrieved.seqNoPrimaryTerm.sequenceNumber()).isNotNegative();
assertThat(retrieved.seqNoPrimaryTerm.primaryTerm()).isNotNull();
assertThat(retrieved.seqNoPrimaryTerm.primaryTerm()).isPositive();
}
@Test // DATAES-799, #1678
@ -1134,9 +1121,7 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
}).verifyComplete();
operations.get(savedEntity.get().getId(), ImmutableEntity.class).as(StepVerifier::create)
.consumeNextWith(retrieved -> {
assertThat(retrieved).isEqualTo(savedEntity.get());
}).verifyComplete();
.consumeNextWith(retrieved -> assertThat(retrieved).isEqualTo(savedEntity.get())).verifyComplete();
}
@Test // #2015
@ -1243,7 +1228,7 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
Message message1 = (Message) o;
return message != null ? message.equals(message1.message) : message1.message == null;
return Objects.equals(message, message1.message);
}
@Override
@ -1311,13 +1296,13 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
if (rate != that.rate) {
return false;
}
if (id != null ? !id.equals(that.id) : that.id != null) {
if (!Objects.equals(id, that.id)) {
return false;
}
if (message != null ? !message.equals(that.message) : that.message != null) {
if (!Objects.equals(message, that.message)) {
return false;
}
return version != null ? version.equals(that.version) : that.version == null;
return Objects.equals(version, that.version);
}
@Override
@ -1496,7 +1481,7 @@ public abstract class ReactiveElasticsearchIntegrationTests implements NewElasti
if (!text.equals(that.text)) {
return false;
}
return seqNoPrimaryTerm != null ? seqNoPrimaryTerm.equals(that.seqNoPrimaryTerm) : that.seqNoPrimaryTerm == null;
return Objects.equals(seqNoPrimaryTerm, that.seqNoPrimaryTerm);
}
@Override

View File

@ -26,6 +26,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.lucene.search.TotalHits;
@ -415,9 +416,9 @@ public class ReactiveElasticsearchTemplateCallbackTests {
Person person = (Person) o;
if (id != null ? !id.equals(person.id) : person.id != null)
if (!Objects.equals(id, person.id))
return false;
return firstname != null ? firstname.equals(person.firstname) : person.firstname == null;
return Objects.equals(firstname, person.firstname);
}
@Override

View File

@ -31,20 +31,22 @@ class ReactiveResourceUtilTest {
@Test
void shouldReadFromClasspath() {
String expected = "{\n" + //
" \"index\": {\n" + //
" \"number_of_shards\": \"1\",\n" + //
" \"number_of_replicas\": \"0\",\n" + //
" \"analysis\": {\n" + //
" \"analyzer\": {\n" + //
" \"emailAnalyzer\": {\n" + //
" \"type\": \"custom\",\n" + //
" \"tokenizer\": \"uax_url_email\"\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"index": {
"number_of_shards": "1",
"number_of_replicas": "0",
"analysis": {
"analyzer": {
"emailAnalyzer": {
"type": "custom",
"tokenizer": "uax_url_email"
}
}
}
}
}
"""; //
ReactiveResourceUtil.readFileFromClasspath("/settings/test-settings.json") //
.as(StepVerifier::create) //

View File

@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
@ -202,13 +203,13 @@ public abstract class SearchAsYouTypeIntegrationTests {
SearchAsYouTypeEntity that = (SearchAsYouTypeEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null) {
if (!Objects.equals(id, that.id)) {
return false;
}
if (name != null ? !name.equals(that.name) : that.name != null) {
if (!Objects.equals(name, that.name)) {
return false;
}
return suggest != null ? suggest.equals(that.suggest) : that.suggest == null;
return Objects.equals(suggest, that.suggest);
}
@Override

View File

@ -85,7 +85,7 @@ public class StreamQueriesTest {
}
private SearchHit<String> getOneSearchHit() {
return new SearchHit<String>(null, null, null, 0, null, null, null, null, null, null, "one");
return new SearchHit<>(null, null, null, 0, null, null, null, null, null, null, "one");
}
@Test // DATAES-766
@ -125,7 +125,7 @@ public class StreamQueriesTest {
0, //
searchScrollHitsIterator.next(), //
scrollId -> searchScrollHitsIterator.next(), //
scrollIds -> clearedScrollIds.addAll(scrollIds));
clearedScrollIds::addAll);
while (iterator.hasNext()) {
iterator.next();
@ -180,6 +180,6 @@ public class StreamQueriesTest {
}
private SearchScrollHits<String> newSearchScrollHits(List<SearchHit<String>> hits, String scrollId) {
return new SearchHitsImpl<String>(hits.size(), TotalHitsRelation.EQUAL_TO, 0, scrollId, hits, null, null);
return new SearchHitsImpl<>(hits.size(), TotalHitsRelation.EQUAL_TO, 0, scrollId, hits, null, null);
}
}

View File

@ -84,9 +84,8 @@ public class AggregationERHLCIntegrationTests extends AggregationIntegrationTest
assertThat(aggregations.asMap().get(aggsName)).isNotNull();
Aggregation keyword_bucket_stats = aggregations.asMap().get(pipelineAggsName);
assertThat(keyword_bucket_stats).isInstanceOf(StatsBucket.class);
if (keyword_bucket_stats instanceof ParsedStatsBucket) {
if (keyword_bucket_stats instanceof ParsedStatsBucket statsBucket) {
// Rest client
ParsedStatsBucket statsBucket = (ParsedStatsBucket) keyword_bucket_stats;
assertThat(statsBucket.getMin()).isEqualTo(1.0);
assertThat(statsBucket.getMax()).isEqualTo(3.0);
assertThat(statsBucket.getAvg()).isEqualTo(2.0);

View File

@ -60,10 +60,11 @@ class GeoConvertersUnitTests {
@DisplayName("should be converted to a Map")
void shouldBeConvertedToAMap() throws JSONException {
String expected = "{\n" + //
" \"type\": \"Point\",\n" + //
" \"coordinates\": [12.0, 34.0]\n" + //
"}"; //
String expected = """
{
"type": "Point",
"coordinates": [12.0, 34.0]
}"""; //
GeoJsonPoint geoJsonPoint = GeoJsonPoint.of(12, 34);
Map<String, Object> map = geoJsonToMapConverter.convert(geoJsonPoint);
@ -77,10 +78,11 @@ class GeoConvertersUnitTests {
void shouldBeConvertedFromAMap() {
// make sure we can read int values as well
String json = "{\n" + //
" \"type\": \"point\",\n" + //
" \"coordinates\": [12, 34.0]\n" + //
"}"; //
String json = """
{
"type": "point",
"coordinates": [12, 34.0]
}"""; //
Document document = Document.parse(json);
GeoJsonPoint expected = GeoJsonPoint.of(12, 34);
@ -99,13 +101,15 @@ class GeoConvertersUnitTests {
@DisplayName("should be converted to a Map")
void shouldBeConvertedToAMap() throws JSONException {
String expected = "{\n" + //
" \"type\": \"MultiPoint\",\n" + //
" \"coordinates\": [\n" + //
" [12.0, 34.0],\n" + //
" [56.0, 78.0]\n" + //
" ]\n" + //
"}\n"; //
String expected = """
{
"type": "MultiPoint",
"coordinates": [
[12.0, 34.0],
[56.0, 78.0]
]
}
"""; //
GeoJsonMultiPoint geoJsonMultiPoint = GeoJsonMultiPoint.of(new Point(12, 34), new Point(56, 78));
@ -120,13 +124,15 @@ class GeoConvertersUnitTests {
void shouldBeConvertedFromAMap() {
// make sure we can read int values as well
String json = "{\n" + //
" \"type\": \"multipoint\",\n" //
+ " \"coordinates\": [\n" + //
" [12.0, 34],\n" + //
" [56, 78.0]\n" + //
" ]\n" + //
"}\n"; //
String json = """
{
"type": "multipoint",
"coordinates": [
[12.0, 34],
[56, 78.0]
]
}
"""; //
Document document = Document.parse(json);
@ -145,13 +151,15 @@ class GeoConvertersUnitTests {
@DisplayName("should be converted to a Map")
void shouldBeConvertedToAMap() throws JSONException {
String expected = "{\n" + //
" \"type\": \"LineString\",\n" + //
" \"coordinates\": [\n" + //
" [12.0, 34.0],\n" + //
" [56.0, 78.0]\n" + //
" ]\n" + //
"}\n"; //
String expected = """
{
"type": "LineString",
"coordinates": [
[12.0, 34.0],
[56.0, 78.0]
]
}
"""; //
GeoJsonLineString geoJsonLineString = GeoJsonLineString.of(new Point(12, 34), new Point(56, 78));
@ -166,13 +174,15 @@ class GeoConvertersUnitTests {
void shouldBeConvertedFromAMap() {
// make sure we can read int values as well
String json = "{\n" + //
" \"type\": \"linestring\",\n" + //
" \"coordinates\": [\n" + //
" [12.0, 34],\n" + //
" [56, 78.0]\n" //
+ " ]\n" //
+ "}\n"; //
String json = """
{
"type": "linestring",
"coordinates": [
[12.0, 34],
[56, 78.0]
]
}
"""; //
Document document = Document.parse(json);
GeoJsonLineString expected = GeoJsonLineString.of(new Point(12, 34), new Point(56, 78));
@ -189,13 +199,15 @@ class GeoConvertersUnitTests {
@Test // DATAES-930
@DisplayName("should be converted to a Map")
void shouldBeConvertedToAMap() throws JSONException {
String expected = "{\n" + //
" \"type\": \"MultiLineString\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34.0], [56.0, 78.0]],\n" + //
" [[90.0, 12.0], [34.0, 56.0]]\n" + //
" ]\n" + //
"}\n"; //
String expected = """
{
"type": "MultiLineString",
"coordinates": [
[[12.0, 34.0], [56.0, 78.0]],
[[90.0, 12.0], [34.0, 56.0]]
]
}
"""; //
List<GeoJsonLineString> lines = Arrays.asList( //
GeoJsonLineString.of(new Point(12, 34), new Point(56, 78)), //
@ -213,13 +225,15 @@ class GeoConvertersUnitTests {
@DisplayName("should be converted from a Map")
void shouldBeConvertedFromAMap() {
// make sure we can read int values as well
String json = "{\n" + //
" \"type\": \"multilinestring\",\n" + //
" \"coordinates\": [\n" + //
" [[12, 34.0], [56.0, 78]],\n" + //
" [[90.0, 12], [34, 56.0]]\n" + //
" ]\n" + //
"}\n"; //
String json = """
{
"type": "multilinestring",
"coordinates": [
[[12, 34.0], [56.0, 78]],
[[90.0, 12], [34, 56.0]]
]
}
"""; //
Document document = Document.parse(json);
List<GeoJsonLineString> lines = Arrays.asList( //
GeoJsonLineString.of(new Point(12, 34), new Point(56, 78)), //
@ -240,13 +254,15 @@ class GeoConvertersUnitTests {
@Test // DATAES-930
@DisplayName("should be converted to a Map")
void shouldBeConvertedToAMap() throws JSONException {
String expected = "{\n" + //
" \"type\": \"Polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]],\n" + //
" [[56.0, 78.0], [90.0, 12.0], [34.0, 56.0], [56.0, 78.0]]\n" + //
" ]\n" + //
"}\n"; //
String expected = """
{
"type": "Polygon",
"coordinates": [
[[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]],
[[56.0, 78.0], [90.0, 12.0], [34.0, 56.0], [56.0, 78.0]]
]
}
"""; //
GeoJsonLineString polygonLineString = GeoJsonLineString.of(new Point(12, 34), new Point(56, 78),
new Point(90, 12), new Point(12, 34));
@ -264,13 +280,15 @@ class GeoConvertersUnitTests {
@DisplayName("should be converted from a Map")
void shouldBeConvertedFromAMap() {
String json = "{\n" + //
" \"type\": \"polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12, 34.0], [56.0, 78], [90, 12.0], [12, 34.0]],\n" + //
" [[56.0, 78], [90, 12.0], [34.0, 56], [56.0, 78]]\n" + //
" ]\n" + //
"}\n"; //
String json = """
{
"type": "polygon",
"coordinates": [
[[12, 34.0], [56.0, 78], [90, 12.0], [12, 34.0]],
[[56.0, 78], [90, 12.0], [34.0, 56], [56.0, 78]]
]
}
"""; //
Document document = Document.parse(json);
GeoJsonLineString polygonLineString = GeoJsonLineString.of(new Point(12, 34), new Point(56, 78),
new Point(90, 12), new Point(12, 34));
@ -291,13 +309,15 @@ class GeoConvertersUnitTests {
@Test // DATAES-390
@DisplayName("should be converted to a Map")
void shouldBeConvertedToAMap() throws JSONException {
String expected = "{\n" + //
" \"type\": \"MultiPolygon\",\n" + //
" \"coordinates\": [\n" + //
" [[[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]]],\n" + //
" [[[56.0, 78.0], [90.0, 12.0], [34.0, 56.0], [56.0, 78.0]]]\n" + //
" ]\n" + //
"}\n"; //
String expected = """
{
"type": "MultiPolygon",
"coordinates": [
[[[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]]],
[[[56.0, 78.0], [90.0, 12.0], [34.0, 56.0], [56.0, 78.0]]]
]
}
"""; //
GeoJsonLineString polygonLineString1 = GeoJsonLineString.of(new Point(12, 34), new Point(56, 78),
new Point(90, 12), new Point(12, 34));
@ -316,13 +336,15 @@ class GeoConvertersUnitTests {
@DisplayName("should be converted from a Map")
void shouldBeConvertedFromAMap() {
String json = "{\n" + //
" \"type\": \"multipolygon\",\n" + //
" \"coordinates\": [\n" + //
" [[[12, 34.0], [56.0, 78], [90, 12.0], [12, 34.0]]],\n" + //
" [[[56, 78.0], [90, 12.0], [34.0, 56], [56, 78.0]]]\n" + //
" ]\n" + //
"}\n"; //
String json = """
{
"type": "multipolygon",
"coordinates": [
[[[12, 34.0], [56.0, 78], [90, 12.0], [12, 34.0]]],
[[[56, 78.0], [90, 12.0], [34.0, 56], [56, 78.0]]]
]
}
"""; //
Document document = Document.parse(json);
GeoJsonLineString polygonLineString1 = GeoJsonLineString.of(new Point(12, 34), new Point(56, 78),
new Point(90, 12), new Point(12, 34));
@ -345,21 +367,23 @@ class GeoConvertersUnitTests {
@DisplayName("should be converted to a Map")
void shouldBeConvertedToAMap() throws JSONException {
String expected = "{\n" + //
" \"type\": \"GeometryCollection\",\n" + //
" \"geometries\": [\n" + //
" {\n" + //
" \"type\": \"Point\",\n" + //
" \"coordinates\": [12.0, 34.0]\n" + //
" },\n" + //
" {\n" + //
" \"type\": \"Polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]]\n" + //
" ]\n" + //
" }\n" + //
" ]\n" + //
"}\n"; //
String expected = """
{
"type": "GeometryCollection",
"geometries": [
{
"type": "Point",
"coordinates": [12.0, 34.0]
},
{
"type": "Polygon",
"coordinates": [
[[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]]
]
}
]
}
"""; //
GeoJsonPoint geoJsonPoint = GeoJsonPoint.of(12, 34);
GeoJsonPolygon geoJsonPolygon = GeoJsonPolygon
.of(GeoJsonLineString.of(new Point(12, 34), new Point(56, 78), new Point(90, 12), new Point(12, 34)));
@ -377,21 +401,23 @@ class GeoConvertersUnitTests {
@DisplayName("should be converted from a Map")
void shouldBeConvertedFromAMap() {
String json = "{\n" + //
" \"type\": \"geometrycollection\",\n" + //
" \"geometries\": [\n" + //
" {\n" + //
" \"type\": \"point\",\n" + //
" \"coordinates\": [12.0, 34.0]\n" + //
" },\n" + //
" {\n" + //
" \"type\": \"polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]]\n" + //
" ]\n" + //
" }\n" + //
" ]\n" + //
"}\n"; //
String json = """
{
"type": "geometrycollection",
"geometries": [
{
"type": "point",
"coordinates": [12.0, 34.0]
},
{
"type": "polygon",
"coordinates": [
[[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]]
]
}
]
}
"""; //
Document document = Document.parse(json);
GeoJsonPoint geoJsonPoint = GeoJsonPoint.of(12, 34);
GeoJsonPolygon geoJsonPolygon = GeoJsonPolygon

View File

@ -33,6 +33,7 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.json.JSONException;
import org.junit.jupiter.api.BeforeEach;
@ -74,7 +75,6 @@ import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Polygon;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
@ -237,7 +237,7 @@ public class MappingElasticsearchConverterUnitTests {
public void shouldReturnMappingContextWithWhichItWasInitialized() {
// given
MappingContext mappingContext = new SimpleElasticsearchMappingContext();
SimpleElasticsearchMappingContext mappingContext = new SimpleElasticsearchMappingContext();
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(mappingContext);
// then
@ -292,21 +292,23 @@ public class MappingElasticsearchConverterUnitTests {
String pointAsString = lat + "," + lon;
double[] pointAsArray = { lon, lat };
String expected = "{\n" + //
" \"pointA\": {\n" + //
" \"lon\": 5.0,\n" + //
" \"lat\": 48.0\n" + //
" },\n" + //
" \"pointB\": {\n" + //
" \"lon\": 5.0,\n" + //
" \"lat\": 48.0\n" + //
" },\n" + //
" \"pointC\": \"48.0,5.0\",\n" + //
" \"pointD\": [\n" + //
" 5.0,\n" + //
" 48.0\n" + //
" ]\n" + //
"}\n"; //
String expected = """
{
"pointA": {
"lon": 5.0,
"lat": 48.0
},
"pointB": {
"lon": 5.0,
"lat": 48.0
},
"pointC": "48.0,5.0",
"pointD": [
5.0,
48.0
]
}
"""; //
GeoEntity geoEntity = new GeoEntity();
geoEntity.setPointA(point);
@ -362,7 +364,7 @@ public class MappingElasticsearchConverterUnitTests {
sarahConnor.coWorkers = Arrays.asList(kyleReese, ginger);
Map<String, Object> target = writeToMap(sarahConnor);
assertThat((List) target.get("coWorkers")).hasSize(2).contains(kyleAsMap);
assertThat((List<Document>) target.get("coWorkers")).hasSize(2).contains(kyleAsMap);
}
@Test // DATAES-530
@ -374,7 +376,7 @@ public class MappingElasticsearchConverterUnitTests {
sarahConnor.inventoryList = Arrays.asList(gun, grenade);
Map<String, Object> target = writeToMap(sarahConnor);
assertThat((List) target.get("inventoryList")).containsExactly(gunAsMap, grenadeAsMap);
assertThat((List<Document>) target.get("inventoryList")).containsExactly(gunAsMap, grenadeAsMap);
}
@Test // DATAES-530
@ -425,8 +427,8 @@ public class MappingElasticsearchConverterUnitTests {
Map<String, Object> target = writeToMap(sarahConnor);
assertThat(target.get("inventoryMap")).isInstanceOf(Map.class);
assertThat((Map) target.get("inventoryMap")).containsEntry("glock19", gunAsMap).containsEntry("40 mm grenade",
grenadeAsMap);
assertThat((Map<String, Document>) target.get("inventoryMap")).containsEntry("glock19", gunAsMap)
.containsEntry("40 mm grenade", grenadeAsMap);
}
@Test // DATAES-530
@ -577,7 +579,7 @@ public class MappingElasticsearchConverterUnitTests {
t800.inventoryList = Collections.singletonList(rifle);
Map<String, Object> target = writeToMap(t800);
assertThat((List) target.get("inventoryList")).contains(rifleAsMap);
assertThat((List<Document>) target.get("inventoryList")).contains(rifleAsMap);
}
@Test // DATAES-530
@ -653,10 +655,12 @@ public class MappingElasticsearchConverterUnitTests {
LocalDatesEntity entity = new LocalDatesEntity();
entity.setId("4711");
entity.setDates(Arrays.asList(LocalDate.of(2020, 9, 15), LocalDate.of(2019, 5, 1)));
String expected = "{\n" + //
" \"id\": \"4711\",\n" + //
" \"dates\": [\"15.09.2020\", \"01.05.2019\"]\n" + //
"}\n"; //
String expected = """
{
"id": "4711",
"dates": ["15.09.2020", "01.05.2019"]
}
"""; //
Document document = Document.create();
mappingElasticsearchConverter.write(entity, document);
@ -806,19 +810,20 @@ public class MappingElasticsearchConverterUnitTests {
List<GeoPoint> locations = Arrays.asList(new GeoPoint(12.34, 23.45), new GeoPoint(34.56, 45.67));
entity.setLocations(locations);
String expected = "{\n" + //
" \"id\": \"42\",\n" + //
" \"locations\": [\n" + //
" {\n" + //
" \"lat\": 12.34,\n" + //
" \"lon\": 23.45\n" + //
" },\n" + //
" {\n" + //
" \"lat\": 34.56,\n" + //
" \"lon\": 45.67\n" + //
" }\n" + //
" ]\n" + //
"}"; //
String expected = """
{
"id": "42",
"locations": [
{
"lat": 12.34,
"lon": 23.45
},
{
"lat": 34.56,
"lon": 45.67
}
]
}"""; //
Document document = Document.create();
mappingElasticsearchConverter.write(entity, document);
@ -830,19 +835,20 @@ public class MappingElasticsearchConverterUnitTests {
@Test // DATAES-857
void shouldReadEntityWithListOfGeoPoints() {
String json = "{\n" + //
" \"id\": \"42\",\n" + //
" \"locations\": [\n" + //
" {\n" + //
" \"lat\": 12.34,\n" + //
" \"lon\": 23.45\n" + //
" },\n" + //
" {\n" + //
" \"lat\": 34.56,\n" + //
" \"lon\": 45.67\n" + //
" }\n" + //
" ]\n" + //
"}"; //
String json = """
{
"id": "42",
"locations": [
{
"lat": 12.34,
"lon": 23.45
},
{
"lat": 34.56,
"lon": 45.67
}
]
}"""; //
Document document = Document.parse(json);
@ -862,12 +868,14 @@ public class MappingElasticsearchConverterUnitTests {
entity.setId("42");
entity.setContent(map);
String expected = "{\n" + //
" \"id\": \"42\",\n" + //
" \"content\": {\n" + //
" \"foo\": \"bar\"\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"id": "42",
"content": {
"foo": "bar"
}
}
"""; //
Document document = Document.create();
@ -883,10 +891,12 @@ public class MappingElasticsearchConverterUnitTests {
EntityWithNullField entity = new EntityWithNullField();
entity.setId("42");
String expected = "{\n" + //
" \"id\": \"42\",\n" + //
" \"saved\": null\n" + //
"}\n"; //
String expected = """
{
"id": "42",
"saved": null
}
"""; //
Document document = Document.create();
@ -1132,121 +1142,123 @@ public class MappingElasticsearchConverterUnitTests {
@DisplayName("should write GeoJson properties")
void shouldWriteGeoJsonProperties() throws JSONException {
String json = "{\n" + //
" \"id\": \"42\",\n" + //
" \"point1\": {\n" + //
" \"type\": \"Point\",\n" + //
" \"coordinates\": [12.0, 34.0]\n" + //
" },\n" + //
" \"point2\": {\n" + //
" \"type\": \"Point\",\n" + //
" \"coordinates\": [56.0, 78.0]\n" + //
" },\n" + //
" \"multiPoint1\": {\n" + //
" \"type\": \"MultiPoint\",\n" + //
" \"coordinates\": [\n" + //
" [12.0, 34.0],\n" + //
" [56.0, 78.0],\n" + //
" [90.0, 12.0]\n" + //
" ]\n" + //
" },\n" + //
" \"multiPoint2\": {\n" + //
" \"type\": \"MultiPoint\",\n" + //
" \"coordinates\": [\n" + //
" [90.0, 12.0],\n" + //
" [56.0, 78.0],\n" + //
" [12.0, 34.0]\n" + //
" ]\n" + //
" },\n" + //
" \"lineString1\": {\n" + //
" \"type\": \"LineString\",\n" + //
" \"coordinates\": [\n" + //
" [12.0, 34.0],\n" + //
" [56.0, 78.0],\n" + //
" [90.0, 12.0]\n" + //
" ]\n" + //
" },\n" + //
" \"lineString2\": {\n" + //
" \"type\": \"LineString\",\n" + //
" \"coordinates\": [\n" + //
" [90.0, 12.0],\n" + //
" [56.0, 78.0],\n" + //
" [12.0, 34.0]\n" + //
" ]\n" + //
" },\n" + //
" \"multiLineString1\":{\n" + //
" \"type\": \"MultiLineString\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34.0], [56.0, 78.0]],\n" + //
" [[90.0, 12.0], [34.0, 56.0]]\n" + //
" ]\n" + //
" },\n" + //
" \"multiLineString2\":{\n" + //
" \"type\": \"MultiLineString\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34.0], [56.0, 78.0]],\n" + //
" [[90.0, 12.0], [34.0, 56.0]]\n" + //
" ]\n" + //
" },\n" + //
" \"polygon1\":{\n" + //
" \"type\": \"Polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34.0],[56.0, 78.0],[90.0, 12.0],[12.0, 34.0]],\n" + //
" [[21.0, 43.0],[65.0, 87.0],[9.0, 21.0],[21.0, 43.0]]\n" + //
" ]\n" + //
" },\n" + //
" \"polygon2\":{\n" + //
" \"type\": \"Polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34.0],[56.0, 78.0],[90.0, 12.0],[12.0, 34.0]],\n" + //
" [[21.0, 43.0],[65.0, 87.0],[9.0, 21.0],[21.0, 43.0]]\n" + //
" ]\n" + //
" },\n" + //
" \"multiPolygon1\":{\n" + //
" \"type\": \"MultiPolygon\",\n" + //
" \"coordinates\": [\n" + //
" [[[12.0, 34.0],[56.0, 78.0],[90.0, 12.0],[12.0, 34.0]]],\n" + //
" [[[21.0, 43.0],[65.0, 87.0],[9.0, 21.0],[21.0, 43.0]]]\n" + //
" ]\n" + //
" },\n" + //
" \"multiPolygon2\":{\n" + //
" \"type\": \"MultiPolygon\",\n" + //
" \"coordinates\": [\n" + //
" [[[12.0, 34.0],[56.0, 78.0],[90.0, 12.0],[12.0, 34.0]]],\n" + //
" [[[21.0, 43.0],[65.0, 87.0],[9.0, 21.0],[21.0, 43.0]]]\n" + //
" ]\n" + //
" },\n" + //
" \"geometryCollection1\": {\n" + //
" \"type\": \"GeometryCollection\",\n" + //
" \"geometries\": [\n" + //
" {\n" + //
" \"type\": \"Point\",\n" + //
" \"coordinates\": [12.0, 34.0]\n" + //
" },\n" + //
" {\n" + //
" \"type\": \"Polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]]\n" + //
" ]\n" + //
" }\n" + //
" ]\n" + //
" },\n" + //
" \"geometryCollection2\": {\n" + //
" \"type\": \"GeometryCollection\",\n" + //
" \"geometries\": [\n" + //
" {\n" + //
" \"type\": \"Point\",\n" + //
" \"coordinates\": [12.0, 34.0]\n" + //
" },\n" + //
" {\n" + //
" \"type\": \"Polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]]\n" + //
" ]\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String json = """
{
"id": "42",
"point1": {
"type": "Point",
"coordinates": [12.0, 34.0]
},
"point2": {
"type": "Point",
"coordinates": [56.0, 78.0]
},
"multiPoint1": {
"type": "MultiPoint",
"coordinates": [
[12.0, 34.0],
[56.0, 78.0],
[90.0, 12.0]
]
},
"multiPoint2": {
"type": "MultiPoint",
"coordinates": [
[90.0, 12.0],
[56.0, 78.0],
[12.0, 34.0]
]
},
"lineString1": {
"type": "LineString",
"coordinates": [
[12.0, 34.0],
[56.0, 78.0],
[90.0, 12.0]
]
},
"lineString2": {
"type": "LineString",
"coordinates": [
[90.0, 12.0],
[56.0, 78.0],
[12.0, 34.0]
]
},
"multiLineString1":{
"type": "MultiLineString",
"coordinates": [
[[12.0, 34.0], [56.0, 78.0]],
[[90.0, 12.0], [34.0, 56.0]]
]
},
"multiLineString2":{
"type": "MultiLineString",
"coordinates": [
[[12.0, 34.0], [56.0, 78.0]],
[[90.0, 12.0], [34.0, 56.0]]
]
},
"polygon1":{
"type": "Polygon",
"coordinates": [
[[12.0, 34.0],[56.0, 78.0],[90.0, 12.0],[12.0, 34.0]],
[[21.0, 43.0],[65.0, 87.0],[9.0, 21.0],[21.0, 43.0]]
]
},
"polygon2":{
"type": "Polygon",
"coordinates": [
[[12.0, 34.0],[56.0, 78.0],[90.0, 12.0],[12.0, 34.0]],
[[21.0, 43.0],[65.0, 87.0],[9.0, 21.0],[21.0, 43.0]]
]
},
"multiPolygon1":{
"type": "MultiPolygon",
"coordinates": [
[[[12.0, 34.0],[56.0, 78.0],[90.0, 12.0],[12.0, 34.0]]],
[[[21.0, 43.0],[65.0, 87.0],[9.0, 21.0],[21.0, 43.0]]]
]
},
"multiPolygon2":{
"type": "MultiPolygon",
"coordinates": [
[[[12.0, 34.0],[56.0, 78.0],[90.0, 12.0],[12.0, 34.0]]],
[[[21.0, 43.0],[65.0, 87.0],[9.0, 21.0],[21.0, 43.0]]]
]
},
"geometryCollection1": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Point",
"coordinates": [12.0, 34.0]
},
{
"type": "Polygon",
"coordinates": [
[[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]]
]
}
]
},
"geometryCollection2": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Point",
"coordinates": [12.0, 34.0]
},
{
"type": "Polygon",
"coordinates": [
[[12.0, 34.0], [56.0, 78.0], [90.0, 12.0], [12.0, 34.0]]
]
}
]
}
}
"""; //
Document document = Document.create();
@ -1260,121 +1272,123 @@ public class MappingElasticsearchConverterUnitTests {
void shouldReadGeoJsonProperties() {
// make sure we can read int values as well
String json = "{\n" + //
" \"id\": \"42\",\n" + //
" \"point1\": {\n" + //
" \"type\": \"Point\",\n" + //
" \"coordinates\": [12, 34]\n" + //
" },\n" + //
" \"point2\": {\n" + //
" \"type\": \"Point\",\n" + //
" \"coordinates\": [56, 78]\n" + //
" },\n" + //
" \"multiPoint1\": {\n" + //
" \"type\": \"MultiPoint\",\n" + //
" \"coordinates\": [\n" + //
" [12.0, 34],\n" + //
" [56, 78.0],\n" + //
" [90, 12.0]\n" + //
" ]\n" + //
" },\n" + //
" \"multiPoint2\": {\n" + //
" \"type\": \"MultiPoint\",\n" + //
" \"coordinates\": [\n" + //
" [90, 12.0],\n" + //
" [56, 78.0],\n" + //
" [12.0, 34]\n" + //
" ]\n" + //
" },\n" + //
" \"lineString1\": {\n" + //
" \"type\": \"LineString\",\n" + //
" \"coordinates\": [\n" + //
" [12.0, 34],\n" + //
" [56, 78.0],\n" + //
" [90, 12.0]\n" + //
" ]\n" + //
" },\n" + //
" \"lineString2\": {\n" + //
" \"type\": \"LineString\",\n" + //
" \"coordinates\": [\n" + //
" [90, 12.0],\n" + //
" [56, 78.0],\n" + //
" [12.0, 34]\n" + //
" ]\n" + //
" },\n" + //
" \"multiLineString1\":{\n" + //
" \"type\": \"MultiLineString\",\n" + //
" \"coordinates\": [\n" + //
" [[12, 34.0], [56, 78.0]],\n" + //
" [[90.0, 12], [34.0, 56]]\n" + //
" ]\n" + //
" },\n" + //
" \"multiLineString2\":{\n" + //
" \"type\": \"MultiLineString\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34], [56.0, 78]],\n" + //
" [[90, 12.0], [34, 56.0]]\n" + //
" ]\n" + //
" },\n" + //
" \"polygon1\":{\n" + //
" \"type\": \"Polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12, 34.0],[56.0, 78],[90, 12.0],[12.0, 34]],\n" + //
" [[21.0, 43],[65, 87.0],[9.0, 21],[21, 43.0]]\n" + //
" ]\n" + //
" },\n" + //
" \"polygon2\":{\n" + //
" \"type\": \"Polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12, 34.0],[56.0, 78],[90, 12.0],[12.0, 34]],\n" + //
" [[21.0, 43],[65, 87.0],[9.0, 21],[21, 43.0]]\n" + //
" ]\n" + //
" },\n" + //
" \"multiPolygon1\":{\n" + //
" \"type\": \"MultiPolygon\",\n" + //
" \"coordinates\": [\n" + //
" [[[12, 34.0],[56.0, 78],[90, 12.0],[12.0, 34]]],\n" + //
" [[[21.0, 43],[65, 87.0],[9.0, 21],[21, 43.0]]]\n" + //
" ]\n" + //
" },\n" + //
" \"multiPolygon2\":{\n" + //
" \"type\": \"MultiPolygon\",\n" + //
" \"coordinates\": [\n" + //
" [[[12, 34.0],[56.0, 78],[90, 12.0],[12.0, 34]]],\n" + //
" [[[21.0, 43],[65, 87.0],[9.0, 21],[21, 43.0]]]\n" + //
" ]\n" + //
" },\n" + //
" \"geometryCollection1\": {\n" + //
" \"type\": \"GeometryCollection\",\n" + //
" \"geometries\": [\n" + //
" {\n" + //
" \"type\": \"Point\",\n" + //
" \"coordinates\": [12, 34.0]\n" + //
" },\n" + //
" {\n" + //
" \"type\": \"Polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34], [56, 78.0], [90.0, 12], [12, 34.0]]\n" + //
" ]\n" + //
" }\n" + //
" ]\n" + //
" },\n" + //
" \"geometryCollection2\": {\n" + //
" \"type\": \"GeometryCollection\",\n" + //
" \"geometries\": [\n" + //
" {\n" + //
" \"type\": \"Point\",\n" + //
" \"coordinates\": [12, 34.0]\n" + //
" },\n" + //
" {\n" + //
" \"type\": \"Polygon\",\n" + //
" \"coordinates\": [\n" + //
" [[12.0, 34], [56, 78.0], [90.0, 12], [12, 34.0]]\n" + //
" ]\n" + //
" }\n" + //
" ]\n" + //
" }\n" + //
"}\n"; //
String json = """
{
"id": "42",
"point1": {
"type": "Point",
"coordinates": [12, 34]
},
"point2": {
"type": "Point",
"coordinates": [56, 78]
},
"multiPoint1": {
"type": "MultiPoint",
"coordinates": [
[12.0, 34],
[56, 78.0],
[90, 12.0]
]
},
"multiPoint2": {
"type": "MultiPoint",
"coordinates": [
[90, 12.0],
[56, 78.0],
[12.0, 34]
]
},
"lineString1": {
"type": "LineString",
"coordinates": [
[12.0, 34],
[56, 78.0],
[90, 12.0]
]
},
"lineString2": {
"type": "LineString",
"coordinates": [
[90, 12.0],
[56, 78.0],
[12.0, 34]
]
},
"multiLineString1":{
"type": "MultiLineString",
"coordinates": [
[[12, 34.0], [56, 78.0]],
[[90.0, 12], [34.0, 56]]
]
},
"multiLineString2":{
"type": "MultiLineString",
"coordinates": [
[[12.0, 34], [56.0, 78]],
[[90, 12.0], [34, 56.0]]
]
},
"polygon1":{
"type": "Polygon",
"coordinates": [
[[12, 34.0],[56.0, 78],[90, 12.0],[12.0, 34]],
[[21.0, 43],[65, 87.0],[9.0, 21],[21, 43.0]]
]
},
"polygon2":{
"type": "Polygon",
"coordinates": [
[[12, 34.0],[56.0, 78],[90, 12.0],[12.0, 34]],
[[21.0, 43],[65, 87.0],[9.0, 21],[21, 43.0]]
]
},
"multiPolygon1":{
"type": "MultiPolygon",
"coordinates": [
[[[12, 34.0],[56.0, 78],[90, 12.0],[12.0, 34]]],
[[[21.0, 43],[65, 87.0],[9.0, 21],[21, 43.0]]]
]
},
"multiPolygon2":{
"type": "MultiPolygon",
"coordinates": [
[[[12, 34.0],[56.0, 78],[90, 12.0],[12.0, 34]]],
[[[21.0, 43],[65, 87.0],[9.0, 21],[21, 43.0]]]
]
},
"geometryCollection1": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Point",
"coordinates": [12, 34.0]
},
{
"type": "Polygon",
"coordinates": [
[[12.0, 34], [56, 78.0], [90.0, 12], [12, 34.0]]
]
}
]
},
"geometryCollection2": {
"type": "GeometryCollection",
"geometries": [
{
"type": "Point",
"coordinates": [12, 34.0]
},
{
"type": "Polygon",
"coordinates": [
[[12.0, 34], [56, 78.0], [90.0, 12], [12, 34.0]]
]
}
]
}
}
"""; //
GeoJsonEntity mapped = mappingElasticsearchConverter.read(GeoJsonEntity.class, Document.parse(json));
@ -1396,20 +1410,22 @@ public class MappingElasticsearchConverterUnitTests {
car2.setModel("Porsche Taycan");
person.setCars(Arrays.asList(car1, car2));
String expected = "{\n" + //
" \"_class\": \"org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverterUnitTests$PersonWithCars\",\n"
+ " \"id\": \"42\",\n" + //
" \"name\": \"Smith\",\n" + //
" \"cars\": [\n" + //
" {\n" + //
" \"model\": \"Ford Mustang\"\n" + //
" },\n" + //
" {\n" + //
" \"_class\": \"org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverterUnitTests$ElectricCar\",\n"
+ " \"model\": \"Porsche Taycan\"\n" + //
" }\n" + //
" ]\n" + //
"}\n"; //
String expected = """
{
"_class": "org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverterUnitTests$PersonWithCars",
"id": "42",
"name": "Smith",
"cars": [
{
"model": "Ford Mustang"
},
{
"_class": "org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverterUnitTests$ElectricCar",
"model": "Porsche Taycan"
}
]
}
"""; //
Document document = Document.create();
@ -1432,18 +1448,20 @@ public class MappingElasticsearchConverterUnitTests {
car2.setModel("Porsche Taycan");
person.setCars(Arrays.asList(car1, car2));
String expected = "{\n" + //
" \"id\": \"42\",\n" + //
" \"name\": \"Smith\",\n" + //
" \"cars\": [\n" + //
" {\n" + //
" \"model\": \"Ford Mustang\"\n" + //
" },\n" + //
" {\n" + //
" \"model\": \"Porsche Taycan\"\n" + //
" }\n" + //
" ]\n" + //
"}\n"; //
String expected = """
{
"id": "42",
"name": "Smith",
"cars": [
{
"model": "Ford Mustang"
},
{
"model": "Porsche Taycan"
}
]
}
"""; //
Document document = Document.create();
@ -1462,12 +1480,14 @@ public class MappingElasticsearchConverterUnitTests {
entity.setFieldWithEnumBasedConverter("enumbased");
entity.setDontConvert("Monty Python's Flying Circus");
String expected = "{\n" + //
" \"id\": \"42\",\n" + //
" \"fieldWithClassBasedConverter\": \"desabssalc\",\n" + //
" \"fieldWithEnumBasedConverter\": \"desabmune\",\n" + //
" \"dontConvert\": \"Monty Python's Flying Circus\"\n" + //
"}\n"; //
String expected = """
{
"id": "42",
"fieldWithClassBasedConverter": "desabssalc",
"fieldWithEnumBasedConverter": "desabmune",
"dontConvert": "Monty Python's Flying Circus"
}
"""; //
Document document = Document.create();
@ -1480,12 +1500,14 @@ public class MappingElasticsearchConverterUnitTests {
@DisplayName("should read using ValueConverters")
void shouldReadUsingValueConverters() throws JSONException {
String json = "{\n" + //
" \"id\": \"42\",\n" + //
" \"fieldWithClassBasedConverter\": \"desabssalc\",\n" + //
" \"fieldWithEnumBasedConverter\": \"desabmune\",\n" + //
" \"dontConvert\": \"Monty Python's Flying Circus\"\n" + //
"}\n"; //
String json = """
{
"id": "42",
"fieldWithClassBasedConverter": "desabssalc",
"fieldWithEnumBasedConverter": "desabmune",
"dontConvert": "Monty Python's Flying Circus"
}
"""; //
Document source = Document.parse(json);
@ -1685,28 +1707,27 @@ public class MappingElasticsearchConverterUnitTests {
Person person = (Person) o;
if (id != null ? !id.equals(person.id) : person.id != null)
if (!Objects.equals(id, person.id))
return false;
if (name != null ? !name.equals(person.name) : person.name != null)
if (!Objects.equals(name, person.name))
return false;
if (firstName != null ? !firstName.equals(person.firstName) : person.firstName != null)
if (!Objects.equals(firstName, person.firstName))
return false;
if (lastName != null ? !lastName.equals(person.lastName) : person.lastName != null)
if (!Objects.equals(lastName, person.lastName))
return false;
if (birthDate != null ? !birthDate.equals(person.birthDate) : person.birthDate != null)
if (!Objects.equals(birthDate, person.birthDate))
return false;
if (gender != person.gender)
return false;
if (address != null ? !address.equals(person.address) : person.address != null)
if (!Objects.equals(address, person.address))
return false;
if (coWorkers != null ? !coWorkers.equals(person.coWorkers) : person.coWorkers != null)
if (!Objects.equals(coWorkers, person.coWorkers))
return false;
if (inventoryList != null ? !inventoryList.equals(person.inventoryList) : person.inventoryList != null)
if (!Objects.equals(inventoryList, person.inventoryList))
return false;
if (shippingAddresses != null ? !shippingAddresses.equals(person.shippingAddresses)
: person.shippingAddresses != null)
if (!Objects.equals(shippingAddresses, person.shippingAddresses))
return false;
return inventoryMap != null ? inventoryMap.equals(person.inventoryMap) : person.inventoryMap == null;
return Objects.equals(inventoryMap, person.inventoryMap);
}
@Override
@ -1827,11 +1848,9 @@ public class MappingElasticsearchConverterUnitTests {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Grenade))
if (!(o instanceof Grenade grenade))
return false;
Grenade grenade = (Grenade) o;
return label.equals(grenade.label);
}
@ -1863,11 +1882,9 @@ public class MappingElasticsearchConverterUnitTests {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Rifle))
if (!(o instanceof Rifle rifle))
return false;
Rifle rifle = (Rifle) o;
if (Double.compare(rifle.weight, weight) != 0)
return false;
if (maxShotsPerMagazine != rifle.maxShotsPerMagazine)
@ -1904,11 +1921,9 @@ public class MappingElasticsearchConverterUnitTests {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ShotGun))
if (!(o instanceof ShotGun shotGun))
return false;
ShotGun shotGun = (ShotGun) o;
return label.equals(shotGun.label);
}
@ -1954,16 +1969,14 @@ public class MappingElasticsearchConverterUnitTests {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Address))
if (!(o instanceof Address address))
return false;
Address address = (Address) o;
if (location != null ? !location.equals(address.location) : address.location != null)
if (!Objects.equals(location, address.location))
return false;
if (street != null ? !street.equals(address.street) : address.street != null)
if (!Objects.equals(street, address.street))
return false;
return city != null ? city.equals(address.city) : address.city == null;
return Objects.equals(city, address.city);
}
@Override
@ -1991,12 +2004,10 @@ public class MappingElasticsearchConverterUnitTests {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Place))
if (!(o instanceof Place place))
return false;
Place place = (Place) o;
return name != null ? name.equals(place.name) : place.name == null;
return Objects.equals(name, place.name);
}
@Override

View File

@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import java.time.LocalDateTime;
import java.util.Objects;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -142,13 +143,13 @@ class AuditingEntityCallbackTests {
Sample sample = (Sample) o;
if (id != null ? !id.equals(sample.id) : sample.id != null)
if (!Objects.equals(id, sample.id))
return false;
if (createdDate != null ? !createdDate.equals(sample.createdDate) : sample.createdDate != null)
if (!Objects.equals(createdDate, sample.createdDate))
return false;
if (createdBy != null ? !createdBy.equals(sample.createdBy) : sample.createdBy != null)
if (!Objects.equals(createdBy, sample.createdBy))
return false;
return modified != null ? modified.equals(sample.modified) : sample.modified == null;
return Objects.equals(modified, sample.modified);
}
@Override

View File

@ -29,7 +29,6 @@ import org.mockito.ArgumentCaptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.ReadOnlyProperty;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.JoinTypeRelation;
import org.springframework.data.elasticsearch.annotations.JoinTypeRelations;
@ -136,8 +135,8 @@ abstract class CallbackIntegrationTests {
assertThat(joinField.getName()).isEqualTo("answer");
assertThat(joinField.getParent()).isEqualTo("42");
assertThat(capturedIndexQuery.getRouting()).isEqualTo("42");
assertThat(capturedIndexQuery.getSeqNo()).isEqualTo(seqNoPrimaryTerm.getSequenceNumber());
assertThat(capturedIndexQuery.getPrimaryTerm()).isEqualTo(seqNoPrimaryTerm.getPrimaryTerm());
assertThat(capturedIndexQuery.getSeqNo()).isEqualTo(seqNoPrimaryTerm.sequenceNumber());
assertThat(capturedIndexQuery.getPrimaryTerm()).isEqualTo(seqNoPrimaryTerm.primaryTerm());
}
@Test // DATAES-972
@ -158,8 +157,8 @@ abstract class CallbackIntegrationTests {
assertThat(joinField.getName()).isEqualTo("answer");
assertThat(joinField.getParent()).isEqualTo("42");
assertThat(capturedIndexQuery.getRouting()).isEqualTo("42");
assertThat(capturedIndexQuery.getSeqNo()).isEqualTo(seqNoPrimaryTerm.getSequenceNumber());
assertThat(capturedIndexQuery.getPrimaryTerm()).isEqualTo(seqNoPrimaryTerm.getPrimaryTerm());
assertThat(capturedIndexQuery.getSeqNo()).isEqualTo(seqNoPrimaryTerm.sequenceNumber());
assertThat(capturedIndexQuery.getPrimaryTerm()).isEqualTo(seqNoPrimaryTerm.primaryTerm());
}
@Test // DATAES-972
@ -175,8 +174,8 @@ abstract class CallbackIntegrationTests {
indexQuery.setId(entity.getId());
indexQuery.setObject(entity);
indexQuery.setRouting("12");
indexQuery.setSeqNo(seqNoPrimaryTermOriginal.getSequenceNumber());
indexQuery.setPrimaryTerm(seqNoPrimaryTermOriginal.getPrimaryTerm());
indexQuery.setSeqNo(seqNoPrimaryTermOriginal.sequenceNumber());
indexQuery.setPrimaryTerm(seqNoPrimaryTermOriginal.primaryTerm());
operations.index(indexQuery, IndexCoordinates.of(indexNameProvider.indexName()));
@ -190,8 +189,8 @@ abstract class CallbackIntegrationTests {
assertThat(joinField.getName()).isEqualTo("answer");
assertThat(joinField.getParent()).isEqualTo("42");
assertThat(capturedIndexQuery.getRouting()).isEqualTo("12");
assertThat(capturedIndexQuery.getSeqNo()).isEqualTo(seqNoPrimaryTermOriginal.getSequenceNumber());
assertThat(capturedIndexQuery.getPrimaryTerm()).isEqualTo(seqNoPrimaryTermOriginal.getPrimaryTerm());
assertThat(capturedIndexQuery.getSeqNo()).isEqualTo(seqNoPrimaryTermOriginal.sequenceNumber());
assertThat(capturedIndexQuery.getPrimaryTerm()).isEqualTo(seqNoPrimaryTermOriginal.primaryTerm());
}
@Test // DATAES-972
@ -218,8 +217,8 @@ abstract class CallbackIntegrationTests {
assertThat(joinField.getName()).isEqualTo("answer");
assertThat(joinField.getParent()).isEqualTo("42");
assertThat(capturedIndexQuery.getRouting()).isEqualTo("42");
assertThat(capturedIndexQuery.getSeqNo()).isEqualTo(seqNoPrimaryTerm.getSequenceNumber());
assertThat(capturedIndexQuery.getPrimaryTerm()).isEqualTo(seqNoPrimaryTerm.getPrimaryTerm());
assertThat(capturedIndexQuery.getSeqNo()).isEqualTo(seqNoPrimaryTerm.sequenceNumber());
assertThat(capturedIndexQuery.getPrimaryTerm()).isEqualTo(seqNoPrimaryTerm.primaryTerm());
}
@Test // #2009

View File

@ -22,6 +22,7 @@ import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.time.LocalDateTime;
import java.util.Objects;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -144,13 +145,13 @@ class ReactiveAuditingEntityCallbackTests {
Sample sample = (Sample) o;
if (id != null ? !id.equals(sample.id) : sample.id != null)
if (!Objects.equals(id, sample.id))
return false;
if (createdDate != null ? !createdDate.equals(sample.createdDate) : sample.createdDate != null)
if (!Objects.equals(createdDate, sample.createdDate))
return false;
if (createdBy != null ? !createdBy.equals(sample.createdBy) : sample.createdBy != null)
if (!Objects.equals(createdBy, sample.createdBy))
return false;
return modified != null ? modified.equals(sample.modified) : sample.modified == null;
return Objects.equals(modified, sample.modified);
}
@Override

View File

@ -122,7 +122,7 @@ public abstract class GeoIntegrationTests implements NewElasticsearchClientDevel
LocationMarkerEntity location4 = new LocationMarkerEntity();
location4.setId("4");
location4.setName("location 4");
location4.setLocationAsArray(new double[] { -9.09882204680034d, 38.77353441278326d });
location4.setLocationAsArray(-9.09882204680034d, 38.77353441278326d);
indexQueries.add(buildIndex(location1));
indexQueries.add(buildIndex(location2));
@ -471,7 +471,7 @@ public abstract class GeoIntegrationTests implements NewElasticsearchClientDevel
return locationAsArray;
}
public void setLocationAsArray(double[] locationAsArray) {
public void setLocationAsArray(double... locationAsArray) {
this.locationAsArray = locationAsArray;
}

View File

@ -15,6 +15,8 @@
*/
package org.springframework.data.elasticsearch.core.geo;
import java.util.Objects;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.geo.Point;
@ -209,42 +211,38 @@ public class GeoJsonEntity {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof GeoJsonEntity))
if (!(o instanceof GeoJsonEntity that))
return false;
GeoJsonEntity that = (GeoJsonEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null)
if (!Objects.equals(id, that.id))
return false;
if (point1 != null ? !point1.equals(that.point1) : that.point1 != null)
if (!Objects.equals(point1, that.point1))
return false;
if (point2 != null ? !point2.equals(that.point2) : that.point2 != null)
if (!Objects.equals(point2, that.point2))
return false;
if (multiPoint1 != null ? !multiPoint1.equals(that.multiPoint1) : that.multiPoint1 != null)
if (!Objects.equals(multiPoint1, that.multiPoint1))
return false;
if (multiPoint2 != null ? !multiPoint2.equals(that.multiPoint2) : that.multiPoint2 != null)
if (!Objects.equals(multiPoint2, that.multiPoint2))
return false;
if (lineString1 != null ? !lineString1.equals(that.lineString1) : that.lineString1 != null)
if (!Objects.equals(lineString1, that.lineString1))
return false;
if (lineString2 != null ? !lineString2.equals(that.lineString2) : that.lineString2 != null)
if (!Objects.equals(lineString2, that.lineString2))
return false;
if (multiLineString1 != null ? !multiLineString1.equals(that.multiLineString1) : that.multiLineString1 != null)
if (!Objects.equals(multiLineString1, that.multiLineString1))
return false;
if (multiLineString2 != null ? !multiLineString2.equals(that.multiLineString2) : that.multiLineString2 != null)
if (!Objects.equals(multiLineString2, that.multiLineString2))
return false;
if (polygon1 != null ? !polygon1.equals(that.polygon1) : that.polygon1 != null)
if (!Objects.equals(polygon1, that.polygon1))
return false;
if (polygon2 != null ? !polygon2.equals(that.polygon2) : that.polygon2 != null)
if (!Objects.equals(polygon2, that.polygon2))
return false;
if (multiPolygon1 != null ? !multiPolygon1.equals(that.multiPolygon1) : that.multiPolygon1 != null)
if (!Objects.equals(multiPolygon1, that.multiPolygon1))
return false;
if (multiPolygon2 != null ? !multiPolygon2.equals(that.multiPolygon2) : that.multiPolygon2 != null)
if (!Objects.equals(multiPolygon2, that.multiPolygon2))
return false;
if (geometryCollection1 != null ? !geometryCollection1.equals(that.geometryCollection1)
: that.geometryCollection1 != null)
if (!Objects.equals(geometryCollection1, that.geometryCollection1))
return false;
return geometryCollection2 != null ? geometryCollection2.equals(that.geometryCollection2)
: that.geometryCollection2 == null;
return Objects.equals(geometryCollection2, that.geometryCollection2);
}
@Override

View File

@ -49,28 +49,29 @@ public class ReactiveMappingBuilderUnitTests extends MappingContextBaseTests {
ReactiveMappingBuilder mappingBuilder = getReactiveMappingBuilder();
String expected = "{\n" + //
" \"runtime\": {\n" + //
" \"day_of_week\": {\n" + //
" \"type\": \"keyword\",\n" + //
" \"script\": {\n" + //
" \"source\": \"emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))\"\n"
+ //
" }\n" + //
" }\n" + //
" },\n" + //
" \"properties\": {\n" + //
" \"_class\": {\n" + //
" \"type\": \"keyword\",\n" + //
" \"index\": false,\n" + //
" \"doc_values\": false\n" + //
" },\n" + //
" \"@timestamp\": {\n" + //
" \"type\": \"date\",\n" + //
" \"format\": \"epoch_millis\"\n" + //
" }\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"runtime": {
"day_of_week": {
"type": "keyword",
"script": {
"source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))"
}
}
},
"properties": {
"_class": {
"type": "keyword",
"index": false,
"doc_values": false
},
"@timestamp": {
"type": "date",
"format": "epoch_millis"
}
}
}
"""; //
String mapping = Mono.defer(() -> mappingBuilder.buildReactivePropertyMapping(RuntimeFieldEntity.class))
.subscribeOn(Schedulers.parallel()).block();

View File

@ -32,45 +32,75 @@ class SettingsUnitTests {
@DisplayName("should merge other Settings on this settings")
void shouldMergeOtherSettingsOnThisSettings() throws JSONException {
String thisSettingsJson = "{\n" + //
" \"index\": {\n" + //
" \"weather\": \"sunny\",\n" + //
" \"backup\": {\n" + //
" \"interval\": 5,\n" + //
" \"target\": {\n" + //
" \"type\":\"cloud\",\n" + //
" \"provider\": \"prov1\"\n" + //
" }\n" + //
" },\n" + //
" \"music\": \"The Eagles\"\n" + //
" }\n" + //
"}\n"; //
String otherSettingsJson = "{\n" + //
" \"index\": {\n" + //
" \"weather\": \"rainy\",\n" + //
" \"backup\": {\n" + //
" \"interval\": 13,\n" + //
" \"target\": {\n" + // " \"type\":\"cloud\",\n" + //
" \"provider\": \"prov2\"\n" + //
" }\n" + //
" },\n" + //
" \"drink\": \"wine\"\n" + //
" }\n" + //
"}\n"; //
String mergedSettingsJson = "{\n" + //
" \"index\": {\n" + //
" \"weather\": \"rainy\",\n" + //
" \"backup\": {\n" + //
" \"interval\": 13,\n" + //
" \"target\": {\n" + //
" \"type\":\"cloud\",\n" + //
" \"provider\": \"prov2\"\n" + //
" }\n" + //
" },\n" + //
" \"music\": \"The Eagles\",\n" + //
" \"drink\": \"wine\"\n" + //
" }\n" + //
"}\n"; //
String thisSettingsJson = """
{
"index": {
"weather": "sunny",
"backup": {
"interval": 5,
"target": {
"type":"cloud",
"provider": "prov1"
}
},
"music": "The Eagles"
}
}
"""; //
//
//
//
//
//
// " \"type\":\"cloud\",\n" + //
//
//
//
//
//
String otherSettingsJson = """
{
"index": {
"weather": "rainy",
"backup": {
"interval": 13,
"target": {
"provider": "prov2"
}
},
"drink": "wine"
}
}
"""; //
//
//
//
//
//
//
//
//
//
//
//
//
//
String mergedSettingsJson = """
{
"index": {
"weather": "rainy",
"backup": {
"interval": 13,
"target": {
"type":"cloud",
"provider": "prov2"
}
},
"music": "The Eagles",
"drink": "wine"
}
}
"""; //
Settings thisSettings = Settings.parse(thisSettingsJson);
Settings otherSettings = Settings.parse(otherSettingsJson);
@ -84,19 +114,21 @@ class SettingsUnitTests {
@DisplayName("should flatten its content")
void shouldFlattenItsContent() {
String settingsJson = "{\n" + //
" \"index\": {\n" + //
" \"weather\": \"sunny\",\n" + //
" \"backup\": {\n" + //
" \"interval\": 5,\n" + //
" \"target\": {\n" + //
" \"type\":\"cloud\",\n" + //
" \"provider\": \"prov1\"\n" + //
" }\n" + //
" },\n" + //
" \"music\": \"The Eagles\"\n" + //
" }\n" + //
"}\n"; //
String settingsJson = """
{
"index": {
"weather": "sunny",
"backup": {
"interval": 5,
"target": {
"type":"cloud",
"provider": "prov1"
}
},
"music": "The Eagles"
}
}
"""; //
Settings settings = Settings.parse(settingsJson);

View File

@ -111,14 +111,15 @@ public abstract class IndexOperationsIntegrationTests implements NewElasticsearc
softly.assertThat(aliasData.getSearchRouting()).isEqualTo("searchrouting");
softly.assertAll();
String expectedMappings = "{\n" + //
" \"properties\": {\n" + //
" \"email\": {\n" + //
" \"type\": \"text\",\n" + //
" \"analyzer\": \"emailAnalyzer\"\n" + //
" }\n" + //
" }\n" + //
"}"; //
String expectedMappings = """
{
"properties": {
"email": {
"type": "text",
"analyzer": "emailAnalyzer"
}
}
}"""; //
JSONAssert.assertEquals(expectedMappings, indexInformation.getMapping().toJson(), false);
}

View File

@ -44,7 +44,16 @@ import org.springframework.data.elasticsearch.annotations.Setting;
import org.springframework.data.elasticsearch.core.AbstractReactiveElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ReactiveIndexOperations;
import org.springframework.data.elasticsearch.core.index.*;
import org.springframework.data.elasticsearch.core.index.AliasAction;
import org.springframework.data.elasticsearch.core.index.AliasActionParameters;
import org.springframework.data.elasticsearch.core.index.AliasActions;
import org.springframework.data.elasticsearch.core.index.AliasData;
import org.springframework.data.elasticsearch.core.index.DeleteTemplateRequest;
import org.springframework.data.elasticsearch.core.index.ExistsTemplateRequest;
import org.springframework.data.elasticsearch.core.index.GetTemplateRequest;
import org.springframework.data.elasticsearch.core.index.PutTemplateRequest;
import org.springframework.data.elasticsearch.core.index.Settings;
import org.springframework.data.elasticsearch.core.index.TemplateData;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
@ -218,17 +227,19 @@ public abstract class ReactiveIndexOperationsIntegrationTests implements NewElas
@Test // DATAES-678
void shouldCreateMappingForEntityFromProperties() {
String expected = "{\n" + //
" \"properties\":{\n" + //
" \"text\": {\n" + //
" \"type\": \"text\"\n" + //
" },\n" + //
" \"publication-date\": {\n" + //
" \"type\": \"date\",\n" + //
" \"format\": \"basic_date\"\n" + //
" }\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"properties":{
"text": {
"type": "text"
},
"publication-date": {
"type": "date",
"format": "basic_date"
}
}
}
"""; //
indexOperations.createMapping(Entity.class) //
.as(StepVerifier::create) //
@ -245,14 +256,16 @@ public abstract class ReactiveIndexOperationsIntegrationTests implements NewElas
@Test // DATAES-678
void shouldCreateMappingForEntityFromMappingAnnotation() {
String expected = "{\n" + //
" \"properties\": {\n" + //
" \"email\": {\n" + //
" \"type\": \"text\",\n" + //
" \"analyzer\": \"emailAnalyzer\"\n" + //
" }\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"properties": {
"email": {
"type": "text",
"analyzer": "emailAnalyzer"
}
}
}
"""; //
indexOperations.createMapping(EntityWithAnnotatedSettingsAndMappings.class) //
.as(StepVerifier::create) //
@ -270,17 +283,19 @@ public abstract class ReactiveIndexOperationsIntegrationTests implements NewElas
void shouldCreateMappingBoundEntity() {
ReactiveIndexOperations indexOps = operations.indexOps(Entity.class);
String expected = "{\n" + //
" \"properties\":{\n" + //
" \"text\": {\n" + //
" \"type\": \"text\"\n" + //
" },\n" + //
" \"publication-date\": {\n" + //
" \"type\": \"date\",\n" + //
" \"format\": \"basic_date\"\n" + //
" }\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"properties":{
"text": {
"type": "text"
},
"publication-date": {
"type": "date",
"format": "basic_date"
}
}
}
"""; //
indexOps.createMapping() //
.as(StepVerifier::create) //
@ -299,17 +314,19 @@ public abstract class ReactiveIndexOperationsIntegrationTests implements NewElas
ReactiveIndexOperations indexOps = operations.indexOps(Entity.class);
String expected = "{\n" + //
" \"properties\":{\n" + //
" \"text\": {\n" + //
" \"type\": \"text\"\n" + //
" },\n" + //
" \"publication-date\": {\n" + //
" \"type\": \"date\",\n" + //
" \"format\": \"basic_date\"\n" + //
" }\n" + //
" }\n" + //
"}\n"; //
String expected = """
{
"properties":{
"text": {
"type": "text"
},
"publication-date": {
"type": "date",
"format": "basic_date"
}
}
}
"""; //
indexOps.create() //
.then(indexOps.putMapping()) //

View File

@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
@ -129,14 +130,12 @@ public abstract class EntityCustomConversionIntegrationTests {
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Entity))
if (!(o instanceof Entity entity))
return false;
Entity entity = (Entity) o;
if (value != null ? !value.equals(entity.value) : entity.value != null)
if (!Objects.equals(value, entity.value))
return false;
return location != null ? location.equals(entity.location) : entity.location == null;
return Objects.equals(location, entity.location);
}
@Override

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