Use Elasticsearch 8.2.2.

Original Pull Request #2174
Closes #2158
This commit is contained in:
Peter-Josef Meisch 2022-05-31 22:13:51 +02:00 committed by GitHub
parent c826adb152
commit ac64a6a733
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
42 changed files with 337 additions and 152 deletions

View File

@ -21,8 +21,8 @@
<!-- version of the RestHighLevelClient --> <!-- version of the RestHighLevelClient -->
<elasticsearch-rhlc>7.17.3</elasticsearch-rhlc> <elasticsearch-rhlc>7.17.3</elasticsearch-rhlc>
<!-- version of the new ElasticsearchClient --> <!-- version of the new ElasticsearchClient -->
<elasticsearch-java>7.17.3</elasticsearch-java> <elasticsearch-java>8.2.2</elasticsearch-java>
<log4j>2.17.1</log4j> <log4j>2.17.2</log4j>
<netty>4.1.65.Final</netty> <netty>4.1.65.Final</netty>
<springdata.commons>3.0.0-SNAPSHOT</springdata.commons> <springdata.commons>3.0.0-SNAPSHOT</springdata.commons>
<testcontainers>1.16.2</testcontainers> <testcontainers>1.16.2</testcontainers>

View File

@ -43,6 +43,7 @@ import org.apache.http.protocol.HttpContext;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RestHighLevelClientBuilder;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -132,7 +133,7 @@ public final class RestClients {
return clientBuilder; return clientBuilder;
}); });
RestHighLevelClient client = new RestHighLevelClient(builder); RestHighLevelClient client = new RestHighLevelClientBuilder(builder.build()).setApiCompatibilityMode(true).build();
return () -> client; return () -> client;
} }

View File

@ -19,6 +19,7 @@ import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper; import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport; import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.TransportOptions; import co.elastic.clients.transport.TransportOptions;
import co.elastic.clients.transport.Version;
import co.elastic.clients.transport.rest_client.RestClientOptions; import co.elastic.clients.transport.rest_client.RestClientOptions;
import co.elastic.clients.transport.rest_client.RestClientTransport; import co.elastic.clients.transport.rest_client.RestClientTransport;
@ -41,8 +42,10 @@ import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor; import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpContext;
import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
@ -242,6 +245,18 @@ public final class ElasticsearchClients {
TransportOptions.Builder transportOptionsBuilder = transportOptions != null ? transportOptions.toBuilder() TransportOptions.Builder transportOptionsBuilder = transportOptions != null ? transportOptions.toBuilder()
: new RestClientOptions(RequestOptions.DEFAULT).toBuilder(); : new RestClientOptions(RequestOptions.DEFAULT).toBuilder();
// need to add the compatibility header, this is only done automatically when not passing in custom options.
// code copied from RestClientTransport as it is not available outside the package
ContentType jsonContentType = null;
if (Version.VERSION == null) {
jsonContentType = ContentType.APPLICATION_JSON;
} else {
jsonContentType = ContentType.create("application/vnd.elasticsearch+json",
new BasicNameValuePair("compatible-with", String.valueOf(Version.VERSION.major())));
}
transportOptionsBuilder.addHeader("Accept", jsonContentType.toString());
TransportOptions transportOptionsWithHeader = transportOptionsBuilder TransportOptions transportOptionsWithHeader = transportOptionsBuilder
.addHeader(X_SPRING_DATA_ELASTICSEARCH_CLIENT, clientType).build(); .addHeader(X_SPRING_DATA_ELASTICSEARCH_CLIENT, clientType).build();

View File

@ -273,18 +273,18 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
// endregion // endregion
@Override @Override
protected String getClusterVersion() { public String getClusterVersion() {
return execute(client -> client.info().version().number()); return execute(client -> client.info().version().number());
} }
@Override @Override
protected String getVendor() { public String getVendor() {
return "Elasticsearch"; return "Elasticsearch";
} }
@Override @Override
protected String getRuntimeLibraryVersion() { public String getRuntimeLibraryVersion() {
return Version.VERSION.toString(); return Version.VERSION.toString();
} }

View File

@ -413,17 +413,17 @@ public class ReactiveElasticsearchTemplate extends AbstractReactiveElasticsearch
// endregion // endregion
@Override @Override
protected Mono<String> getVendor() { public Mono<String> getVendor() {
return Mono.just("Elasticsearch"); return Mono.just("Elasticsearch");
} }
@Override @Override
protected Mono<String> getRuntimeLibraryVersion() { public Mono<String> getRuntimeLibraryVersion() {
return Mono.just(Version.VERSION != null ? Version.VERSION.toString() : "null"); return Mono.just(Version.VERSION != null ? Version.VERSION.toString() : "null");
} }
@Override @Override
protected Mono<String> getClusterVersion() { public Mono<String> getClusterVersion() {
return Mono.from(execute(ReactiveElasticsearchClient::info)).map(infoResponse -> infoResponse.version().number()); return Mono.from(execute(ReactiveElasticsearchClient::info)).map(infoResponse -> infoResponse.version().number());
} }

View File

@ -820,7 +820,7 @@ class RequestConverter {
.refresh(reindexRequest.getRefresh()) // .refresh(reindexRequest.getRefresh()) //
.requireAlias(reindexRequest.getRequireAlias()) // .requireAlias(reindexRequest.getRequireAlias()) //
.requestsPerSecond(reindexRequest.getRequestsPerSecond()) // .requestsPerSecond(reindexRequest.getRequestsPerSecond()) //
.slices(reindexRequest.getSlices()); .slices(slices(reindexRequest.getSlices()));
return builder.build(); return builder.build();
} }
@ -963,24 +963,24 @@ class RequestConverter {
.pipeline(updateQuery.getPipeline()) // .pipeline(updateQuery.getPipeline()) //
.requestsPerSecond( .requestsPerSecond(
updateQuery.getRequestsPerSecond() != null ? updateQuery.getRequestsPerSecond().longValue() : null) // updateQuery.getRequestsPerSecond() != null ? updateQuery.getRequestsPerSecond().longValue() : null) //
.slices(updateQuery.getSlices() != null ? Long.valueOf(updateQuery.getSlices()) : null) // .slices(slices(updateQuery.getSlices() != null ? Long.valueOf(updateQuery.getSlices()) : null));
;
if (updateQuery.getAbortOnVersionConflict() != null) { if (updateQuery.getAbortOnVersionConflict() != null) {
ub.conflicts(updateQuery.getAbortOnVersionConflict() ? Conflicts.Abort : Conflicts.Proceed); ub.conflicts(updateQuery.getAbortOnVersionConflict() ? Conflicts.Abort : Conflicts.Proceed);
} }
if (updateQuery.getBatchSize() != null) {
ub.size(Long.valueOf(updateQuery.getBatchSize()));
}
if (updateQuery.getQuery() != null) { if (updateQuery.getQuery() != null) {
Query queryQuery = updateQuery.getQuery(); Query queryQuery = updateQuery.getQuery();
if (updateQuery.getBatchSize() != null) {
((BaseQuery) queryQuery).setMaxResults(updateQuery.getBatchSize());
}
ub.query(getQuery(queryQuery, null)); ub.query(getQuery(queryQuery, null));
// no indicesOptions available like in old client // no indicesOptions available like in old client
ub.scroll(time(queryQuery.getScrollTime())); ub.scroll(time(queryQuery.getScrollTime()));
} }
// no maxRetries available like in old client // no maxRetries available like in old client
@ -1164,11 +1164,11 @@ class RequestConverter {
if (!query.getRuntimeFields().isEmpty()) { if (!query.getRuntimeFields().isEmpty()) {
Map<String, RuntimeField> runtimeMappings = new HashMap<>(); Map<String, List<RuntimeField>> runtimeMappings = new HashMap<>();
query.getRuntimeFields().forEach(runtimeField -> { query.getRuntimeFields().forEach(runtimeField -> {
runtimeMappings.put(runtimeField.getName(), RuntimeField.of(rt -> rt // runtimeMappings.put(runtimeField.getName(), Collections.singletonList(RuntimeField.of(rt -> rt //
.type(RuntimeFieldType._DESERIALIZER.parse(runtimeField.getType())) // .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); builder.runtimeMappings(runtimeMappings);
} }
@ -1328,6 +1328,7 @@ class RequestConverter {
} else { } else {
throw new IllegalArgumentException("unhandled Query implementation " + query.getClass().getName()); throw new IllegalArgumentException("unhandled Query implementation " + query.getClass().getName());
} }
return esQuery; return esQuery;
} }

View File

@ -90,7 +90,7 @@ class ResponseConverter {
.withNumberOfPendingTasks(healthResponse.numberOfPendingTasks()) // .withNumberOfPendingTasks(healthResponse.numberOfPendingTasks()) //
.withRelocatingShards(healthResponse.relocatingShards()) // .withRelocatingShards(healthResponse.relocatingShards()) //
.withStatus(healthResponse.status().toString()) // .withStatus(healthResponse.status().toString()) //
.withTaskMaxWaitingTimeMillis(Long.parseLong(healthResponse.taskMaxWaitingInQueueMillis())) // .withTaskMaxWaitingTimeMillis(healthResponse.taskMaxWaitingInQueueMillis().toEpochMilli()) //
.withTimedOut(healthResponse.timedOut()) // .withTimedOut(healthResponse.timedOut()) //
.withUnassignedShards(healthResponse.unassignedShards()) // .withUnassignedShards(healthResponse.unassignedShards()) //
.build(); // .build(); //
@ -144,11 +144,11 @@ class ResponseConverter {
if (indexMappingRecord == null) { if (indexMappingRecord == null) {
if (mappings.size() != 1) { if (mappings.size() != 1) {
LOGGER.warn("no mapping returned for index {}", indexCoordinates.getIndexName()); LOGGER.warn("no mapping returned for index {}", indexCoordinates.getIndexName());
return Document.create(); return Document.create();
} }
String index = mappings.keySet().iterator().next(); String index = mappings.keySet().iterator().next();
indexMappingRecord = mappings.get(index); indexMappingRecord = mappings.get(index);
} }
return Document.parse(toJson(indexMappingRecord.mappings(), jsonpMapper)); return Document.parse(toJson(indexMappingRecord.mappings(), jsonpMapper));
@ -277,9 +277,9 @@ class ResponseConverter {
.withNoops(reindexResponse.noops()) // .withNoops(reindexResponse.noops()) //
.withBulkRetries(reindexResponse.retries().bulk()) // .withBulkRetries(reindexResponse.retries().bulk()) //
.withSearchRetries(reindexResponse.retries().search()) // .withSearchRetries(reindexResponse.retries().search()) //
.withThrottledMillis(Long.parseLong(reindexResponse.throttledMillis())) // .withThrottledMillis(reindexResponse.throttledMillis().toEpochMilli()) //
.withRequestsPerSecond(reindexResponse.requestsPerSecond()) // .withRequestsPerSecond(reindexResponse.requestsPerSecond()) //
.withThrottledUntilMillis(Long.parseLong(reindexResponse.throttledUntilMillis())).withFailures(failures) // .withThrottledUntilMillis(reindexResponse.throttledUntilMillis().toEpochMilli()).withFailures(failures) //
.build(); .build();
} }

View File

@ -18,7 +18,6 @@ package org.springframework.data.elasticsearch.client.elc;
import co.elastic.clients.elasticsearch._types.*; import co.elastic.clients.elasticsearch._types.*;
import co.elastic.clients.elasticsearch._types.mapping.FieldType; import co.elastic.clients.elasticsearch._types.mapping.FieldType;
import co.elastic.clients.elasticsearch.core.search.BoundaryScanner; import co.elastic.clients.elasticsearch.core.search.BoundaryScanner;
import co.elastic.clients.elasticsearch.core.search.BuiltinHighlighterType;
import co.elastic.clients.elasticsearch.core.search.HighlighterEncoder; import co.elastic.clients.elasticsearch.core.search.HighlighterEncoder;
import co.elastic.clients.elasticsearch.core.search.HighlighterFragmenter; import co.elastic.clients.elasticsearch.core.search.HighlighterFragmenter;
import co.elastic.clients.elasticsearch.core.search.HighlighterOrder; import co.elastic.clients.elasticsearch.core.search.HighlighterOrder;
@ -170,11 +169,11 @@ final class TypeUtils {
if (value != null) { if (value != null) {
switch (value.toLowerCase()) { switch (value.toLowerCase()) {
case "unified": case "unified":
return HighlighterType.of(b -> b.builtin(BuiltinHighlighterType.Unified)); return HighlighterType.Unified;
case "plain": case "plain":
return HighlighterType.of(b -> b.builtin(BuiltinHighlighterType.Plain)); return HighlighterType.Plain;
case "fvh": case "fvh":
return HighlighterType.of(b -> b.builtin(BuiltinHighlighterType.FastVector)); return HighlighterType.FastVector;
default: default:
return null; return null;
} }
@ -308,6 +307,16 @@ final class TypeUtils {
return null; return null;
} }
@Nullable
static Slices slices(@Nullable Long count) {
if (count == null) {
return null;
}
return Slices.of(s -> s.value(Math.toIntExact(count)));
}
@Nullable @Nullable
static SortMode sortMode(Order.Mode mode) { static SortMode sortMode(Order.Mode mode) {

View File

@ -257,6 +257,16 @@ public interface WebClientProvider {
if (suppliedHeaders != null && suppliedHeaders != HttpHeaders.EMPTY) { if (suppliedHeaders != null && suppliedHeaders != HttpHeaders.EMPTY) {
httpHeaders.addAll(suppliedHeaders); httpHeaders.addAll(suppliedHeaders);
} }
// this WebClientProvider is built with ES 7 and not used on 8 anymore
httpHeaders.add("Accept", "application/vnd.elasticsearch+json;compatible-with=7");
var contentTypeHeader = "Content-Type";
if (httpHeaders.containsKey(contentTypeHeader)) {
httpHeaders.remove(contentTypeHeader);
}
httpHeaders.add(contentTypeHeader, "application/vnd.elasticsearch+json;compatible-with=7");
})); }));
return provider; return provider;

View File

@ -145,8 +145,8 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
/** /**
* Set the {@link EntityCallbacks} instance to use when invoking {@link EntityCallbacks callbacks} like the * Set the {@link EntityCallbacks} instance to use when invoking {@link EntityCallbacks callbacks} like the
* {@link org.springframework.data.elasticsearch.core.event.BeforeConvertCallback}. * {@link org.springframework.data.elasticsearch.core.event.BeforeConvertCallback}. Overrides potentially existing
* Overrides potentially existing {@link EntityCallbacks}. * {@link EntityCallbacks}.
* *
* @param entityCallbacks must not be {@literal null}. * @param entityCallbacks must not be {@literal null}.
* @throws IllegalArgumentException if the given instance is {@literal null}. * @throws IllegalArgumentException if the given instance is {@literal null}.
@ -588,19 +588,19 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
* @return the version as string if it can be retrieved * @return the version as string if it can be retrieved
*/ */
@Nullable @Nullable
abstract protected String getClusterVersion(); public abstract String getClusterVersion();
/** /**
* @return the vendor name of the used cluster and client library * @return the vendor name of the used cluster and client library
* @since 4.3 * @since 4.3
*/ */
abstract protected String getVendor(); public abstract String getVendor();
/** /**
* @return the version of the used client runtime library. * @return the version of the used client runtime library.
* @since 4.3 * @since 4.3
*/ */
abstract protected String getRuntimeLibraryVersion(); public abstract String getRuntimeLibraryVersion();
// endregion // endregion

View File

@ -611,15 +611,15 @@ abstract public class AbstractReactiveElasticsearchTemplate
* @return the vendor name of the used cluster and client library * @return the vendor name of the used cluster and client library
* @since 4.3 * @since 4.3
*/ */
abstract protected Mono<String> getVendor(); public abstract Mono<String> getVendor();
/** /**
* @return the version of the used client runtime library. * @return the version of the used client runtime library.
* @since 4.3 * @since 4.3
*/ */
abstract protected Mono<String> getRuntimeLibraryVersion(); public abstract Mono<String> getRuntimeLibraryVersion();
abstract protected Mono<String> getClusterVersion(); public abstract Mono<String> getClusterVersion();
/** /**
* Value class to capture client independent information from a response to an index request. * Value class to capture client independent information from a response to an index request.

View File

@ -607,7 +607,7 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate {
// region helper methods // region helper methods
@Override @Override
protected String getClusterVersion() { public String getClusterVersion() {
try { try {
return execute(client -> client.info(RequestOptions.DEFAULT)).getVersion().getNumber(); return execute(client -> client.info(RequestOptions.DEFAULT)).getVersion().getNumber();
} catch (Exception ignored) {} } catch (Exception ignored) {}
@ -629,12 +629,12 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate {
} }
@Override @Override
protected String getVendor() { public String getVendor() {
return "Elasticsearch"; return "Elasticsearch";
} }
@Override @Override
protected String getRuntimeLibraryVersion() { public String getRuntimeLibraryVersion() {
return Version.CURRENT.toString(); return Version.CURRENT.toString();
} }

View File

@ -676,7 +676,7 @@ public class ReactiveElasticsearchTemplate extends AbstractReactiveElasticsearch
// region Helper methods // region Helper methods
@Override @Override
protected Mono<String> getClusterVersion() { public Mono<String> getClusterVersion() {
try { try {
return Mono.from(execute(ReactiveElasticsearchClient::info)) return Mono.from(execute(ReactiveElasticsearchClient::info))
.map(mainResponse -> mainResponse.getVersion().toString()); .map(mainResponse -> mainResponse.getVersion().toString());
@ -689,7 +689,7 @@ public class ReactiveElasticsearchTemplate extends AbstractReactiveElasticsearch
* @since 4.3 * @since 4.3
*/ */
@Override @Override
protected Mono<String> getVendor() { public Mono<String> getVendor() {
return Mono.just("Elasticsearch"); return Mono.just("Elasticsearch");
} }
@ -698,7 +698,7 @@ public class ReactiveElasticsearchTemplate extends AbstractReactiveElasticsearch
* @since 4.3 * @since 4.3
*/ */
@Override @Override
protected Mono<String> getRuntimeLibraryVersion() { public Mono<String> getRuntimeLibraryVersion() {
return Mono.just(Version.CURRENT.toString()); return Mono.just(Version.CURRENT.toString());
} }

View File

@ -510,36 +510,37 @@ public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntit
return new Settings(); return new Settings();
} }
Settings settings = new Settings() // var index = new Settings() //
.append("index.number_of_shards", String.valueOf(shards)) .append("number_of_shards", String.valueOf(shards)) //
.append("index.number_of_replicas", String.valueOf(replicas)); .append("number_of_replicas", String.valueOf(replicas));
if (refreshIntervall != null) { if (refreshIntervall != null) {
settings.append("index.refresh_interval", refreshIntervall); index.append("refresh_interval", refreshIntervall);
} }
if (indexStoreType != null) { if (indexStoreType != null) {
settings.append("index.store.type", indexStoreType); index.append("store", new Settings().append("type", indexStoreType));
} }
if (sortFields != null && sortFields.length > 0) { if (sortFields != null && sortFields.length > 0) {
settings.append("index.sort.field", sortFields); var sort = new Settings().append("field", sortFields);
if (sortOrders != null && sortOrders.length > 0) { if (sortOrders != null && sortOrders.length > 0) {
settings.append("index.sort.order", sortOrders); sort.append("order", sortOrders);
} }
if (sortModes != null && sortModes.length > 0) { if (sortModes != null && sortModes.length > 0) {
settings.append("index.sort.mode", sortModes); sort.append("mode", sortModes);
} }
if (sortMissingValues != null && sortMissingValues.length > 0) { if (sortMissingValues != null && sortMissingValues.length > 0) {
settings.append("index.sort.missing", sortMissingValues); sort.append("missing", sortMissingValues);
} }
index.append("sort", sort);
} }
return settings; // return new Settings().append("index", index); //
} }
} }

View File

@ -16,19 +16,17 @@
package org.springframework.data.elasticsearch; package org.springframework.data.elasticsearch;
/** /**
* TODO remove when the new Elasticsearch client is fully working * TODO remove when the new Elasticsearch client is fully working and the old client is removed
* *
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
*/ */
public interface NewElasticsearchClientDevelopment { public interface NewElasticsearchClientDevelopment {
boolean forceEnable = false; default boolean newElasticsearchClient() {
default boolean usesNewElasticsearchClient() {
return false; return false;
} }
default boolean newElasticsearchClient() { default boolean oldElasticsearchClient() {
return !forceEnable && usesNewElasticsearchClient(); return !newElasticsearchClient();
} }
} }

View File

@ -19,6 +19,9 @@ import static org.assertj.core.api.Assertions.*;
import co.elastic.clients.elasticsearch.ElasticsearchClient; import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue; import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.Script;
import co.elastic.clients.elasticsearch._types.mapping.RuntimeField;
import co.elastic.clients.elasticsearch._types.mapping.RuntimeFieldType;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping; import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch.cluster.HealthRequest; import co.elastic.clients.elasticsearch.cluster.HealthRequest;
import co.elastic.clients.elasticsearch.cluster.HealthResponse; import co.elastic.clients.elasticsearch.cluster.HealthResponse;
@ -36,6 +39,7 @@ import reactor.core.publisher.Mono;
import java.io.IOException; import java.io.IOException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Objects; import java.util.Objects;
import java.util.function.Function; import java.util.function.Function;
@ -83,22 +87,29 @@ public class DevTests {
ElasticsearchClient client = imperativeElasticsearchClient; ElasticsearchClient client = imperativeElasticsearchClient;
String index = "testindex"; String index = "testindex";
Person person = new Person("42", new Name("Ford", "Prefect")); var p = new Product("p1", 42.0);
if (LOGGER.isInfoEnabled()) { client.index(ir -> ir //
LOGGER.info(String.format("Person: %s", person)); .index(index)//
} .document(p));
IndexRequest<Object> indexRequest = IndexRequest.of(b -> b.index(index).id(person.id).document(person)); client.indices().flush(f -> f.index(index));
client.index(indexRequest); RuntimeField runtimeField = RuntimeField.of(rf -> rf //
client.search(srb -> srb.index(index).trackTotalHits(thb -> thb.enabled(false)), Person.class); .type(RuntimeFieldType.Double) //
.script(Script.of(s -> s //
.inline(i -> i. //
source("emit(doc['price'].value * 1.19)") //
) //
)) //
); //
ReactiveClient asyncClient = new ReactiveClient(client._transport()); client.search(sr -> sr //
.index(index) //
asyncClient.index(indexRequest).block(); .runtimeMappings("priceWithTax", Collections.singletonList(runtimeField)), //
Person.class); //
} }
static class ReactiveClient { static class ReactiveClient {
@ -113,6 +124,36 @@ public class DevTests {
} }
} }
static class Product {
@Nullable String id;
@Nullable Double price;
public Product() {}
public Product(@Nullable String id, @Nullable Double price) {
this.id = id;
this.price = price;
}
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public Double getPrice() {
return price;
}
public void setPrice(@Nullable Double price) {
this.price = price;
}
}
static class Person { static class Person {
@Nullable String id; @Nullable String id;
@Nullable Name name; @Nullable Name name;
@ -327,7 +368,7 @@ public class DevTests {
private ClientConfiguration clientConfiguration() { private ClientConfiguration clientConfiguration() {
return ClientConfiguration.builder() // return ClientConfiguration.builder() //
.connectedTo("localhost:9200")// .connectedTo("thranduil.local.:9200")//
.withBasicAuth("elastic", "hcraescitsale").withProxy("localhost:8080") // .withBasicAuth("elastic", "hcraescitsale").withProxy("localhost:8080") //
.withHeaders(() -> { .withHeaders(() -> {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();

View File

@ -61,7 +61,7 @@ public class ElasticsearchELCIntegrationTests extends ElasticsearchIntegrationTe
} }
@Override @Override
public boolean usesNewElasticsearchClient() { public boolean newElasticsearchClient() {
return true; return true;
} }

View File

@ -2783,6 +2783,7 @@ public abstract class ElasticsearchIntegrationTests implements NewElasticsearchC
assertThat(settings).doesNotContainKey("index.max_result_window"); assertThat(settings).doesNotContainKey("index.max_result_window");
} }
@DisabledIf(value = "newElasticsearchClient", disabledReason = "todo #2165, ES issue 286")
@Test // DATAES-709 @Test // DATAES-709
public void shouldIncludeDefaultsOnGetIndexSettings() { public void shouldIncludeDefaultsOnGetIndexSettings() {

View File

@ -56,6 +56,12 @@ public class ReactiveElasticsearchELCIntegrationTests extends ReactiveElasticsea
return new IndexNameProvider("reactive-template"); return new IndexNameProvider("reactive-template");
} }
} }
@Override
public boolean newElasticsearchClient() {
return true;
}
@Override @Override
protected Query getTermsAggsQuery(String aggsName, String aggsField) { protected Query getTermsAggsQuery(String aggsName, String aggsField) {
return ELCQueries.getTermsAggsQuery(aggsName, aggsField); return ELCQueries.getTermsAggsQuery(aggsName, aggsField);

View File

@ -45,6 +45,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIf;
import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
@ -54,6 +55,7 @@ import org.springframework.data.annotation.Version;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.NewElasticsearchClientDevelopment;
import org.springframework.data.elasticsearch.RestStatusException; import org.springframework.data.elasticsearch.RestStatusException;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
@ -88,7 +90,7 @@ import org.springframework.util.StringUtils;
*/ */
@SuppressWarnings("SpringJavaAutowiredMembersInspection") @SuppressWarnings("SpringJavaAutowiredMembersInspection")
@SpringIntegrationTest @SpringIntegrationTest
public abstract class ReactiveElasticsearchIntegrationTests { public abstract class ReactiveElasticsearchIntegrationTests implements NewElasticsearchClientDevelopment {
@Autowired private ReactiveElasticsearchOperations operations; @Autowired private ReactiveElasticsearchOperations operations;
@Autowired private IndexNameProvider indexNameProvider; @Autowired private IndexNameProvider indexNameProvider;
@ -1072,6 +1074,7 @@ public abstract class ReactiveElasticsearchIntegrationTests {
}).verifyComplete(); }).verifyComplete();
} }
@DisabledIf(value = "newElasticsearchClient", disabledReason = "todo #2165, ES issue 286")
@Test // #1646, #1718 @Test // #1646, #1718
@DisplayName("should return a list of info for specific index") @DisplayName("should return a list of info for specific index")
void shouldReturnInformationListOfAllIndices() { void shouldReturnInformationListOfAllIndices() {

View File

@ -37,4 +37,9 @@ public class RuntimeFieldsELCIntegrationTests extends RuntimeFieldsIntegrationTe
return new IndexNameProvider("runtime-fields-rest-template"); return new IndexNameProvider("runtime-fields-rest-template");
} }
} }
@Override
public boolean newElasticsearchClient() {
return true;
}
} }

View File

@ -21,8 +21,10 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIf;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.NewElasticsearchClientDevelopment;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.FieldType;
@ -38,7 +40,7 @@ import org.springframework.lang.Nullable;
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
*/ */
@SpringIntegrationTest @SpringIntegrationTest
public abstract class RuntimeFieldsIntegrationTests { public abstract class RuntimeFieldsIntegrationTests implements NewElasticsearchClientDevelopment {
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired protected IndexNameProvider indexNameProvider; @Autowired protected IndexNameProvider indexNameProvider;
@ -58,6 +60,7 @@ public abstract class RuntimeFieldsIntegrationTests {
operations.indexOps(IndexCoordinates.of(indexNameProvider.getPrefix() + "*")).delete(); operations.indexOps(IndexCoordinates.of(indexNameProvider.getPrefix() + "*")).delete();
} }
@DisabledIf(value = "newElasticsearchClient", disabledReason = "todo #2171, ES issue 298")
@Test // #1971 @Test // #1971
@DisplayName("should use runtime-field from query in search") @DisplayName("should use runtime-field from query in search")
void shouldUseRuntimeFieldFromQueryInSearch() { void shouldUseRuntimeFieldFromQueryInSearch() {

View File

@ -45,6 +45,11 @@ public class GeoELCIntegrationTests extends GeoIntegrationTests {
} }
} }
@Override
public boolean newElasticsearchClient() {
return true;
}
@Override @Override
protected Query nativeQueryForBoundingBox(String fieldName, double top, double left, double bottom, double right) { protected Query nativeQueryForBoundingBox(String fieldName, double top, double left, double bottom, double right) {
return NativeQuery.builder() // return NativeQuery.builder() //

View File

@ -23,10 +23,13 @@ import java.util.List;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIf;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.NewElasticsearchClientDevelopment;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField; import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.AbstractElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit; import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.SearchHits;
@ -53,11 +56,16 @@ import org.springframework.lang.Nullable;
* Latitude , max Longitude , max Latitude * Latitude , max Longitude , max Latitude
*/ */
@SpringIntegrationTest @SpringIntegrationTest
public abstract class GeoIntegrationTests { public abstract class GeoIntegrationTests implements NewElasticsearchClientDevelopment {
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexNameProvider indexNameProvider; @Autowired private IndexNameProvider indexNameProvider;
boolean rhlcWithCluster8() {
var clusterVersion = ((AbstractElasticsearchTemplate) operations).getClusterVersion();
return (oldElasticsearchClient() && clusterVersion != null && clusterVersion.startsWith("8"));
}
@BeforeEach @BeforeEach
public void before() { public void before() {
indexNameProvider.increment(); indexNameProvider.increment();
@ -219,6 +227,7 @@ public abstract class GeoIntegrationTests {
assertThat(geoAuthorsForGeoCriteria).hasSize(3); assertThat(geoAuthorsForGeoCriteria).hasSize(3);
} }
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test @Test
public void shouldFindAllMarkersForNativeSearchQuery() { public void shouldFindAllMarkersForNativeSearchQuery() {
@ -236,6 +245,7 @@ public abstract class GeoIntegrationTests {
protected abstract Query nativeQueryForBoundingBox(String fieldName, double top, double left, double bottom, protected abstract Query nativeQueryForBoundingBox(String fieldName, double top, double left, double bottom,
double right); double right);
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test @Test
public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoBox() { public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoBox() {
@ -254,6 +264,7 @@ public abstract class GeoIntegrationTests {
.containsExactlyInAnyOrder("def", "ghi"); .containsExactlyInAnyOrder("def", "ghi");
} }
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test @Test
public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeohash() { public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeohash() {
@ -272,6 +283,7 @@ public abstract class GeoIntegrationTests {
.containsExactlyInAnyOrder("def", "ghi"); .containsExactlyInAnyOrder("def", "ghi");
} }
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test @Test
public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoPoints() { public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoPoints() {
@ -290,6 +302,7 @@ public abstract class GeoIntegrationTests {
.containsExactlyInAnyOrder("def", "ghi"); .containsExactlyInAnyOrder("def", "ghi");
} }
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test @Test
public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingPoints() { public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingPoints() {
@ -308,6 +321,7 @@ public abstract class GeoIntegrationTests {
.containsExactlyInAnyOrder("def", "ghi"); .containsExactlyInAnyOrder("def", "ghi");
} }
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test @Test
public void shouldFindLocationWithGeoHashPrefix() { public void shouldFindLocationWithGeoHashPrefix() {

View File

@ -16,13 +16,26 @@
package org.springframework.data.elasticsearch.core.geo; package org.springframework.data.elasticsearch.core.geo;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
/** /**
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
* @since 4.4 * @since 4.4
*/ */
@ContextConfiguration(classes = { ElasticsearchTemplateConfiguration.class }) @ContextConfiguration(classes = { GeoJsonELCIntegrationTests.Config.class })
@DisplayName("GeoJson integration test with ElasticsearchClient") @DisplayName("GeoJson integration test with ElasticsearchClient")
public class GeoJsonELCIntegrationTests extends GeoJsonIntegrationTests {} public class GeoJsonELCIntegrationTests extends GeoJsonIntegrationTests {
@Configuration
@Import({ ElasticsearchTemplateConfiguration.class })
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("geojson-integration");
}
}
}

View File

@ -16,12 +16,26 @@
package org.springframework.data.elasticsearch.core.geo; package org.springframework.data.elasticsearch.core.geo;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
/** /**
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
*/ */
@ContextConfiguration(classes = { ElasticsearchRestTemplateConfiguration.class }) @ContextConfiguration(classes = { GeoJsonERHLCIntegrationTests.Config.class })
@DisplayName("GeoJson integration test with RestHighLevelClient") @DisplayName("GeoJson integration test with RestHighLevelClient")
public class GeoJsonERHLCIntegrationTests extends GeoJsonIntegrationTests {} public class GeoJsonERHLCIntegrationTests extends GeoJsonIntegrationTests {
@Configuration
@Import({ ElasticsearchRestTemplateConfiguration.class })
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("geojson-integration-es7");
}
}
}

View File

@ -23,7 +23,7 @@ import org.springframework.lang.Nullable;
/** /**
* this class contains each GeoJson type as explicit type and as GeoJson interface. Used by several test classes * this class contains each GeoJson type as explicit type and as GeoJson interface. Used by several test classes
*/ */
@Document(indexName = "geojson-index") @Document(indexName = "#{@indexNameProvider.indexName()}-geojson")
public class GeoJsonEntity { public class GeoJsonEntity {
@Nullable @Nullable
@Id private String id; @Id private String id;

View File

@ -19,20 +19,21 @@ import static org.assertj.core.api.Assertions.*;
import java.util.Arrays; import java.util.Arrays;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.Criteria; import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery; import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.data.geo.Point; import org.springframework.data.geo.Point;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
@ -44,7 +45,21 @@ abstract class GeoJsonIntegrationTests {
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
private IndexOperations indexOps; @Autowired private IndexNameProvider indexNameProvider;
@BeforeEach
public void before() {
indexNameProvider.increment();
operations.indexOps(Area.class).createWithMapping();
operations.indexOps(GeoJsonEntity.class).createWithMapping();
operations.save(Arrays.asList(area10To20, area30To40));
}
@Test
@Order(java.lang.Integer.MAX_VALUE)
void cleanup() {
operations.indexOps(IndexCoordinates.of("*" + indexNameProvider.getPrefix() + "*")).delete();
}
// region data // region data
@ -89,29 +104,6 @@ abstract class GeoJsonIntegrationTests {
private final Area area32To37 = new Area("area32To37", geoShape30To40); private final Area area32To37 = new Area("area32To37", geoShape30To40);
// endregion // endregion
// region setup
@BeforeEach
void setUp() {
indexOps = operations.indexOps(GeoJsonEntity.class);
indexOps.delete();
indexOps.create();
indexOps.putMapping();
IndexOperations indexOpsArea = operations.indexOps(Area.class);
indexOpsArea.delete();
indexOpsArea.create();
indexOpsArea.putMapping();
operations.save(Arrays.asList(area10To20, area30To40));
indexOpsArea.refresh();
}
@AfterEach
void tearDown() {
indexOps.delete();
}
// endregion
// region tests // region tests
@Test // DATAES-930 @Test // DATAES-930
@DisplayName("should write and read an entity with GeoJson properties") @DisplayName("should write and read an entity with GeoJson properties")
@ -149,7 +141,6 @@ abstract class GeoJsonIntegrationTests {
entity.setGeometryCollection2(geoJsonGeometryCollection); entity.setGeometryCollection2(geoJsonGeometryCollection);
operations.save(entity); operations.save(entity);
indexOps.refresh();
GeoJsonEntity result = operations.get("42", GeoJsonEntity.class); GeoJsonEntity result = operations.get("42", GeoJsonEntity.class);
@ -202,7 +193,7 @@ abstract class GeoJsonIntegrationTests {
// endregion // endregion
// region test classes // region test classes
@Document(indexName = "areas") @Document(indexName = "#{@indexNameProvider.indexName()}-area")
static class Area { static class Area {
@Nullable @Nullable
@Id private String id; @Id private String id;

View File

@ -23,4 +23,9 @@ import org.springframework.test.context.ContextConfiguration;
* @since 4.4 * @since 4.4
*/ */
@ContextConfiguration(classes = { ElasticsearchTemplateConfiguration.class }) @ContextConfiguration(classes = { ElasticsearchTemplateConfiguration.class })
public class IndexTemplateELCIntegrationTests extends IndexTemplateIntegrationTests {} public class IndexTemplateELCIntegrationTests extends IndexTemplateIntegrationTests {
@Override
public boolean newElasticsearchClient() {
return true;
}
}

View File

@ -22,4 +22,5 @@ import org.springframework.test.context.ContextConfiguration;
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
*/ */
@ContextConfiguration(classes = { ElasticsearchRestTemplateConfiguration.class }) @ContextConfiguration(classes = { ElasticsearchRestTemplateConfiguration.class })
public class IndexTemplateERHLCIntegrationTests extends IndexTemplateIntegrationTests {} public class IndexTemplateERHLCIntegrationTests extends IndexTemplateIntegrationTests {
}

View File

@ -23,12 +23,15 @@ import java.util.UUID;
import org.json.JSONException; import org.json.JSONException;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIf;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.NewElasticsearchClientDevelopment;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.Setting; import org.springframework.data.elasticsearch.annotations.Setting;
import org.springframework.data.elasticsearch.core.AbstractElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
@ -39,10 +42,16 @@ import org.springframework.lang.Nullable;
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
*/ */
@SpringIntegrationTest @SpringIntegrationTest
public abstract class IndexTemplateIntegrationTests { public abstract class IndexTemplateIntegrationTests implements NewElasticsearchClientDevelopment {
@Autowired ElasticsearchOperations operations; @Autowired ElasticsearchOperations operations;
boolean rhlcWithCluster8() {
var clusterVersion = ((AbstractElasticsearchTemplate) operations).getClusterVersion();
return (oldElasticsearchClient() && clusterVersion != null && clusterVersion.startsWith("8"));
}
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test // DATAES-612 @Test // DATAES-612
void shouldCreateTemplate() { void shouldCreateTemplate() {
@ -76,6 +85,7 @@ public abstract class IndexTemplateIntegrationTests {
assertThat(templateData).isNull(); assertThat(templateData).isNull();
} }
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test // DATAES-612 @Test // DATAES-612
void shouldGetTemplate() throws JSONException { void shouldGetTemplate() throws JSONException {
IndexOperations indexOps = operations.indexOps(IndexCoordinates.of("dont-care")); IndexOperations indexOps = operations.indexOps(IndexCoordinates.of("dont-care"));
@ -101,7 +111,7 @@ public abstract class IndexTemplateIntegrationTests {
assertThat(templateData).isNotNull(); assertThat(templateData).isNotNull();
assertThat(templateData.getIndexPatterns()).containsExactlyInAnyOrder(putTemplateRequest.getIndexPatterns()); assertThat(templateData.getIndexPatterns()).containsExactlyInAnyOrder(putTemplateRequest.getIndexPatterns());
assertEquals(settings.toJson(), templateData.getSettings().toJson(), false); assertEquals(settings.flatten().toJson(), templateData.getSettings().toJson(), false);
assertEquals(mapping.toJson(), templateData.getMapping().toJson(), false); assertEquals(mapping.toJson(), templateData.getMapping().toJson(), false);
Map<String, AliasData> aliases = templateData.getAliases(); Map<String, AliasData> aliases = templateData.getAliases();
assertThat(aliases).hasSize(2); assertThat(aliases).hasSize(2);

View File

@ -39,7 +39,7 @@ public class MappingBuilderELCIntegrationTests extends MappingBuilderIntegration
} }
@Override @Override
public boolean usesNewElasticsearchClient() { public boolean newElasticsearchClient() {
return true; return true;
} }
} }

View File

@ -33,12 +33,12 @@ public class IndexOperationsELCIntegrationTests extends IndexOperationsIntegrati
static class Config { static class Config {
@Bean @Bean
IndexNameProvider indexNameProvider() { IndexNameProvider indexNameProvider() {
return new IndexNameProvider("indexoperations-es"); return new IndexNameProvider("indexoperations");
} }
} }
@Override @Override
public boolean usesNewElasticsearchClient() { public boolean newElasticsearchClient() {
return true; return true;
} }
} }

View File

@ -25,6 +25,7 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIf;
import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
@ -70,6 +71,7 @@ public abstract class IndexOperationsIntegrationTests implements NewElasticsearc
operations.indexOps(IndexCoordinates.of(indexNameProvider.getPrefix() + "*")).delete(); operations.indexOps(IndexCoordinates.of(indexNameProvider.getPrefix() + "*")).delete();
} }
@DisabledIf(value = "newElasticsearchClient", disabledReason = "todo #2165, ES issue 286")
@Test // #1646, #1718 @Test // #1646, #1718
@DisplayName("should return a list of info for specific index") @DisplayName("should return a list of info for specific index")
void shouldReturnInformationList() throws JSONException { void shouldReturnInformationList() throws JSONException {

View File

@ -27,7 +27,6 @@ import org.springframework.test.context.ContextConfiguration;
*/ */
@ContextConfiguration(classes = { ReactiveIndexOperationsELCIntegrationTests.Config.class }) @ContextConfiguration(classes = { ReactiveIndexOperationsELCIntegrationTests.Config.class })
public class ReactiveIndexOperationsELCIntegrationTests extends ReactiveIndexOperationsIntegrationTests { public class ReactiveIndexOperationsELCIntegrationTests extends ReactiveIndexOperationsIntegrationTests {
@Configuration @Configuration
@Import({ ReactiveElasticsearchTemplateConfiguration.class }) @Import({ ReactiveElasticsearchTemplateConfiguration.class })
static class Config { static class Config {
@ -36,4 +35,9 @@ public class ReactiveIndexOperationsELCIntegrationTests extends ReactiveIndexOpe
return new IndexNameProvider("reactive-indexoperations"); return new IndexNameProvider("reactive-indexoperations");
} }
} }
@Override
public boolean newElasticsearchClient() {
return true;
}
} }

View File

@ -31,26 +31,20 @@ import org.json.JSONException;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIf;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.NewElasticsearchClientDevelopment;
import org.springframework.data.elasticsearch.annotations.DateFormat; import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.Mapping; import org.springframework.data.elasticsearch.annotations.Mapping;
import org.springframework.data.elasticsearch.annotations.Setting; import org.springframework.data.elasticsearch.annotations.Setting;
import org.springframework.data.elasticsearch.core.AbstractReactiveElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations; import org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ReactiveIndexOperations; import org.springframework.data.elasticsearch.core.ReactiveIndexOperations;
import org.springframework.data.elasticsearch.core.index.AliasAction; import org.springframework.data.elasticsearch.core.index.*;
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.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.utils.IndexNameProvider; import org.springframework.data.elasticsearch.utils.IndexNameProvider;
@ -60,12 +54,17 @@ import org.springframework.lang.Nullable;
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
*/ */
@SpringIntegrationTest @SpringIntegrationTest
public abstract class ReactiveIndexOperationsIntegrationTests { public abstract class ReactiveIndexOperationsIntegrationTests implements NewElasticsearchClientDevelopment {
@Autowired private ReactiveElasticsearchOperations operations; @Autowired private ReactiveElasticsearchOperations operations;
@Autowired private IndexNameProvider indexNameProvider; @Autowired private IndexNameProvider indexNameProvider;
private ReactiveIndexOperations indexOperations; private ReactiveIndexOperations indexOperations;
boolean rhlcWithCluster8() {
var clusterVersion = ((AbstractReactiveElasticsearchTemplate) operations).getClusterVersion().block();
return (oldElasticsearchClient() && clusterVersion != null && clusterVersion.startsWith("8"));
}
@BeforeEach @BeforeEach
void setUp() { void setUp() {
indexNameProvider.increment(); indexNameProvider.increment();
@ -124,11 +123,11 @@ public abstract class ReactiveIndexOperationsIntegrationTests {
@Test // DATAES-678 @Test // DATAES-678
void shouldCreateIndexWithGivenSettings() { void shouldCreateIndexWithGivenSettings() {
org.springframework.data.elasticsearch.core.document.Document requiredSettings = org.springframework.data.elasticsearch.core.document.Document var index = new Settings() //
.create(); .append("number_of_replicas", 3) //
requiredSettings.put("index.number_of_replicas", 3); .append("number_of_shards", 4)//
requiredSettings.put("index.number_of_shards", 4); .append("refresh_interval", "5s");
requiredSettings.put("index.refresh_interval", "5s"); var requiredSettings = new Settings().append("index", index);
indexOperations.create(requiredSettings) // indexOperations.create(requiredSettings) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
@ -136,9 +135,10 @@ public abstract class ReactiveIndexOperationsIntegrationTests {
.verifyComplete(); .verifyComplete();
indexOperations.getSettings().as(StepVerifier::create).consumeNextWith(settings -> { indexOperations.getSettings().as(StepVerifier::create).consumeNextWith(settings -> {
assertThat(settings.get("index.number_of_replicas")).isEqualTo("3"); var flattened = settings.flatten();
assertThat(settings.get("index.number_of_shards")).isEqualTo("4"); assertThat(flattened.get("index.number_of_replicas")).isEqualTo("3");
assertThat(settings.get("index.refresh_interval")).isEqualTo("5s"); assertThat(flattened.get("index.number_of_shards")).isEqualTo("4");
assertThat(flattened.get("index.refresh_interval")).isEqualTo("5s");
}).verifyComplete(); }).verifyComplete();
} }
@ -359,6 +359,7 @@ public abstract class ReactiveIndexOperationsIntegrationTests {
.verifyComplete(); .verifyComplete();
} }
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test // DATAES-612 @Test // DATAES-612
void shouldPutTemplate() { void shouldPutTemplate() {
@ -391,6 +392,7 @@ public abstract class ReactiveIndexOperationsIntegrationTests {
.verifyComplete(); .verifyComplete();
} }
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test // DATAES-612 @Test // DATAES-612
void shouldGetTemplate() throws JSONException { void shouldGetTemplate() throws JSONException {
@ -417,10 +419,8 @@ public abstract class ReactiveIndexOperationsIntegrationTests {
SoftAssertions softly = new SoftAssertions(); SoftAssertions softly = new SoftAssertions();
softly.assertThat(templateData).isNotNull(); softly.assertThat(templateData).isNotNull();
softly.assertThat(templateData.getIndexPatterns()).containsExactlyInAnyOrder(putTemplateRequest.getIndexPatterns()); softly.assertThat(templateData.getIndexPatterns()).containsExactlyInAnyOrder(putTemplateRequest.getIndexPatterns());
assertEquals(settings.toJson(), templateData.getSettings().toJson(), false); assertEquals(settings.flatten().toJson(), templateData.getSettings().toJson(), false);
assertEquals(mapping.toJson(), templateData.getMapping().toJson(), false); assertEquals(mapping.toJson(), templateData.getMapping().toJson(), false);
Map<String, AliasData> aliases = templateData.getAliases(); Map<String, AliasData> aliases = templateData.getAliases();
softly.assertThat(aliases).hasSize(2); softly.assertThat(aliases).hasSize(2);
AliasData alias1 = aliases.get("alias1"); AliasData alias1 = aliases.get("alias1");

View File

@ -177,16 +177,29 @@ public class SimpleElasticsearchPersistentEntityTests extends MappingContextBase
.isInstanceOf(IllegalArgumentException.class); .isInstanceOf(IllegalArgumentException.class);
} }
@Test // #1719 @Test // #1719, #2158
@DisplayName("should write sort parameters to Settings object") @DisplayName("should write sort parameters to Settings object")
void shouldWriteSortParametersToSettingsObject() throws JSONException { void shouldWriteSortParametersToSettingsObject() throws JSONException {
String expected = "{\n" + // String expected = """
" \"index.sort.field\": [\"second_field\", \"first_field\"],\n" + // {
" \"index.sort.mode\": [\"max\", \"min\"],\n" + // "index": {
" \"index.sort.order\": [\"desc\",\"asc\"],\n" + // "sort": {
" \"index.sort.missing\": [\"_last\",\"_first\"]\n" + // "field": [
"}\n"; // "second_field",
"first_field"
],
"mode": [
"max",
"min"
],
"missing": [
"_last",
"_first"
]
}
}
} """;
ElasticsearchPersistentEntity<?> entity = elasticsearchConverter.get().getMappingContext() ElasticsearchPersistentEntity<?> entity = elasticsearchConverter.get().getMappingContext()
.getRequiredPersistentEntity(SettingsValidSortParameterSizes.class); .getRequiredPersistentEntity(SettingsValidSortParameterSizes.class);

View File

@ -47,7 +47,7 @@ public class CompletionELCIntegrationTests extends CompletionIntegrationTests {
} }
@Override @Override
public boolean usesNewElasticsearchClient() { public boolean newElasticsearchClient() {
return true; return true;
} }

View File

@ -45,7 +45,7 @@ public class ReactiveSuggestELCIntegrationTests extends ReactiveSuggestIntegrati
} }
@Override @Override
public boolean usesNewElasticsearchClient() { public boolean newElasticsearchClient() {
return true; return true;
} }

View File

@ -42,4 +42,9 @@ public class CustomMethodRepositoryERHLCIntegrationTests extends CustomMethodRep
return new IndexNameProvider("custom-method-repository-es7"); return new IndexNameProvider("custom-method-repository-es7");
} }
} }
@Override
public boolean newElasticsearchClient() {
return false;
}
} }

View File

@ -32,6 +32,7 @@ import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIf;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version; import org.springframework.data.annotation.Version;
@ -40,12 +41,14 @@ import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order; import org.springframework.data.domain.Sort.Order;
import org.springframework.data.elasticsearch.NewElasticsearchClientDevelopment;
import org.springframework.data.elasticsearch.annotations.CountQuery; import org.springframework.data.elasticsearch.annotations.CountQuery;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Highlight; import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.data.elasticsearch.annotations.HighlightField; import org.springframework.data.elasticsearch.annotations.HighlightField;
import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.core.AbstractElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHit; import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.SearchHits;
@ -75,7 +78,7 @@ import org.springframework.lang.Nullable;
* @author James Mudd * @author James Mudd
*/ */
@SpringIntegrationTest @SpringIntegrationTest
public abstract class CustomMethodRepositoryIntegrationTests { public abstract class CustomMethodRepositoryIntegrationTests implements NewElasticsearchClientDevelopment {
@Autowired private IndexNameProvider indexNameProvider; @Autowired private IndexNameProvider indexNameProvider;
@Autowired private SampleCustomMethodRepository repository; @Autowired private SampleCustomMethodRepository repository;
@ -83,6 +86,11 @@ public abstract class CustomMethodRepositoryIntegrationTests {
@Autowired ElasticsearchOperations operations; @Autowired ElasticsearchOperations operations;
boolean rhlcWithCluster8() {
var clusterVersion = ((AbstractElasticsearchTemplate) operations).getClusterVersion();
return (oldElasticsearchClient() && clusterVersion != null && clusterVersion.startsWith("8"));
}
@BeforeEach @BeforeEach
public void before() { public void before() {
@ -806,6 +814,7 @@ public abstract class CustomMethodRepositoryIntegrationTests {
assertThat(page.getTotalElements()).isEqualTo(1L); assertThat(page.getTotalElements()).isEqualTo(1L);
} }
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test @Test
public void shouldExecuteCustomMethodWithNearBox() { public void shouldExecuteCustomMethodWithNearBox() {
@ -1365,6 +1374,7 @@ public abstract class CustomMethodRepositoryIntegrationTests {
assertThat(count).isEqualTo(1L); assertThat(count).isEqualTo(1L);
} }
@DisabledIf(value = "rhlcWithCluster8", disabledReason = "RHLC fails to parse response from ES 8.2")
@Test // DATAES-106 @Test // DATAES-106
public void shouldCountCustomMethodWithNearBox() { public void shouldCountCustomMethodWithNearBox() {

View File

@ -15,10 +15,14 @@
# #
# #
sde.testcontainers.image-name=docker.elastic.co/elasticsearch/elasticsearch sde.testcontainers.image-name=docker.elastic.co/elasticsearch/elasticsearch
sde.testcontainers.image-version=7.17.3 sde.testcontainers.image-version=8.2.2
# #
# #
# needed as we do a DELETE /* at the end of the tests, will be required from 8.0 on, produces a warning since 7.13 # needed as we do a DELETE /* at the end of the tests, will be required from 8.0 on, produces a warning since 7.13
# #
action.destructive_requires_name=false action.destructive_requires_name=false
reindex.remote.whitelist=localhost:9200 reindex.remote.whitelist=localhost:9200
#
# we do not want to complicate the test setup with the security features, makes it harder for debugging, proxyuing
xpack.security.enabled=false
xpack.security.http.ssl.enabled=false