Improve integration test time.

Original Pull Request #1827 
Closes #1826
This commit is contained in:
Peter-Josef Meisch 2021-05-24 12:29:53 +02:00 committed by GitHub
parent 7582617a26
commit 67d084beea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 776 additions and 876 deletions

View File

@ -23,7 +23,7 @@
<log4j>2.13.3</log4j>
<netty>4.1.52.Final</netty>
<springdata.commons>2.6.0-SNAPSHOT</springdata.commons>
<testcontainers>1.15.1</testcontainers>
<testcontainers>1.15.3</testcontainers>
<blockhound-junit>1.0.6.RELEASE</blockhound-junit>
<java-module-name>spring.data.elasticsearch</java-module-name>
</properties>

View File

@ -15,7 +15,10 @@
*/
package org.springframework.data.elasticsearch.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import org.elasticsearch.action.ActionFuture;
@ -290,12 +293,21 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
public List<IndexedObjectInformation> doBulkOperation(List<?> queries, BulkOptions bulkOptions,
IndexCoordinates index) {
BulkRequestBuilder bulkRequestBuilder = requestFactory.bulkRequestBuilder(client, queries, bulkOptions, index);
bulkRequestBuilder = prepareWriteRequestBuilder(bulkRequestBuilder);
final List<IndexedObjectInformation> indexedObjectInformations = checkForBulkOperationFailure(
bulkRequestBuilder.execute().actionGet());
updateIndexedObjectsWithQueries(queries, indexedObjectInformations);
return indexedObjectInformations;
// do it in batches; test code on some machines kills the transport node when the size gets too much
Collection<? extends List<?>> queryLists = partitionBasedOnSize(queries, 2500);
List<IndexedObjectInformation> allIndexedObjectInformations = new ArrayList<>(queries.size());
queryLists.forEach(queryList -> {
BulkRequestBuilder bulkRequestBuilder = requestFactory.bulkRequestBuilder(client, queryList, bulkOptions, index);
bulkRequestBuilder = prepareWriteRequestBuilder(bulkRequestBuilder);
final List<IndexedObjectInformation> indexedObjectInformations = checkForBulkOperationFailure(
bulkRequestBuilder.execute().actionGet());
updateIndexedObjectsWithQueries(queryList, indexedObjectInformations);
allIndexedObjectInformations.addAll(indexedObjectInformations);
});
return allIndexedObjectInformations;
}
// endregion
@ -411,6 +423,11 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
public Client getClient() {
return client;
}
<T> Collection<List<T>> partitionBasedOnSize(List<T> inputList, int size) {
final AtomicInteger counter = new AtomicInteger(0);
return inputList.stream().collect(Collectors.groupingBy(s -> counter.getAndIncrement() / size)).values();
}
// endregion
/**

View File

@ -18,10 +18,8 @@ package org.springframework.data.elasticsearch.core;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.skyscreamer.jsonassert.JSONAssert.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import static org.springframework.data.elasticsearch.utils.IdGenerator.*;
import java.lang.Object;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
@ -37,16 +35,16 @@ import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.json.JSONException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.data.annotation.Id;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.elasticsearch.UncategorizedElasticsearchException;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.lang.Nullable;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.test.context.ContextConfiguration;
/**
@ -64,10 +62,19 @@ import org.springframework.test.context.ContextConfiguration;
* @author Peter-Josef Meisch
* @author Farid Faoudi
*/
@ContextConfiguration(classes = { ElasticsearchRestTemplateConfiguration.class })
@ContextConfiguration(classes = { ElasticsearchRestTemplateTests.Config.class })
@DisplayName("ElasticsearchRestTemplate")
public class ElasticsearchRestTemplateTests extends ElasticsearchTemplateTests {
@Configuration
@Import({ ElasticsearchRestTemplateConfiguration.class })
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("rest-template");
}
}
@Test
public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() {
@ -75,35 +82,10 @@ public class ElasticsearchRestTemplateTests extends ElasticsearchTemplateTests {
org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document
.create();
UpdateQuery updateQuery = UpdateQuery.builder(nextIdAsString()).withDocument(document).build();
assertThatThrownBy(() -> operations.update(updateQuery, index))
assertThatThrownBy(() -> operations.update(updateQuery, IndexCoordinates.of(indexNameProvider.indexName())))
.isInstanceOf(UncategorizedElasticsearchException.class);
}
@Document(indexName = "test-index-sample-core-rest-template")
static class SampleEntity {
@Nullable @Id private String id;
@Nullable
@Field(type = Text, store = true, fielddata = true) private String type;
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public String getType() {
return type;
}
public void setType(@Nullable String type) {
this.type = type;
}
}
@Test // DATAES-768
void shouldUseAllOptionsFromUpdateQuery() {
Map<String, Object> doc = new HashMap<>();

View File

@ -41,6 +41,9 @@ import org.json.JSONException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
@ -52,6 +55,7 @@ import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.lang.Nullable;
import org.springframework.test.context.ContextConfiguration;
@ -60,10 +64,19 @@ import org.springframework.test.context.ContextConfiguration;
* @author Sascha Woo
* @author Farid Faoudi
*/
@ContextConfiguration(classes = { ElasticsearchTemplateConfiguration.class })
@ContextConfiguration(classes = { ElasticsearchTransportTemplateTests.Config.class })
@DisplayName("ElasticsearchTransportTemplate")
public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTests {
@Configuration
@Import({ ElasticsearchTemplateConfiguration.class })
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("transport-template");
}
}
@Autowired private Client client;
@Test
@ -72,7 +85,8 @@ public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTe
org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document
.create();
UpdateQuery updateQuery = UpdateQuery.builder(nextIdAsString()).withDocument(document).build();
assertThatThrownBy(() -> operations.update(updateQuery, index)).isInstanceOf(DocumentMissingException.class);
assertThatThrownBy(() -> operations.update(updateQuery, IndexCoordinates.of(indexNameProvider.indexName())))
.isInstanceOf(DocumentMissingException.class);
}
@Override

View File

@ -47,12 +47,13 @@ import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.json.JSONException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.dao.DataAccessResourceFailureException;
@ -78,6 +79,7 @@ import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.data.elasticsearch.junit.jupiter.ReactiveElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
@ -99,40 +101,29 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Configuration
@Import({ ReactiveElasticsearchRestTemplateConfiguration.class })
static class Config {}
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("reactive-template");
}
}
static final String DEFAULT_INDEX = "reactive-template-test-index";
static final String ALTERNATE_INDEX = "reactive-template-tests-alternate-index";
@Autowired private ReactiveElasticsearchOperations operations;
@Autowired private ReactiveElasticsearchTemplate template;
private ReactiveIndexOperations indexOperations;
@Autowired private IndexNameProvider indexNameProvider;
// region Setup
@BeforeEach
public void setUp() {
indexOperations = template.indexOps(SampleEntity.class);
public void beforeEach() {
deleteIndices();
indexOperations.create() //
.then(indexOperations.putMapping(SampleEntity.class)) //
.then(indexOperations.refresh()) //
.block(); //
indexNameProvider.increment();
operations.indexOps(SampleEntity.class).createWithMapping().block();
}
@AfterEach
public void after() {
deleteIndices();
}
private void deleteIndices() {
template.indexOps(IndexCoordinates.of(DEFAULT_INDEX)).delete().block();
template.indexOps(IndexCoordinates.of(ALTERNATE_INDEX)).delete().block();
template.indexOps(IndexCoordinates.of("rx-template-test-index-this")).delete().block();
template.indexOps(IndexCoordinates.of("rx-template-test-index-that")).delete().block();
template.indexOps(IndexCoordinates.of("test-index-reactive-optimistic-entity-template")).delete().block();
template.indexOps(IndexCoordinates.of("test-index-reactive-optimistic-and-versioned-entity-template")).delete()
.block();
@Test
@Order(java.lang.Integer.MAX_VALUE)
void cleanup() {
operations.indexOps(IndexCoordinates.of("*")).delete().block();
}
// endregion
@ -140,7 +131,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-504
public void executeShouldProvideResource() {
Mono.from(template.execute(ReactiveElasticsearchClient::ping)) //
Mono.from(operations.execute(ReactiveElasticsearchClient::ping)) //
.as(StepVerifier::create) //
.expectNext(true) //
.verifyComplete();
@ -149,7 +140,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-504
public void executeShouldConvertExceptions() {
Mono.from(template.execute(client -> {
Mono.from(operations.execute(client -> {
throw new RuntimeException(new ConnectException("we're doomed"));
})) //
.as(StepVerifier::create) //
@ -162,13 +153,12 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = randomEntity("foo bar");
template.save(sampleEntity) //
.then(indexOperations.refresh()) //
operations.save(sampleEntity) //
.block();
template
operations
.search(new CriteriaQuery(Criteria.where("message").is(sampleEntity.getMessage())), SampleEntity.class,
IndexCoordinates.of(DEFAULT_INDEX)) //
IndexCoordinates.of(indexNameProvider.indexName())) //
.as(StepVerifier::create) //
.expectNextCount(1) //
.verifyComplete();
@ -180,34 +170,33 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setMessage("wohoo");
template.save(sampleEntity) //
operations.save(sampleEntity) //
.map(SampleEntity::getId) //
.flatMap(id -> indexOperations.refresh().thenReturn(id)) //
.flatMap(id -> documentWithIdExistsInIndex(id, DEFAULT_INDEX)).as(StepVerifier::create) //
.flatMap(id -> documentWithIdExistsInIndex(id, indexNameProvider.indexName())).as(StepVerifier::create) //
.expectNext(true) //
.verifyComplete();
}
private Mono<Boolean> documentWithIdExistsInIndex(String id, String index) {
return template.exists(id, IndexCoordinates.of(index));
return operations.exists(id, IndexCoordinates.of(index));
}
@Test // DATAES-504
public void insertWithExplicitIndexNameShouldOverwriteMetadata() {
SampleEntity sampleEntity = randomEntity("in another index");
IndexCoordinates alternateIndex = IndexCoordinates.of(ALTERNATE_INDEX);
String defaultIndexName = indexNameProvider.indexName();
String alternateIndexName = defaultIndexName + "-alt";
template.save(sampleEntity, alternateIndex) //
SampleEntity sampleEntity = randomEntity("in another index");
IndexCoordinates alternateIndex = IndexCoordinates.of(alternateIndexName);
operations.save(sampleEntity, alternateIndex) //
.as(StepVerifier::create)//
.expectNextCount(1)//
.verifyComplete();
template.indexOps(IndexCoordinates.of(DEFAULT_INDEX)).refresh().block();
template.indexOps(alternateIndex).refresh().block();
assertThat(documentWithIdExistsInIndex(sampleEntity.getId(), DEFAULT_INDEX).block()).isFalse();
assertThat(documentWithIdExistsInIndex(sampleEntity.getId(), ALTERNATE_INDEX).block()).isTrue();
assertThat(documentWithIdExistsInIndex(sampleEntity.getId(), defaultIndexName).block()).isFalse();
assertThat(documentWithIdExistsInIndex(sampleEntity.getId(), alternateIndexName).block()).isTrue();
}
@Test // DATAES-504
@ -215,7 +204,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
Map<String, Object> map = new LinkedHashMap<>(Collections.singletonMap("foo", "bar"));
template.save(map, IndexCoordinates.of(ALTERNATE_INDEX)) //
operations.save(map, IndexCoordinates.of(indexNameProvider.indexName())) //
.as(StepVerifier::create) //
.consumeNextWith(actual -> {
assertThat(map).containsKey("id");
@ -225,14 +214,14 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-504
public void insertShouldErrorOnNullEntity() {
assertThatThrownBy(() -> {
template.save(null);
operations.save(null);
}).isInstanceOf(IllegalArgumentException.class);
}
@Test // DATAES-519, DATAES-767, DATAES-822
public void getByIdShouldErrorWhenIndexDoesNotExist() {
template.get("foo", SampleEntity.class, IndexCoordinates.of("no-such-index")) //
operations.get("foo", SampleEntity.class, IndexCoordinates.of("no-such-index")) //
.as(StepVerifier::create) //
.expectError(ElasticsearchStatusException.class);
}
@ -243,7 +232,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = randomEntity("some message");
index(sampleEntity);
template.get(sampleEntity.getId(), SampleEntity.class) //
operations.get(sampleEntity.getId(), SampleEntity.class) //
.as(StepVerifier::create) //
.expectNext(sampleEntity) //
.verifyComplete();
@ -259,7 +248,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
assertThat(sampleEntity.getId()).isNotNull();
template.get(sampleEntity.getId(), SampleEntity.class) //
operations.get(sampleEntity.getId(), SampleEntity.class) //
.as(StepVerifier::create) //
.consumeNextWith(it -> assertThat(it.getId()).isEqualTo(sampleEntity.getId())) //
.verifyComplete();
@ -271,7 +260,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = randomEntity("some message");
index(sampleEntity);
template.get("foo", SampleEntity.class) //
operations.get("foo", SampleEntity.class) //
.as(StepVerifier::create) //
.verifyComplete();
}
@ -279,7 +268,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-504
public void getByIdShouldErrorForNullId() {
assertThatThrownBy(() -> {
template.get(null, SampleEntity.class);
operations.get(null, SampleEntity.class);
}).isInstanceOf(IllegalArgumentException.class);
}
@ -288,20 +277,19 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = randomEntity("some message");
IndexCoordinates defaultIndex = IndexCoordinates.of(DEFAULT_INDEX);
IndexCoordinates alternateIndex = IndexCoordinates.of(ALTERNATE_INDEX);
IndexCoordinates defaultIndex = IndexCoordinates.of(indexNameProvider.indexName());
IndexCoordinates alternateIndex = IndexCoordinates.of(indexNameProvider.indexName() + "-alt");
template.save(sampleEntity, alternateIndex) //
.then(indexOperations.refresh()) //
.then(template.indexOps(defaultIndex).refresh()) //
.then(template.indexOps(alternateIndex).refresh()) //
operations.save(sampleEntity, alternateIndex) //
.then(operations.indexOps(defaultIndex).refresh()) //
.then(operations.indexOps(alternateIndex).refresh()) //
.block();
template.get(sampleEntity.getId(), SampleEntity.class, defaultIndex) //
operations.get(sampleEntity.getId(), SampleEntity.class, defaultIndex) //
.as(StepVerifier::create) //
.verifyComplete();
template.get(sampleEntity.getId(), SampleEntity.class, alternateIndex) //
operations.get(sampleEntity.getId(), SampleEntity.class, alternateIndex) //
.as(StepVerifier::create)//
.expectNextCount(1) //
.verifyComplete();
@ -310,7 +298,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-519
public void existsShouldReturnFalseWhenIndexDoesNotExist() {
template.exists("foo", IndexCoordinates.of("no-such-index")) //
operations.exists("foo", IndexCoordinates.of("no-such-index")) //
.as(StepVerifier::create) //
.expectNext(false) //
.verifyComplete();
@ -322,7 +310,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = randomEntity("some message");
index(sampleEntity);
template.exists(sampleEntity.getId(), SampleEntity.class) //
operations.exists(sampleEntity.getId(), SampleEntity.class) //
.as(StepVerifier::create) //
.expectNext(true) //
.verifyComplete();
@ -334,7 +322,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = randomEntity("some message");
index(sampleEntity);
template.exists("foo", SampleEntity.class) //
operations.exists("foo", SampleEntity.class) //
.as(StepVerifier::create) //
.expectNext(false) //
.verifyComplete();
@ -343,7 +331,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-519, DATAES-767
public void searchShouldCompleteWhenIndexDoesNotExist() {
template
operations
.search(new CriteriaQuery(Criteria.where("message").is("some message")), SampleEntity.class,
IndexCoordinates.of("no-such-index")) //
.as(StepVerifier::create) //
@ -358,7 +346,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
CriteriaQuery criteriaQuery = new CriteriaQuery(Criteria.where("message").is("some message"));
template.search(criteriaQuery, SampleEntity.class) //
operations.search(criteriaQuery, SampleEntity.class) //
.map(SearchHit::getContent) //
.as(StepVerifier::create) //
.expectNext(sampleEntity) //
@ -373,7 +361,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
CriteriaQuery criteriaQuery = new CriteriaQuery(Criteria.where("message").is("foo"));
template.search(criteriaQuery, SampleEntity.class) //
operations.search(criteriaQuery, SampleEntity.class) //
.as(StepVerifier::create) //
.verifyComplete();
}
@ -383,7 +371,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
index(randomEntity("test message"), randomEntity("test test"), randomEntity("some message"));
template.search(new StringQuery(matchAllQuery().toString()), SampleEntity.class) //
operations.search(new StringQuery(matchAllQuery().toString()), SampleEntity.class) //
.as(StepVerifier::create) //
.expectNextCount(3) //
.verifyComplete();
@ -398,7 +386,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("test"));
template.search(query, SampleEntity.class) //
operations.search(query, SampleEntity.class) //
.map(SearchHit::getContent) //
.as(StepVerifier::create) //
.assertNext(next -> {
@ -419,7 +407,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
CriteriaQuery query = new CriteriaQuery(
new Criteria("message").contains("some").and("message").contains("message"));
template.search(query, SampleEntity.class) //
operations.search(query, SampleEntity.class) //
.map(SearchHit::getContent) //
.as(StepVerifier::create) //
.expectNext(sampleEntity3) //
@ -439,7 +427,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
new Criteria("message").contains("some").and("message").contains("message"));
queryWithValidPreference.setPreference("_local");
template.search(queryWithValidPreference, SampleEntity.class) //
operations.search(queryWithValidPreference, SampleEntity.class) //
.map(SearchHit::getContent) //
.as(StepVerifier::create) //
.expectNext(sampleEntity3) //
@ -459,7 +447,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
new Criteria("message").contains("some").and("message").contains("message"));
queryWithInvalidPreference.setPreference("_only_nodes:oops");
template.search(queryWithInvalidPreference, SampleEntity.class) //
operations.search(queryWithInvalidPreference, SampleEntity.class) //
.as(StepVerifier::create) //
.expectError(UncategorizedElasticsearchException.class).verify();
}
@ -476,7 +464,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
CriteriaQuery query = new CriteriaQuery(
new Criteria("message").contains("some").and("message").contains("message"));
template.search(query, SampleEntity.class, Message.class) //
operations.search(query, SampleEntity.class, Message.class) //
.map(SearchHit::getContent) //
.as(StepVerifier::create) //
.expectNext(new Message(sampleEntity3.getMessage())) //
@ -492,7 +480,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
.addSort(Sort.by("message"))//
.setPageable(PageRequest.of(0, 20));
template.search(query, SampleEntity.class).as(StepVerifier::create) //
operations.search(query, SampleEntity.class).as(StepVerifier::create) //
.expectNextCount(20) //
.verifyComplete();
}
@ -506,7 +494,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
.addSort(Sort.by("message"))//
.setPageable(Pageable.unpaged());
template.search(query, SampleEntity.class).as(StepVerifier::create) //
operations.search(query, SampleEntity.class).as(StepVerifier::create) //
.expectNextCount(100) //
.verifyComplete();
}
@ -523,7 +511,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
NativeSearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.addAggregation(AggregationBuilders.terms("messages").field("message")).build();
template.aggregate(query, SampleEntity.class) //
operations.aggregate(query, SampleEntity.class) //
.as(StepVerifier::create) //
.consumeNextWith(aggregation -> {
assertThat(aggregation.getName()).isEqualTo("messages");
@ -538,7 +526,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-567, DATAES-767
public void aggregateShouldErrorWhenIndexDoesNotExist() {
template
operations
.aggregate(new CriteriaQuery(Criteria.where("message").is("some message")), SampleEntity.class,
IndexCoordinates.of("no-such-index")) //
.as(StepVerifier::create) //
@ -548,7 +536,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-519, DATAES-767
public void countShouldReturnZeroWhenIndexDoesNotExist() {
template.count(SampleEntity.class) //
operations.count(SampleEntity.class) //
.as(StepVerifier::create) //
.expectError(ElasticsearchStatusException.class);
}
@ -558,7 +546,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
index(randomEntity("test message"), randomEntity("test test"), randomEntity("some message"));
template.count(SampleEntity.class) //
operations.count(SampleEntity.class) //
.as(StepVerifier::create) //
.expectNext(3L) //
.verifyComplete();
@ -571,7 +559,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("test"));
template.count(query, SampleEntity.class) //
operations.count(query, SampleEntity.class) //
.as(StepVerifier::create) //
.expectNext(2L) //
.verifyComplete();
@ -580,7 +568,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-519, DATAES-767
public void deleteShouldErrorWhenIndexDoesNotExist() {
template.delete("does-not-exists", IndexCoordinates.of("no-such-index")) //
operations.delete("does-not-exists", IndexCoordinates.of("no-such-index")) //
.as(StepVerifier::create)//
.expectError(ElasticsearchStatusException.class);
}
@ -591,7 +579,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = randomEntity("test message");
index(sampleEntity);
template.delete(sampleEntity.getId(), SampleEntity.class) //
operations.delete(sampleEntity.getId(), SampleEntity.class) //
.as(StepVerifier::create)//
.expectNext(sampleEntity.getId()) //
.verifyComplete();
@ -603,7 +591,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = randomEntity("test message");
index(sampleEntity);
template.delete(sampleEntity.getId(), IndexCoordinates.of(DEFAULT_INDEX)) //
operations.delete(sampleEntity.getId(), IndexCoordinates.of(indexNameProvider.indexName())) //
.as(StepVerifier::create)//
.expectNext(sampleEntity.getId()) //
.verifyComplete();
@ -615,7 +603,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = randomEntity("test message");
index(sampleEntity);
template.delete(sampleEntity) //
operations.delete(sampleEntity) //
.as(StepVerifier::create)//
.expectNext(sampleEntity.getId()) //
.verifyComplete();
@ -626,7 +614,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity sampleEntity = randomEntity("test message");
template.delete(sampleEntity) //
operations.delete(sampleEntity) //
.as(StepVerifier::create)//
.verifyComplete();
}
@ -636,7 +624,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("test"));
template.delete(query, SampleEntity.class) //
operations.delete(query, SampleEntity.class) //
.as(StepVerifier::create) //
.consumeNextWith(byQueryResponse -> {
assertThat(byQueryResponse.getDeleted()).isEqualTo(0L);
@ -650,25 +638,25 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
IndexCoordinates thisIndex = IndexCoordinates.of(indexPrefix + "-this");
IndexCoordinates thatIndex = IndexCoordinates.of(indexPrefix + "-that");
template.save(randomEntity("test"), thisIndex) //
.then(template.save(randomEntity("test"), thatIndex)) //
operations.save(randomEntity("test"), thisIndex) //
.then(operations.save(randomEntity("test"), thatIndex)) //
.then() //
.as(StepVerifier::create)//
.verifyComplete();
template.indexOps(thisIndex).refresh().then(template.indexOps(thatIndex).refresh()).block();
operations.indexOps(thisIndex).refresh().then(operations.indexOps(thatIndex).refresh()).block();
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() //
.withQuery(termQuery("message", "test")) //
.build();
template.delete(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) //
operations.delete(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) //
.map(ByQueryResponse::getDeleted) //
.as(StepVerifier::create) //
.expectNext(2L) //
.verifyComplete();
template.indexOps(thisIndex).delete().then(template.indexOps(thatIndex).delete()).block();
operations.indexOps(thisIndex).delete().then(operations.indexOps(thatIndex).delete()).block();
}
@Test // DATAES-547
@ -678,25 +666,25 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
IndexCoordinates thisIndex = IndexCoordinates.of(indexPrefix + "-this");
IndexCoordinates thatIndex = IndexCoordinates.of(indexPrefix + "-that");
template.save(randomEntity("positive"), thisIndex) //
.then(template.save(randomEntity("positive"), thatIndex)) //
operations.save(randomEntity("positive"), thisIndex) //
.then(operations.save(randomEntity("positive"), thatIndex)) //
.then() //
.as(StepVerifier::create)//
.verifyComplete();
template.indexOps(thisIndex).refresh().then(template.indexOps(thatIndex).refresh()).block();
operations.indexOps(thisIndex).refresh().then(operations.indexOps(thatIndex).refresh()).block();
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() //
.withQuery(termQuery("message", "negative")) //
.build();
template.delete(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) //
operations.delete(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) //
.map(ByQueryResponse::getDeleted) //
.as(StepVerifier::create) //
.expectNext(0L) //
.verifyComplete();
template.indexOps(thisIndex).delete().then(template.indexOps(thatIndex).delete()).block();
operations.indexOps(thisIndex).delete().then(operations.indexOps(thatIndex).delete()).block();
}
@Test // DATAES-504
@ -706,7 +694,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("test"));
template.delete(query, SampleEntity.class) //
operations.delete(query, SampleEntity.class) //
.map(ByQueryResponse::getDeleted) //
.as(StepVerifier::create) //
.expectNext(2L) //
@ -720,7 +708,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("luke"));
template.delete(query, SampleEntity.class) //
operations.delete(query, SampleEntity.class) //
.map(ByQueryResponse::getDeleted) //
.as(StepVerifier::create) //
.expectNext(0L) //
@ -744,7 +732,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
.withPageable(PageRequest.of(0, 25)) //
.build();
template.search(query, SampleEntity.class, IndexCoordinates.of(DEFAULT_INDEX)) //
operations.search(query, SampleEntity.class, IndexCoordinates.of(indexNameProvider.indexName())) //
.as(StepVerifier::create) //
.expectNextCount(2) //
.verifyComplete();
@ -761,7 +749,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
.withSort(new FieldSortBuilder("rate").order(SortOrder.DESC)) //
.build();
template.search(query, SampleEntity.class) //
operations.search(query, SampleEntity.class) //
.as(StepVerifier::create) //
.consumeNextWith(it -> {
List<Object> sortValues = it.getSortValues();
@ -784,7 +772,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
.withIds(Arrays.asList(entity1.getId(), entity2.getId())) //
.build();
template.multiGet(query, SampleEntity.class, IndexCoordinates.of(DEFAULT_INDEX)) //
operations.multiGet(query, SampleEntity.class, IndexCoordinates.of(indexNameProvider.indexName())) //
.map(MultiGetItem::getItem).as(StepVerifier::create) //
.expectNext(entity1, entity2) //
.verifyComplete();
@ -804,7 +792,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
.withFields("message") //
.build();
template.multiGet(query, SampleEntity.class, IndexCoordinates.of(DEFAULT_INDEX)) //
operations.multiGet(query, SampleEntity.class, IndexCoordinates.of(indexNameProvider.indexName())) //
.as(StepVerifier::create) //
.expectNextCount(2) //
.verifyComplete();
@ -834,12 +822,12 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
.build();
List<UpdateQuery> queries = Arrays.asList(updateQuery1, updateQuery2);
template.bulkUpdate(queries, IndexCoordinates.of(DEFAULT_INDEX)).block();
operations.bulkUpdate(queries, IndexCoordinates.of(indexNameProvider.indexName())).block();
NativeSearchQuery getQuery = new NativeSearchQueryBuilder() //
.withIds(Arrays.asList(entity1.getId(), entity2.getId())) //
.build();
template.multiGet(getQuery, SampleEntity.class, IndexCoordinates.of(DEFAULT_INDEX)) //
operations.multiGet(getQuery, SampleEntity.class, IndexCoordinates.of(indexNameProvider.indexName())) //
.map(MultiGetItem::getItem) //
.as(StepVerifier::create) //
.expectNextMatches(entity -> entity.getMessage().equals("updated 1")) //
@ -854,12 +842,11 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
SampleEntity entity2 = randomEntity("test message 2");
entity2.rate = 2;
template.saveAll(Mono.just(Arrays.asList(entity1, entity2)), IndexCoordinates.of(DEFAULT_INDEX)) //
.then(indexOperations.refresh()) //
.block();
operations.saveAll(Mono.just(Arrays.asList(entity1, entity2)), IndexCoordinates.of(indexNameProvider.indexName())) //
.then().block();
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
template.search(searchQuery, SampleEntity.class, IndexCoordinates.of(DEFAULT_INDEX)) //
operations.search(searchQuery, SampleEntity.class, IndexCoordinates.of(indexNameProvider.indexName())) //
.as(StepVerifier::create) //
.expectNextMatches(hit -> entity1.equals(hit.getContent()) || entity2.equals(hit.getContent())) //
.expectNextMatches(hit -> entity1.equals(hit.getContent()) || entity2.equals(hit.getContent())) //
@ -868,7 +855,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-753
void shouldReturnEmptyFluxOnSaveAllWithEmptyInput() {
template.saveAll(Collections.emptyList(), IndexCoordinates.of(DEFAULT_INDEX)) //
operations.saveAll(Collections.emptyList(), IndexCoordinates.of(indexNameProvider.indexName())) //
.as(StepVerifier::create) //
.verifyComplete();
}
@ -877,9 +864,9 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
void getShouldReturnSeqNoPrimaryTerm() {
OptimisticEntity original = new OptimisticEntity();
original.setMessage("It's fine");
OptimisticEntity saved = template.save(original).block();
OptimisticEntity saved = operations.save(original).block();
template.get(saved.getId(), OptimisticEntity.class).as(StepVerifier::create)
operations.get(saved.getId(), OptimisticEntity.class).as(StepVerifier::create)
.assertNext(this::assertThatSeqNoPrimaryTermIsFilled).verifyComplete();
}
@ -895,11 +882,11 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
void multiGetShouldReturnSeqNoPrimaryTerm() {
OptimisticEntity original = new OptimisticEntity();
original.setMessage("It's fine");
OptimisticEntity saved = template.save(original).block();
OptimisticEntity saved = operations.save(original).block();
template
operations
.multiGet(multiGetQueryForOne(saved.getId()), OptimisticEntity.class,
template.getIndexCoordinatesFor(OptimisticEntity.class)) //
operations.getIndexCoordinatesFor(OptimisticEntity.class)) //
.map(MultiGetItem::getItem) //
.as(StepVerifier::create) //
.assertNext(this::assertThatSeqNoPrimaryTermIsFilled).verifyComplete();
@ -913,13 +900,13 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
void searchShouldReturnSeqNoPrimaryTerm() {
OptimisticEntity original = new OptimisticEntity();
original.setMessage("It's fine");
OptimisticEntity saved = template.save(original).block();
OptimisticEntity saved = operations.save(original).block();
template.indexOps(OptimisticEntity.class).refresh().block();
operations.indexOps(OptimisticEntity.class).refresh().block();
template
operations
.search(searchQueryForOne(saved.getId()), OptimisticEntity.class,
template.getIndexCoordinatesFor(OptimisticEntity.class))
operations.getIndexCoordinatesFor(OptimisticEntity.class))
.map(SearchHit::getContent).as(StepVerifier::create).assertNext(this::assertThatSeqNoPrimaryTermIsFilled)
.verifyComplete();
}
@ -932,16 +919,16 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
void shouldThrowOptimisticLockingFailureExceptionWhenConcurrentUpdateOccursOnEntityWithSeqNoPrimaryTermProperty() {
OptimisticEntity original = new OptimisticEntity();
original.setMessage("It's fine");
OptimisticEntity saved = template.save(original).block();
OptimisticEntity saved = operations.save(original).block();
OptimisticEntity forEdit1 = template.get(saved.getId(), OptimisticEntity.class).block();
OptimisticEntity forEdit2 = template.get(saved.getId(), OptimisticEntity.class).block();
OptimisticEntity forEdit1 = operations.get(saved.getId(), OptimisticEntity.class).block();
OptimisticEntity forEdit2 = operations.get(saved.getId(), OptimisticEntity.class).block();
forEdit1.setMessage("It'll be ok");
template.save(forEdit1).block();
operations.save(forEdit1).block();
forEdit2.setMessage("It'll be great");
template.save(forEdit2) //
operations.save(forEdit2) //
.as(StepVerifier::create) //
.expectError(OptimisticLockingFailureException.class) //
.verify();
@ -951,28 +938,28 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
void shouldThrowOptimisticLockingFailureExceptionWhenConcurrentUpdateOccursOnVersionedEntityWithSeqNoPrimaryTermProperty() {
OptimisticAndVersionedEntity original = new OptimisticAndVersionedEntity();
original.setMessage("It's fine");
OptimisticAndVersionedEntity saved = template.save(original).block();
OptimisticAndVersionedEntity saved = operations.save(original).block();
OptimisticAndVersionedEntity forEdit1 = template.get(saved.getId(), OptimisticAndVersionedEntity.class).block();
OptimisticAndVersionedEntity forEdit2 = template.get(saved.getId(), OptimisticAndVersionedEntity.class).block();
OptimisticAndVersionedEntity forEdit1 = operations.get(saved.getId(), OptimisticAndVersionedEntity.class).block();
OptimisticAndVersionedEntity forEdit2 = operations.get(saved.getId(), OptimisticAndVersionedEntity.class).block();
forEdit1.setMessage("It'll be ok");
template.save(forEdit1).block();
operations.save(forEdit1).block();
forEdit2.setMessage("It'll be great");
template.save(forEdit2).as(StepVerifier::create).expectError(OptimisticLockingFailureException.class).verify();
operations.save(forEdit2).as(StepVerifier::create).expectError(OptimisticLockingFailureException.class).verify();
}
@Test // DATAES-799
void shouldAllowFullReplaceOfEntityWithBothSeqNoPrimaryTermAndVersion() {
OptimisticAndVersionedEntity original = new OptimisticAndVersionedEntity();
original.setMessage("It's fine");
OptimisticAndVersionedEntity saved = template.save(original).block();
OptimisticAndVersionedEntity saved = operations.save(original).block();
OptimisticAndVersionedEntity forEdit = template.get(saved.getId(), OptimisticAndVersionedEntity.class).block();
OptimisticAndVersionedEntity forEdit = operations.get(saved.getId(), OptimisticAndVersionedEntity.class).block();
forEdit.setMessage("It'll be ok");
template.save(forEdit).as(StepVerifier::create).expectNextCount(1).verifyComplete();
operations.save(forEdit).as(StepVerifier::create).expectNextCount(1).verifyComplete();
}
@Test // DATAES-909
@ -988,11 +975,12 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
.withDocument(document) //
.build();
UpdateResponse updateResponse = template.update(updateQuery, IndexCoordinates.of(DEFAULT_INDEX)).block();
UpdateResponse updateResponse = operations.update(updateQuery, IndexCoordinates.of(indexNameProvider.indexName()))
.block();
assertThat(updateResponse).isNotNull();
assertThat(updateResponse.getResult()).isEqualTo(UpdateResponse.Result.UPDATED);
template.get(entity.getId(), SampleEntity.class, IndexCoordinates.of(DEFAULT_INDEX)) //
operations.get(entity.getId(), SampleEntity.class, IndexCoordinates.of(indexNameProvider.indexName())) //
.as(StepVerifier::create) //
.expectNextMatches(foundEntity -> foundEntity.getMessage().equals("updated")) //
.verifyComplete();
@ -1000,28 +988,28 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // DATAES-908
void shouldFillVersionOnSaveOne() {
VersionedEntity saved = template.save(new VersionedEntity()).block();
VersionedEntity saved = operations.save(new VersionedEntity()).block();
assertThat(saved.getVersion()).isNotNull();
}
@Test // DATAES-908
void shouldFillVersionOnSaveAll() {
VersionedEntity saved = template.saveAll(singletonList(new VersionedEntity()), VersionedEntity.class).blockLast();
VersionedEntity saved = operations.saveAll(singletonList(new VersionedEntity()), VersionedEntity.class).blockLast();
assertThat(saved.getVersion()).isNotNull();
}
@Test // DATAES-908
void shouldFillSeqNoPrimaryTermOnSaveOne() {
OptimisticEntity saved = template.save(new OptimisticEntity()).block();
OptimisticEntity saved = operations.save(new OptimisticEntity()).block();
assertThatSeqNoPrimaryTermIsFilled(saved);
}
@Test // DATAES-908
void shouldFillSeqNoPrimaryTermOnSaveAll() {
OptimisticEntity saved = template.saveAll(singletonList(new OptimisticEntity()), OptimisticEntity.class)
OptimisticEntity saved = operations.saveAll(singletonList(new OptimisticEntity()), OptimisticEntity.class)
.blockLast();
assertThatSeqNoPrimaryTermIsFilled(saved);
@ -1037,9 +1025,9 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
Query query = Query.findAll().setPageable(PageRequest.of(0, 5));
template.saveAll(Mono.just(entities), SampleEntity.class).then(indexOperations.refresh()).block();
operations.saveAll(Mono.just(entities), SampleEntity.class).then().block();
Mono<SearchPage<SampleEntity>> searchPageMono = template.searchForPage(query, SampleEntity.class);
Mono<SearchPage<SampleEntity>> searchPageMono = operations.searchForPage(query, SampleEntity.class);
searchPageMono.as(StepVerifier::create) //
.consumeNextWith(searchPage -> {
@ -1057,19 +1045,19 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
String indexName = "foo-" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy.MM"));
String dateMathIndexName = "<foo-{now/M{yyyy.MM}}>";
template.indexOps(IndexCoordinates.of(dateMathIndexName)) //
operations.indexOps(IndexCoordinates.of(dateMathIndexName)) //
.create() //
.as(StepVerifier::create) //
.expectNext(true) //
.verifyComplete(); //
template.indexOps(IndexCoordinates.of(indexName)) //
operations.indexOps(IndexCoordinates.of(indexName)) //
.exists() //
.as(StepVerifier::create) //
.expectNext(true) //
.verifyComplete(); //
template.indexOps(IndexCoordinates.of(dateMathIndexName)) //
operations.indexOps(IndexCoordinates.of(dateMathIndexName)) //
.delete() //
.as(StepVerifier::create) //
.expectNext(true) //
@ -1082,12 +1070,12 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
ElasticsearchTemplateTests.SampleEntity entity = ElasticsearchTemplateTests.SampleEntity.builder().id("42")
.message("a message with text").build();
template.save(entity).as(StepVerifier::create).expectNextCount(1).verifyComplete();
operations.save(entity).as(StepVerifier::create).expectNextCount(1).verifyComplete();
Criteria criteria = new Criteria("message").contains("with");
CriteriaQuery query = new CriteriaQuery(criteria);
template.search(query, ElasticsearchTemplateTests.SampleEntity.class).as(StepVerifier::create)
operations.search(query, ElasticsearchTemplateTests.SampleEntity.class).as(StepVerifier::create)
.consumeNextWith(searchHit -> {
Explanation explanation = searchHit.getExplanation();
assertThat(explanation).isNull();
@ -1100,13 +1088,13 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
ElasticsearchTemplateTests.SampleEntity entity = ElasticsearchTemplateTests.SampleEntity.builder().id("42")
.message("a message with text").build();
template.save(entity).as(StepVerifier::create).expectNextCount(1).verifyComplete();
operations.save(entity).as(StepVerifier::create).expectNextCount(1).verifyComplete();
Criteria criteria = new Criteria("message").contains("with");
CriteriaQuery query = new CriteriaQuery(criteria);
query.setExplain(true);
template.search(query, ElasticsearchTemplateTests.SampleEntity.class).as(StepVerifier::create)
operations.search(query, ElasticsearchTemplateTests.SampleEntity.class).as(StepVerifier::create)
.consumeNextWith(searchHit -> {
Explanation explanation = searchHit.getExplanation();
assertThat(explanation).isNotNull();
@ -1116,11 +1104,12 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
@Test // #1646, #1718
@DisplayName("should return a list of info for specific index")
void shouldReturnInformationListOfAllIndices() {
String indexName = "test-index-reactive-information-list";
String aliasName = "testindexinformationindex";
ReactiveIndexOperations indexOps = template.indexOps(EntityWithSettingsAndMappingsReactive.class);
String indexName = indexNameProvider.indexName();
String aliasName = indexName + "-alias";
ReactiveIndexOperations indexOps = operations.indexOps(EntityWithSettingsAndMappingsReactive.class);
indexOps.createWithMapping().block();
// beforeEach uses SampleEntity, so recreate the index here
indexOps.delete().then(indexOps.createWithMapping()).block();
AliasActionParameters parameters = AliasActionParameters.builder().withAliases(aliasName).withIndices(indexName)
.withIsHidden(false).withIsWriteIndex(false).withRouting("indexrouting").withSearchRouting("searchrouting")
@ -1158,7 +1147,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
ImmutableEntity entity = new ImmutableEntity(null, "some text", null);
AtomicReference<ImmutableEntity> savedEntity = new AtomicReference<>();
template.save(entity).as(StepVerifier::create).consumeNextWith(saved -> {
operations.save(entity).as(StepVerifier::create).consumeNextWith(saved -> {
assertThat(saved).isNotNull();
savedEntity.set(saved);
assertThat(saved.getId()).isNotEmpty();
@ -1166,7 +1155,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
assertThat(seqNoPrimaryTerm).isNotNull();
}).verifyComplete();
template.get(savedEntity.get().getId(), ImmutableEntity.class).as(StepVerifier::create)
operations.get(savedEntity.get().getId(), ImmutableEntity.class).as(StepVerifier::create)
.consumeNextWith(retrieved -> {
assertThat(retrieved).isEqualTo(savedEntity.get());
}).verifyComplete();
@ -1195,58 +1184,18 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
private void index(SampleEntity... entities) {
IndexCoordinates indexCoordinates = IndexCoordinates.of(DEFAULT_INDEX);
IndexCoordinates indexCoordinates = IndexCoordinates.of(indexNameProvider.indexName());
if (entities.length == 1) {
template.save(entities[0], indexCoordinates).then(indexOperations.refresh()).block();
operations.save(entities[0], indexCoordinates).block();
} else {
template.saveAll(Mono.just(Arrays.asList(entities)), indexCoordinates).then(indexOperations.refresh()).block();
operations.saveAll(Mono.just(Arrays.asList(entities)), indexCoordinates).then().block();
}
}
// endregion
// region Entities
@Document(indexName = "marvel")
static class Person {
@Nullable private @Id String id;
@Nullable private String name;
@Nullable private int age;
public Person() {}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Nullable
public String getId() {
return id;
}
public void setId(@Nullable String id) {
this.id = id;
}
@Nullable
public String getName() {
return name;
}
public void setName(@Nullable String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
static class Message {
@Nullable String message;
@ -1281,7 +1230,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
}
}
@Document(indexName = DEFAULT_INDEX)
@Document(indexName = "#{@indexNameProvider.indexName()}")
static class SampleEntity {
@Nullable @Id private String id;
@Nullable @Field(type = Text, store = true, fielddata = true) private String message;
@ -1351,7 +1300,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
}
}
@Document(indexName = "test-index-reactive-optimistic-entity-template")
@Document(indexName = "#{@indexNameProvider.indexName()}")
static class OptimisticEntity {
@Nullable @Id private String id;
@Nullable private String message;
@ -1385,7 +1334,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
}
}
@Document(indexName = "test-index-reactive-optimistic-and-versioned-entity-template")
@Document(indexName = "#{@indexNameProvider.indexName()}")
static class OptimisticAndVersionedEntity {
@Nullable @Id private String id;
@Nullable private String message;
@ -1429,7 +1378,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
}
}
@Document(indexName = "test-index-reactive-versioned-entity-template")
@Document(indexName = "#{@indexNameProvider.indexName()}")
static class VersionedEntity {
@Nullable @Id private String id;
@Nullable @Version private Long version;
@ -1453,7 +1402,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
}
}
@Document(indexName = "test-index-reactive-information-list", createIndex = false)
@Document(indexName = "#{@indexNameProvider.indexName()}", createIndex = false)
@Setting(settingPath = "settings/test-settings.json")
@Mapping(mappingPath = "mappings/test-mappings.json")
private static class EntityWithSettingsAndMappingsReactive {
@ -1469,7 +1418,7 @@ public class ReactiveElasticsearchTemplateIntegrationTests {
}
}
@Document(indexName = "immutable-class")
@Document(indexName = "#{@indexNameProvider.indexName()}")
private static final class ImmutableEntity {
@Id private final String id;
@Field(type = FieldType.Text) private final String text;

View File

@ -38,9 +38,8 @@ import java.util.Set;
import org.assertj.core.data.Percentage;
import org.elasticsearch.search.suggest.completion.context.ContextMapping;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
@ -84,27 +83,18 @@ import org.springframework.test.context.ContextConfiguration;
public class MappingBuilderIntegrationTests extends MappingContextBaseTests {
@Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@AfterEach
@BeforeEach
public void deleteIndices() {
indexOperations = operations.indexOps(SimpleRecursiveEntity.class);
indexOperations.delete();
operations.indexOps(StockPrice.class).delete();
operations.indexOps(SampleInheritedEntity.class).delete();
operations.indexOps(User.class).delete();
operations.indexOps(Group.class).delete();
operations.indexOps(Book.class).delete();
operations.indexOps(NormalizerEntity.class).delete();
operations.indexOps(CopyToEntity.class).delete();
@Test
@Order(java.lang.Integer.MAX_VALUE)
void cleanup() {
operations.indexOps(IndexCoordinates.of("*")).delete();
}
@Test
public void shouldNotFailOnCircularReference() {
operations.indexOps(SimpleRecursiveEntity.class).create();
indexOperations.putMapping(SimpleRecursiveEntity.class);
IndexOperations indexOperations = operations.indexOps(SimpleRecursiveEntity.class);
indexOperations.createWithMapping();
indexOperations.refresh();
}
@ -274,7 +264,6 @@ public class MappingBuilderIntegrationTests extends MappingContextBaseTests {
IndexOperations indexOps = operations.indexOps(DenseVectorEntity.class);
indexOps.create();
indexOps.putMapping();
indexOps.delete();
}
@Test // #1370
@ -284,7 +273,7 @@ public class MappingBuilderIntegrationTests extends MappingContextBaseTests {
IndexOperations indexOps = operations.indexOps(DisabledMappingEntity.class);
indexOps.create();
indexOps.putMapping();
indexOps.delete();
}
@Test // #1370
@ -294,7 +283,7 @@ public class MappingBuilderIntegrationTests extends MappingContextBaseTests {
IndexOperations indexOps = operations.indexOps(DisabledMappingProperty.class);
indexOps.create();
indexOps.putMapping();
indexOps.delete();
}
@Test // #1767
@ -304,7 +293,7 @@ public class MappingBuilderIntegrationTests extends MappingContextBaseTests {
IndexOperations indexOps = operations.indexOps(DynamicMappingEntity.class);
indexOps.create();
indexOps.putMapping();
indexOps.delete();
}
@Test // #638
@ -314,7 +303,7 @@ public class MappingBuilderIntegrationTests extends MappingContextBaseTests {
IndexOperations indexOps = operations.indexOps(DynamicDetectionMapping.class);
indexOps.create();
indexOps.putMapping();
indexOps.delete();
}
@Test // #1816
@ -324,7 +313,7 @@ public class MappingBuilderIntegrationTests extends MappingContextBaseTests {
IndexOperations indexOps = operations.indexOps(RuntimeFieldEntity.class);
indexOps.create();
indexOps.putMapping();
indexOps.delete();
}
// region entities

View File

@ -24,10 +24,11 @@ import java.lang.Long;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id;
@ -35,12 +36,12 @@ import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.lang.Nullable;
import org.springframework.test.context.ContextConfiguration;
@ -56,31 +57,31 @@ public class CriteriaQueryIntegrationTests {
@Configuration
@Import({ ElasticsearchRestTemplateConfiguration.class })
static class Config {}
private final IndexCoordinates index = IndexCoordinates.of("test-index-sample-core-query");
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider();
}
}
@Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@Autowired private IndexNameProvider indexNameProvider;
@BeforeEach
public void before() {
indexOperations = operations.indexOps(SampleEntity.class);
indexOperations.delete();
indexOperations.create();
indexOperations.putMapping(SampleEntity.class);
indexOperations.refresh();
indexNameProvider.increment();
operations.indexOps(SampleEntity.class).createWithMapping();
}
@AfterEach
void after() {
indexOperations.delete();
@Test
@Order(java.lang.Integer.MAX_VALUE)
void cleanup() {
operations.indexOps(IndexCoordinates.of("*")).delete();
}
@Test // ,DATAES-706
@Test // DATAES-706
public void shouldPerformAndOperationOnCriteriaEntries() {
// given
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(nextIdAsString());
sampleEntity1.setMessage("some test message");
@ -89,22 +90,18 @@ public class CriteriaQueryIntegrationTests {
sampleEntity2.setId(nextIdAsString());
sampleEntity2.setMessage("some other message");
operations.save(sampleEntity2);
indexOperations.refresh();
// when
CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("test").and("message").contains("some"));
SearchHit<SampleEntity> searchHit = operations.searchOne(criteriaQuery, SampleEntity.class, index);
SearchHit<SampleEntity> searchHit = operations.searchOne(criteriaQuery, SampleEntity.class);
// then
assertThat(searchHit).isNotNull();
assertThat(searchHit.getId()).isEqualTo(sampleEntity1.id);
}
@Test // ,DATAES-706
@Test // DATAES-706
public void shouldPerformOrOperationOnCriteriaEntries() {
// given
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(nextIdAsString());
sampleEntity1.setMessage("some test message");
@ -113,23 +110,19 @@ public class CriteriaQueryIntegrationTests {
sampleEntity2.setId(nextIdAsString());
sampleEntity2.setMessage("some other message");
operations.save(sampleEntity2);
indexOperations.refresh();
// when
CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("test").or("message").contains("other"));
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(searchHits).isNotNull();
assertThat(searchHits.getSearchHits().stream().map(SearchHit::getId)).containsExactlyInAnyOrder(sampleEntity1.id,
sampleEntity2.id);
}
@Test // ,DATAES-706
@Test // DATAES-706
public void shouldPerformAndOperationWithinCriteria() {
// given
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(nextIdAsString());
sampleEntity1.setMessage("some test message");
@ -138,22 +131,18 @@ public class CriteriaQueryIntegrationTests {
sampleEntity2.setId(nextIdAsString());
sampleEntity2.setMessage("some other message");
operations.save(sampleEntity2);
indexOperations.refresh();
// when
CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("test").and(new Criteria("message").contains("some")));
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(searchHits).isNotNull();
assertThat(searchHits.getTotalHits()).isGreaterThanOrEqualTo(1);
}
@Test // ,DATAES-706
@Test // DATAES-706
public void shouldPerformOrOperationWithinCriteria() {
// given
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(nextIdAsString());
sampleEntity1.setMessage("some test message");
@ -162,14 +151,11 @@ public class CriteriaQueryIntegrationTests {
sampleEntity2.setId(nextIdAsString());
sampleEntity2.setMessage("some other message");
operations.save(sampleEntity2);
indexOperations.refresh();
// when
CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("test").or(new Criteria("message").contains("other")));
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(searchHits).isNotNull();
assertThat(searchHits.getSearchHits().stream().map(SearchHit::getId)).containsExactlyInAnyOrder(sampleEntity1.id,
sampleEntity2.id);
@ -178,9 +164,8 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformIsOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
@ -192,12 +177,12 @@ public class CriteriaQueryIntegrationTests {
indexQuery.setObject(sampleEntity);
indexQueries.add(indexQuery);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message"));
// when
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
@ -207,7 +192,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformMultipleIsOperations() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -234,14 +218,12 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message"));
// when
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(searchHits.getTotalHits()).isEqualTo(1);
}
@ -249,7 +231,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformEndsWithOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -276,15 +257,13 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
Criteria criteria = new Criteria("message").endsWith("end");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
// when
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class, index);
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class);
// then
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(sampleEntity).isNotNull();
}
@ -292,7 +271,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformStartsWithOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
@ -318,15 +296,13 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
Criteria criteria = new Criteria("message").startsWith("start");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
// when
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class, index);
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class);
// then
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(sampleEntity).isNotNull();
}
@ -334,7 +310,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformContainsOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
@ -360,14 +335,12 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("contains"));
// when
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class, index);
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class);
// then
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(sampleEntity).isNotNull();
}
@ -401,12 +374,12 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").expression("+elasticsearch || test"));
// when
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class, index);
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class);
// then
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
@ -416,7 +389,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldExecuteCriteriaChain() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
@ -442,15 +414,13 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").startsWith("some").endsWith("search").contains("message").is("some message search"));
// when
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class, index);
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class);
// then
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(sampleEntity).isNotNull();
}
@ -458,7 +428,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformIsNotOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
@ -484,14 +453,12 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("foo").not());
// when
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(criteriaQuery.getCriteria().isNegating()).isTrue();
assertThat(searchHits).isNotNull();
assertThat(searchHits.iterator().next().getContent().getMessage()).doesNotContain("foo");
@ -500,7 +467,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformBetweenOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
@ -528,21 +494,18 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100, 150));
// when
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class, index);
SearchHit<SampleEntity> sampleEntity = operations.searchOne(criteriaQuery, SampleEntity.class);
// then
assertThat(sampleEntity).isNotNull();
}
@Test
public void shouldPerformBetweenOperationWithoutUpperBound() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
@ -570,14 +533,12 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(350, null));
// when
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(searchHits).isNotNull();
assertThat(searchHits.getTotalHits()).isGreaterThanOrEqualTo(1);
}
@ -585,7 +546,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformBetweenOperationWithoutLowerBound() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
@ -613,14 +573,12 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(null, 550));
// when
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(searchHits).isNotNull();
assertThat(searchHits.getTotalHits()).isGreaterThanOrEqualTo(1);
}
@ -628,7 +586,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformLessThanEqualOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
@ -656,14 +613,12 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").lessThanEqual(750));
// when
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(searchHits).isNotNull();
assertThat(searchHits.getTotalHits()).isGreaterThanOrEqualTo(1);
}
@ -671,7 +626,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformGreaterThanEquals() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
@ -699,14 +653,12 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").greaterThanEqual(950));
// when
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(searchHits).isNotNull();
assertThat(searchHits.getTotalHits()).isGreaterThanOrEqualTo(1);
}
@ -714,7 +666,6 @@ public class CriteriaQueryIntegrationTests {
@Test
public void shouldPerformBoostOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = nextIdAsString();
@ -742,14 +693,12 @@ public class CriteriaQueryIntegrationTests {
indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1));
// when
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
// then
assertThat(searchHits.getTotalHits()).isGreaterThanOrEqualTo(1);
}
@ -760,13 +709,12 @@ public class CriteriaQueryIntegrationTests {
indexQueries.add(buildIndex(new SampleEntity("1", "ab")));
indexQueries.add(buildIndex(new SampleEntity("2", "bc")));
indexQueries.add(buildIndex(new SampleEntity("3", "ac")));
operations.bulkIndex(indexQueries, index);
indexOperations.refresh();
operations.bulkIndex(indexQueries, SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("a").or(new Criteria("message").contains("b")));
criteriaQuery.setMinScore(2.0F);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class, index);
SearchHits<SampleEntity> searchHits = operations.search(criteriaQuery, SampleEntity.class);
assertThat(searchHits.getTotalHits()).isEqualTo(1);
assertThat(searchHits.getSearchHit(0).getContent().getMessage()).isEqualTo("ab");
@ -775,7 +723,6 @@ public class CriteriaQueryIntegrationTests {
@Test // DATAES-213
public void shouldEscapeValue() {
// given
String documentId = nextIdAsString();
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
@ -785,19 +732,16 @@ public class CriteriaQueryIntegrationTests {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(documentId);
indexQuery.setObject(sampleEntity);
operations.index(indexQuery, index);
indexOperations.refresh();
operations.index(indexQuery, IndexCoordinates.of(indexNameProvider.indexName()));
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("Hello World!"));
// when
SearchHit<SampleEntity> sampleEntity1 = operations.searchOne(criteriaQuery, SampleEntity.class, index);
SearchHit<SampleEntity> sampleEntity1 = operations.searchOne(criteriaQuery, SampleEntity.class);
// then
assertThat(sampleEntity1).isNotNull();
}
@Document(indexName = "test-index-sample-core-query")
@Document(indexName = "#{@indexNameProvider.indexName()}")
static class SampleEntity {
@Nullable @Id private String id;
@Nullable @Field(type = Text, store = true, fielddata = true) private String type;

View File

@ -15,10 +15,12 @@
*/
package org.springframework.data.elasticsearch.core.query;
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.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.test.context.ContextConfiguration;
/**
@ -29,5 +31,11 @@ public class CriteriaQueryTransportIntegrationTests extends CriteriaQueryIntegra
@Configuration
@Import({ ElasticsearchTemplateConfiguration.class })
@EnableElasticsearchRepositories(considerNestedRepositories = true)
static class Config {}
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("criteria-query");
}
}
}

View File

@ -15,15 +15,11 @@
*/
package org.springframework.data.elasticsearch.junit.jupiter;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.support.VersionInfo;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.testcontainers.elasticsearch.ElasticsearchContainer;
/**
@ -47,12 +43,10 @@ public class ClusterConnection implements ExtensionContext.Store.CloseableResour
@Nullable private final ClusterConnectionInfo clusterConnectionInfo;
/**
* creates the ClusterConnection, starting a container if necessary.
*
* @param clusterUrl if null or empty a local cluster is tarted
* creates the ClusterConnection, starting a container
*/
public ClusterConnection(@Nullable String clusterUrl) {
clusterConnectionInfo = StringUtils.isEmpty(clusterUrl) ? startElasticsearchContainer() : parseUrl(clusterUrl);
public ClusterConnection() {
clusterConnectionInfo = startElasticsearchContainer();
if (clusterConnectionInfo != null) {
LOGGER.debug(clusterConnectionInfo.toString());
@ -75,28 +69,6 @@ public class ClusterConnection implements ExtensionContext.Store.CloseableResour
return clusterConnectionInfo;
}
/**
* @param clusterUrl the URL to parse
* @return the connection information
*/
private ClusterConnectionInfo parseUrl(String clusterUrl) {
try {
URL url = new URL(clusterUrl);
if (!url.getProtocol().startsWith("http") || url.getPort() <= 0) {
throw new ClusterConnectionException("invalid url " + clusterUrl);
}
return ClusterConnectionInfo.builder() //
.withHostAndPort(url.getHost(), url.getPort()) //
.useSsl(url.getProtocol().equals("https")) //
.build();
} catch (MalformedURLException e) {
throw new ClusterConnectionException(e);
}
}
@Nullable
private ClusterConnectionInfo startElasticsearchContainer() {

View File

@ -46,7 +46,6 @@ import org.springframework.test.context.MergedContextConfiguration;
public class SpringDataElasticsearchExtension
implements BeforeAllCallback, ParameterResolver, ContextCustomizerFactory {
public static final String SPRING_DATA_ELASTICSEARCH_TEST_CLUSTER_URL = "SPRING_DATA_ELASTICSEARCH_TEST_CLUSTER_URL";
private static final Logger LOGGER = LoggerFactory.getLogger(SpringDataElasticsearchExtension.class);
private static final ExtensionContext.Namespace NAMESPACE = ExtensionContext.Namespace
@ -77,7 +76,7 @@ public class SpringDataElasticsearchExtension
}
private ClusterConnection createClusterConnection() {
return new ClusterConnection(System.getenv(SPRING_DATA_ELASTICSEARCH_TEST_CLUSTER_URL));
return new ClusterConnection();
}
@Override
@ -89,7 +88,7 @@ public class SpringDataElasticsearchExtension
/*
* (non javadoc)
* no need to check the paramaterContext and extensionContext here, this was done before in supportsParameter.
* no need to check the parameterContext and extensionContext here, this was done before in supportsParameter.
*/
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)

View File

@ -20,12 +20,16 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
/**
* Combines the {@link SpringDataElasticsearchExtension} and the {@link SpringExtension}.
* Combines the {@link SpringDataElasticsearchExtension} and the {@link SpringExtension}. Tests are executed in
* accordance to the {@link org.junit.jupiter.api.Order} annotation, to be able to have an explicit last test method for
* cleanup (since 4.3)
*
* @author Peter-Josef Meisch
*/
@ -34,5 +38,6 @@ import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringDataElasticsearchExtension.class)
@ExtendWith(SpringExtension.class)
@Tag(Tags.INTEGRATION_TEST)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public @interface SpringIntegrationTest {
}

View File

@ -153,10 +153,6 @@ public class CdiRepositoryTests {
assertThat(personRepository.returnOne()).isEqualTo(1);
}
/**
* @author Mohsin Husen
* @author Artur Konczak
*/
@Document(indexName = "test-index-product-cdi-repository")
static class Product {
@Nullable @Id private String id;
@ -372,7 +368,7 @@ public class CdiRepositoryTests {
}
}
static class Author {
private static class Author {
@Nullable private String id;
@Nullable private String name;

View File

@ -18,21 +18,22 @@ package org.springframework.data.elasticsearch.repositories.complex.custommethod
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.lang.Nullable;
import org.springframework.test.context.ContextConfiguration;
@ -48,38 +49,37 @@ public class ComplexCustomMethodRepositoryTests {
@Configuration
@Import({ ElasticsearchRestTemplateConfiguration.class })
@EnableElasticsearchRepositories(considerNestedRepositories = true)
static class Config {}
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("complex-custom-method");
}
}
@Autowired private ComplexElasticsearchRepository complexRepository;
@Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@Autowired private IndexNameProvider indexNameProvider;
@BeforeEach
public void before() {
indexOperations = operations.indexOps(SampleEntity.class);
IndexInitializer.init(indexOperations);
indexNameProvider.increment();
operations.indexOps(SampleEntity.class).createWithMapping();
}
@AfterEach
void after() {
indexOperations.delete();
@Test
@Order(java.lang.Integer.MAX_VALUE)
void cleanup() {
operations.indexOps(IndexCoordinates.of("*")).delete();
}
@Test
public void shouldExecuteComplexCustomMethod() {
// given
// when
String result = complexRepository.doSomethingSpecial();
// then
assertThat(result).isEqualTo("2+2=4");
}
@Document(indexName = "test-index-sample-repositories-complex-custommethod-autowiring")
@Document(indexName = "#{@indexNameProvider.indexName()}")
static class SampleEntity {
@Nullable @Id private String id;
@Nullable @Field(type = Text, store = true, fielddata = true) private String type;

View File

@ -15,10 +15,12 @@
*/
package org.springframework.data.elasticsearch.repositories.complex.custommethod.autowiring;
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.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.test.context.ContextConfiguration;
/**
@ -29,5 +31,10 @@ public class ComplexCustomMethodRepositoryTransportTests extends ComplexCustomMe
@Configuration
@Import({ ElasticsearchTemplateConfiguration.class })
@EnableElasticsearchRepositories(considerNestedRepositories = true)
static class Config {}
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("complex-custom-method");
}
}
}

View File

@ -18,21 +18,22 @@ package org.springframework.data.elasticsearch.repositories.complex.custommethod
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.lang.Nullable;
import org.springframework.test.context.ContextConfiguration;
@ -47,37 +48,37 @@ public class ComplexCustomMethodRepositoryManualWiringTests {
@Configuration
@Import({ ElasticsearchRestTemplateConfiguration.class })
@EnableElasticsearchRepositories(considerNestedRepositories = true)
static class Config {}
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("complex-custom-method");
}
}
@Autowired private ComplexElasticsearchRepositoryManualWiring complexRepository;
@Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@Autowired private IndexNameProvider indexNameProvider;
@BeforeEach
public void before() {
indexOperations = operations.indexOps(SampleEntity.class);
IndexInitializer.init(indexOperations);
indexNameProvider.increment();
operations.indexOps(SampleEntity.class).createWithMapping();
}
@AfterEach
void after() {
indexOperations.delete();
@Test
@Order(java.lang.Integer.MAX_VALUE)
void cleanup() {
operations.indexOps(IndexCoordinates.of("*")).delete();
}
@Test
public void shouldExecuteComplexCustomMethod() {
// given
// when
String result = complexRepository.doSomethingSpecial();
// then
assertThat(result).isEqualTo("3+3=6");
}
@Document(indexName = "test-index-sample-repository-manual-wiring")
@Document(indexName = "#{@indexNameProvider.indexName()}")
static class SampleEntity {
@Nullable @Id private String id;
@Nullable @Field(type = Text, store = true, fielddata = true) private String type;

View File

@ -15,10 +15,12 @@
*/
package org.springframework.data.elasticsearch.repositories.complex.custommethod.manualwiring;
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.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.test.context.ContextConfiguration;
/**
@ -30,5 +32,10 @@ public class ComplexCustomMethodRepositoryManualWiringTransportTests
@Configuration
@Import({ ElasticsearchTemplateConfiguration.class })
@EnableElasticsearchRepositories(considerNestedRepositories = true)
static class Config {}
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("complex-custom-method");
}
}
}

View File

@ -28,7 +28,6 @@ import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@ -47,16 +46,16 @@ import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.data.elasticsearch.annotations.HighlightField;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.data.elasticsearch.core.geo.GeoBox;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.GeoDistanceOrder;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
@ -76,22 +75,23 @@ import org.springframework.lang.Nullable;
@SpringIntegrationTest
public abstract class CustomMethodRepositoryBaseTests {
@Autowired private IndexNameProvider indexNameProvider;
@Autowired private SampleCustomMethodRepository repository;
@Autowired private SampleStreamingCustomMethodRepository streamingRepository;
@Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach
public void before() {
indexOperations = operations.indexOps(SampleEntity.class);
IndexInitializer.init(indexOperations);
indexNameProvider.increment();
operations.indexOps(SampleEntity.class).createWithMapping();
}
@AfterEach
void after() {
indexOperations.delete();
@Test
@org.junit.jupiter.api.Order(java.lang.Integer.MAX_VALUE)
void cleanup() {
operations.indexOps(IndexCoordinates.of("*")).delete();
}
@Test
@ -1431,13 +1431,15 @@ public abstract class CustomMethodRepositoryBaseTests {
// given
List<SampleEntity> entities = createSampleEntities("abc", 10001);
repository.saveAll(entities);
operations.indexOps(SampleEntity.class).refresh();
// when
Stream<SampleEntity> stream = streamingRepository.findByType("abc");
// then
assertThat(stream).isNotNull();
assertThat(stream.count()).isEqualTo(10001L);
long count = stream.count();
assertThat(count).isEqualTo(10001L);
}
@Test // DATAES-605
@ -1647,7 +1649,7 @@ public abstract class CustomMethodRepositoryBaseTests {
assertThat(count).isEqualTo(20);
}
@Document(indexName = "test-index-sample-repositories-custom-method")
@Document(indexName = "#{@indexNameProvider.indexName()}")
static class SampleEntity {
@Nullable @Id private String id;
@Nullable @Field(type = Text, store = true, fielddata = true) private String type;
@ -1734,6 +1736,7 @@ public abstract class CustomMethodRepositoryBaseTests {
* @author Mohsin Husen
* @author Kevin Leturc
*/
@SuppressWarnings("SpringDataRepositoryMethodParametersInspection")
public interface SampleCustomMethodRepository extends ElasticsearchRepository<SampleEntity, String> {
Page<SampleEntity> findByType(String type, Pageable pageable);

View File

@ -15,10 +15,12 @@
*/
package org.springframework.data.elasticsearch.repositories.custommethod;
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.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.test.context.ContextConfiguration;
/**
@ -34,5 +36,10 @@ public class CustomMethodRepositoryRestTests extends CustomMethodRepositoryBaseT
@EnableElasticsearchRepositories(
basePackages = { "org.springframework.data.elasticsearch.repositories.custommethod" },
considerNestedRepositories = true)
static class Config {}
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("custom-method-repository");
}
}
}

View File

@ -15,10 +15,13 @@
*/
package org.springframework.data.elasticsearch.repositories.custommethod;
import org.junit.jupiter.api.Disabled;
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.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.test.context.ContextConfiguration;
/**
@ -34,6 +37,15 @@ public class CustomMethodRepositoryTests extends CustomMethodRepositoryBaseTests
@EnableElasticsearchRepositories(
basePackages = { "org.springframework.data.elasticsearch.repositories.custommethod" },
considerNestedRepositories = true)
static class Config {}
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider("custom-method-repository");
}
}
@Disabled("this test crashes the transport client connection in some dockerized test container setup")
@Override
public void streamMethodsShouldWorkWithLargeResultSets() {
}
}

View File

@ -21,22 +21,23 @@ import static org.springframework.data.elasticsearch.utils.IdGenerator.*;
import java.util.Arrays;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.test.context.ContextConfiguration;
/**
@ -53,22 +54,28 @@ public class DoubleIDRepositoryTests {
@Configuration
@Import({ ElasticsearchRestTemplateConfiguration.class })
@EnableElasticsearchRepositories(considerNestedRepositories = true)
static class Config {}
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider();
}
}
@Autowired private DoubleIDRepository repository;
@Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@Autowired IndexNameProvider indexNameProvider;
@BeforeEach
public void before() {
indexOperations = operations.indexOps(DoubleIDEntity.class);
IndexInitializer.init(indexOperations);
indexNameProvider.increment();
operations.indexOps(DoubleIDEntity.class).createWithMapping();
}
@AfterEach
public void after() {
indexOperations.delete();
@Test
@Order(Integer.MAX_VALUE)
public void cleanup() {
operations.indexOps(IndexCoordinates.of("*")).delete();
}
@Test
@ -116,12 +123,7 @@ public class DoubleIDRepositoryTests {
assertThat(entityFromElasticSearch).isPresent();
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Document(indexName = "test-index-double-keyed-entity")
@Document(indexName = "#{@indexNameProvider.indexName()}")
static class DoubleIDEntity {
@Id private Double id;
@ -162,9 +164,5 @@ public class DoubleIDRepositoryTests {
}
}
/**
* @author Ryan Henszey
* @author Mohsin Husen
*/
interface DoubleIDRepository extends ElasticsearchRepository<DoubleIDEntity, Double> {}
}

View File

@ -22,10 +22,11 @@ import static org.springframework.data.elasticsearch.utils.IdGenerator.*;
import java.util.Map;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id;
@ -42,7 +43,7 @@ import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTem
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.data.elasticsearch.utils.IndexNameProvider;
import org.springframework.test.context.ContextConfiguration;
/**
@ -59,31 +60,34 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
@Configuration
@Import({ ElasticsearchRestTemplateConfiguration.class })
@EnableElasticsearchRepositories(considerNestedRepositories = true)
static class Config {}
static class Config {
@Bean
IndexNameProvider indexNameProvider() {
return new IndexNameProvider();
}
}
@Autowired private ElasticsearchOperations operations;
private IndexOperations indexOperations;
@Autowired IndexNameProvider indexNameProvider;
@Autowired private DynamicSettingAndMappingEntityRepository repository;
@BeforeEach
public void before() {
indexNameProvider.increment();
indexOperations = operations.indexOps(DynamicSettingAndMappingEntity.class);
IndexInitializer.init(indexOperations);
indexOperations.createWithMapping();
}
@AfterEach
void after() {
indexOperations.delete();
@Test
@Order(Integer.MAX_VALUE)
void cleanup() {
operations.indexOps(IndexCoordinates.of("*")).delete();
}
@Test // DATAES-64
public void shouldCreateGivenDynamicSettingsForGivenIndex() {
// given
// delete , create and apply mapping in before method
// then
assertThat(indexOperations.exists()).isTrue();
Map<String, Object> map = indexOperations.getSettings();
assertThat(map.containsKey("index.number_of_replicas")).isTrue();
@ -97,7 +101,6 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
@Test // DATAES-64
public void shouldSearchOnGivenTokenizerUsingGivenDynamicSettingsForGivenIndex() {
// given
DynamicSettingAndMappingEntity dynamicSettingAndMappingEntity1 = new DynamicSettingAndMappingEntity();
dynamicSettingAndMappingEntity1.setId(nextIdAsString());
dynamicSettingAndMappingEntity1.setName("test-setting1");
@ -112,16 +115,14 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
repository.save(dynamicSettingAndMappingEntity2);
// when
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.termQuery("email", dynamicSettingAndMappingEntity1.getEmail())).build();
IndexCoordinates index = IndexCoordinates.of("test-index-dynamic-setting-and-mapping");
IndexCoordinates index = IndexCoordinates.of(indexNameProvider.indexName());
long count = operations.count(searchQuery, DynamicSettingAndMappingEntity.class, index);
SearchHits<DynamicSettingAndMappingEntity> entityList = operations.search(searchQuery,
DynamicSettingAndMappingEntity.class, index);
// then
assertThat(count).isEqualTo(1L);
assertThat(entityList).isNotNull().hasSize(1);
assertThat(entityList.getSearchHit(0).getContent().getEmail())
@ -131,13 +132,8 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
@Test
public void shouldGetMappingForGivenIndexAndType() {
// given
// delete , create and apply mapping in before method
// when
Map<String, Object> mapping = indexOperations.getMapping();
// then
Map<String, Object> properties = (Map<String, Object>) mapping.get("properties");
assertThat(mapping).isNotNull();
assertThat(properties).isNotNull();
@ -176,9 +172,6 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
@Test // DATAES-86
public void shouldCreateMappingWithUsingMappingAnnotation() {
// given
// then
Map<String, Object> mapping = indexOperations.getMapping();
Map<String, Object> properties = (Map<String, Object>) mapping.get("properties");
assertThat(mapping).isNotNull();
@ -188,10 +181,7 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
assertThat(emailProperties.get("analyzer")).isEqualTo("emailAnalyzer");
}
/**
* @author Mohsin Husen
*/
@Document(indexName = "test-index-dynamic-setting-and-mapping")
@Document(indexName = "#{@indexNameProvider.indexName()}")
@Setting(settingPath = "/settings/test-settings.json")
@Mapping(mappingPath = "/mappings/test-mappings.json")
static class DynamicSettingAndMappingEntity {
@ -225,9 +215,6 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
}
}
/**
* @author Mohsin Husen
*/
public interface DynamicSettingAndMappingEntityRepository
extends ElasticsearchRepository<DynamicSettingAndMappingEntity, String> {}

View File

@ -0,0 +1,44 @@
/*
* Copyright 2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.utils;
/**
* Class providing an index name with a prefix and a index number
*
* @author Peter-Josef Meisch
*/
public class IndexNameProvider {
private final String prefix;
private int idx = -1;
private String indexName;
public IndexNameProvider() {
this("index-default");
}
public IndexNameProvider(String prefix) {
this.prefix = prefix;
increment();
}
public void increment() {
indexName = prefix + "-" + ++idx;
}
public String indexName() {
return indexName;
}
}