From 96ebc72dd1d1b8a03217e1af320de5823256ac8d Mon Sep 17 00:00:00 2001 From: Peter-Josef Meisch Date: Tue, 25 Feb 2020 22:01:40 +0100 Subject: [PATCH] Dataes 745 consolidate operations api Original PR: #396 --- .../AbstractElasticsearchConfiguration.java | 6 - .../core/AbstractDefaultIndexOperations.java | 195 ++++-- .../core/AbstractElasticsearchTemplate.java | 106 ++- .../core/DefaultIndexOperations.java | 43 +- .../core/DefaultTransportIndexOperations.java | 40 +- .../core/DocumentOperations.java | 110 +++- .../core/ElasticsearchOperations.java | 166 +++-- .../core/ElasticsearchRestTemplate.java | 59 +- .../core/ElasticsearchTemplate.java | 55 +- .../elasticsearch/core/IndexOperations.java | 192 ++---- .../core/ReactiveDocumentOperations.java | 96 ++- .../core/ReactiveElasticsearchTemplate.java | 125 ++-- .../elasticsearch/core/RequestFactory.java | 198 +++--- .../elasticsearch/core/SearchOperations.java | 140 ++-- .../elasticsearch/core/document/Document.java | 2 +- .../core/document/MapDocument.java | 2 +- .../core/query/AbstractQuery.java | 13 + .../core/query/CriteriaQuery.java | 20 +- .../elasticsearch/core/query/DeleteQuery.java | 2 + .../elasticsearch/core/query/GetQuery.java | 2 + .../elasticsearch/core/query/IndexQuery.java | 5 + .../core/query/NativeSearchQuery.java | 2 + .../data/elasticsearch/core/query/Query.java | 28 +- .../elasticsearch/core/query/UpdateQuery.java | 155 ++++- .../core/query/UpdateQueryBuilder.java | 67 -- .../core/query/UpdateResponse.java | 45 ++ ...tReactiveElasticsearchRepositoryQuery.java | 2 +- .../query/ElasticsearchPartQuery.java | 2 +- .../AbstractElasticsearchRepository.java | 61 +- .../SimpleElasticsearchRepository.java | 4 - ...SimpleReactiveElasticsearchRepository.java | 8 +- .../data/elasticsearch/NestedObjectTests.java | 25 +- .../EnableElasticsearchRepositoriesTests.java | 9 +- .../core/ElasticsearchRestTemplateTests.java | 12 +- .../core/ElasticsearchTemplateTests.java | 622 ++++++++++-------- .../ElasticsearchTransportTemplateTests.java | 12 +- .../elasticsearch/core/LogEntityTests.java | 9 +- .../ReactiveElasticsearchTemplateTests.java | 94 +-- ...eactiveElasticsearchTemplateUnitTests.java | 12 +- ...ElasticsearchTemplateAggregationTests.java | 9 +- .../ElasticsearchTemplateCompletionTests.java | 16 +- ...chTemplateCompletionWithContextsTests.java | 11 +- .../geo/ElasticsearchTemplateGeoTests.java | 14 +- .../core/index/MappingBuilderTests.java | 74 ++- .../core/query/CriteriaQueryTests.java | 53 +- ...ImmutableElasticsearchRepositoryTests.java | 9 +- .../ElasticsearchTemplateConfiguration.java | 7 - .../ComplexCustomMethodRepositoryTests.java | 10 +- ...stomMethodRepositoryManualWiringTests.java | 9 +- .../CustomMethodRepositoryBaseTests.java | 9 +- .../doubleid/DoubleIDRepositoryTests.java | 9 +- .../dynamicindex/DynamicIndexEntityTests.java | 14 +- .../geo/SpringDataGeoRepositoryTests.java | 9 +- .../integer/IntegerIDRepositoryTests.java | 10 +- .../nestedobject/InnerObjectTests.java | 10 +- ...ettingAndMappingEntityRepositoryTests.java | 28 +- ...ldDynamicMappingEntityRepositoryTests.java | 7 +- .../repositories/spel/SpELEntityTests.java | 7 +- .../synonym/SynonymRepositoryTests.java | 7 +- .../UUIDElasticsearchRepositoryTests.java | 9 +- .../query/keywords/QueryKeywordsTests.java | 9 +- .../SimpleElasticsearchRepositoryTests.java | 7 +- .../elasticsearch/utils/IndexInitializer.java | 21 +- 63 files changed, 1813 insertions(+), 1301 deletions(-) delete mode 100644 src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQueryBuilder.java create mode 100644 src/main/java/org/springframework/data/elasticsearch/core/query/UpdateResponse.java diff --git a/src/main/java/org/springframework/data/elasticsearch/config/AbstractElasticsearchConfiguration.java b/src/main/java/org/springframework/data/elasticsearch/config/AbstractElasticsearchConfiguration.java index c81ade77c..97e680d90 100644 --- a/src/main/java/org/springframework/data/elasticsearch/config/AbstractElasticsearchConfiguration.java +++ b/src/main/java/org/springframework/data/elasticsearch/config/AbstractElasticsearchConfiguration.java @@ -19,7 +19,6 @@ import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; -import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; /** @@ -48,9 +47,4 @@ public abstract class AbstractElasticsearchConfiguration extends ElasticsearchCo public ElasticsearchOperations elasticsearchOperations(ElasticsearchConverter elasticsearchConverter) { return new ElasticsearchRestTemplate(elasticsearchClient(), elasticsearchConverter); } - - @Bean - public IndexOperations indexOperations(ElasticsearchOperations elasticsearchOperations) { - return elasticsearchOperations.getIndexOperations(); - } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/AbstractDefaultIndexOperations.java b/src/main/java/org/springframework/data/elasticsearch/core/AbstractDefaultIndexOperations.java index 2032624c8..f6100e8ab 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/AbstractDefaultIndexOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/AbstractDefaultIndexOperations.java @@ -18,20 +18,26 @@ package org.springframework.data.elasticsearch.core; import static org.springframework.util.StringUtils.*; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse; +import org.elasticsearch.cluster.metadata.AliasMetaData; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.settings.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.annotations.Mapping; import org.springframework.data.elasticsearch.annotations.Setting; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; +import org.springframework.data.elasticsearch.core.document.Document; import org.springframework.data.elasticsearch.core.index.MappingBuilder; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; +import org.springframework.data.elasticsearch.core.query.AliasQuery; +import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; /** @@ -48,88 +54,145 @@ abstract class AbstractDefaultIndexOperations implements IndexOperations { protected final ElasticsearchConverter elasticsearchConverter; protected final RequestFactory requestFactory; - public AbstractDefaultIndexOperations(ElasticsearchConverter elasticsearchConverter) { + @Nullable protected final Class boundClass; + protected final IndexCoordinates boundIndex; + + public AbstractDefaultIndexOperations(ElasticsearchConverter elasticsearchConverter, Class boundClass) { this.elasticsearchConverter = elasticsearchConverter; requestFactory = new RequestFactory(elasticsearchConverter); + + this.boundClass = boundClass; + this.boundIndex = getIndexCoordinatesFor(boundClass); + } + + public AbstractDefaultIndexOperations(ElasticsearchConverter elasticsearchConverter, IndexCoordinates boundIndex) { + this.elasticsearchConverter = elasticsearchConverter; + requestFactory = new RequestFactory(elasticsearchConverter); + + this.boundClass = null; + this.boundIndex = boundIndex; + } + + protected Class checkForBoundClass() { + if (boundClass == null) { + throw new InvalidDataAccessApiUsageException("IndexOperations are not bound"); + } + return boundClass; } // region IndexOperations - @Override - public boolean createIndex(String indexName) { - return createIndex(indexName, null); - } @Override - public boolean createIndex(Class clazz) { + public boolean create() { - String indexName = getRequiredPersistentEntity(clazz).getIndexCoordinates().getIndexName(); - if (clazz.isAnnotationPresent(Setting.class)) { - String settingPath = clazz.getAnnotation(Setting.class).settingPath(); + if (boundClass != null) { + Class clazz = boundClass; + String indexName = boundIndex.getIndexName(); - if (hasText(settingPath)) { - String settings = ResourceUtil.readFileFromClasspath(settingPath); + if (clazz.isAnnotationPresent(Setting.class)) { + String settingPath = clazz.getAnnotation(Setting.class).settingPath(); - if (hasText(settings)) { - return createIndex(indexName, settings); + if (hasText(settingPath)) { + String settings = ResourceUtil.readFileFromClasspath(settingPath); + + if (hasText(settings)) { + return doCreate(indexName, Document.parse(settings)); + } + } else { + LOGGER.info("settingPath in @Setting has to be defined. Using default instead."); } - } else { - LOGGER.info("settingPath in @Setting has to be defined. Using default instead."); } + return doCreate(indexName, getDefaultSettings(getRequiredPersistentEntity(clazz))); } - return createIndex(indexName, getDefaultSettings(getRequiredPersistentEntity(clazz))); + return doCreate(boundIndex.getIndexName(), null); } @Override - public boolean createIndex(Class clazz, Object settings) { - return createIndex(getRequiredPersistentEntity(clazz).getIndexCoordinates().getIndexName(), settings); + public boolean create(Document settings) { + return doCreate(boundIndex.getIndexName(), settings); + } + + protected abstract boolean doCreate(String indexName, @Nullable Document settings); + + @Override + public boolean delete() { + return doDelete(boundIndex.getIndexName()); + } + + protected abstract boolean doDelete(String indexName); + + @Override + public boolean exists() { + return doExists(boundIndex.getIndexName()); + } + + protected abstract boolean doExists(String indexName); + + @Override + public boolean putMapping(Document mapping) { + return doPutMapping(boundIndex, mapping); + } + + protected abstract boolean doPutMapping(IndexCoordinates index, Document mapping); + + @Override + public Map getMapping() { + return doGetMapping(boundIndex); + } + + abstract protected Map doGetMapping(IndexCoordinates index); + + @Override + public Map getSettings() { + return getSettings(false); } @Override - public boolean deleteIndex(Class clazz) { - return deleteIndex(getRequiredPersistentEntity(clazz).getIndexCoordinates().getIndexName()); + public Map getSettings(boolean includeDefaults) { + return doGetSettings(boundIndex.getIndexName(), includeDefaults); + } + + protected abstract Map doGetSettings(String indexName, boolean includeDefaults); + + @Override + public void refresh() { + doRefresh(boundIndex); + } + + protected abstract void doRefresh(IndexCoordinates indexCoordinates); + + @Override + public boolean addAlias(AliasQuery query) { + return doAddAlias(query, boundIndex); + } + + protected abstract boolean doAddAlias(AliasQuery query, IndexCoordinates index); + + @Override + public List queryForAlias() { + return doQueryForAlias(boundIndex.getIndexName()); + } + + protected abstract List doQueryForAlias(String indexName); + + @Override + public boolean removeAlias(AliasQuery query) { + return doRemoveAlias(query, boundIndex); + } + + protected abstract boolean doRemoveAlias(AliasQuery query, IndexCoordinates index); + + @Override + public Document createMapping() { + return createMapping(checkForBoundClass()); } @Override - public boolean indexExists(Class clazz) { - return indexExists(getIndexCoordinatesFor(clazz).getIndexName()); + public Document createMapping(Class clazz) { + return buildMapping(clazz); } - @Override - public Map getMapping(Class clazz) { - return getMapping(getIndexCoordinatesFor(clazz)); - } - - @Override - public boolean putMapping(Class clazz) { - return putMapping(clazz, buildMapping(clazz)); - } - - @Override - public boolean putMapping(Class clazz, Object mapping) { - return putMapping(getIndexCoordinatesFor(clazz), mapping); - } - - @Override - public boolean putMapping(IndexCoordinates index, Class clazz) { - return putMapping(index, buildMapping(clazz)); - } - - @Override - public Map getSettings(Class clazz) { - return getSettings(clazz, false); - } - - @Override - public Map getSettings(Class clazz, boolean includeDefaults) { - return getSettings(getRequiredPersistentEntity(clazz).getIndexCoordinates().getIndexName(), includeDefaults); - } - - @Override - public void refresh(Class clazz) { - refresh(getIndexCoordinatesFor(clazz)); - } - - protected String buildMapping(Class clazz) { + protected Document buildMapping(Class clazz) { // load mapping specified in Mapping annotation if present if (clazz.isAnnotationPresent(Mapping.class)) { @@ -139,7 +202,7 @@ abstract class AbstractDefaultIndexOperations implements IndexOperations { String mappings = ResourceUtil.readFileFromClasspath(mappingPath); if (!StringUtils.isEmpty(mappings)) { - return mappings; + return Document.parse(mappings); } } else { LOGGER.info("mappingPath in @Mapping has to be defined. Building mappings using @Field"); @@ -148,7 +211,8 @@ abstract class AbstractDefaultIndexOperations implements IndexOperations { // build mapping from field annotations try { - return new MappingBuilder(elasticsearchConverter).buildPropertyMapping(clazz); + String mapping = new MappingBuilder(elasticsearchConverter).buildPropertyMapping(clazz); + return Document.parse(mapping); } catch (Exception e) { throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e); } @@ -156,15 +220,18 @@ abstract class AbstractDefaultIndexOperations implements IndexOperations { // endregion // region Helper functions - private Map getDefaultSettings(ElasticsearchPersistentEntity persistentEntity) { + private Document getDefaultSettings(ElasticsearchPersistentEntity persistentEntity) { - if (persistentEntity.isUseServerConfiguration()) - return new HashMap(); + if (persistentEntity.isUseServerConfiguration()) { + return Document.create(); + } - return new MapBuilder().put("index.number_of_shards", String.valueOf(persistentEntity.getShards())) + Map map = new MapBuilder() + .put("index.number_of_shards", String.valueOf(persistentEntity.getShards())) .put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas())) .put("index.refresh_interval", persistentEntity.getRefreshInterval()) .put("index.store.type", persistentEntity.getIndexStoreType()).map(); + return Document.from(map); } ElasticsearchPersistentEntity getRequiredPersistentEntity(Class clazz) { diff --git a/src/main/java/org/springframework/data/elasticsearch/core/AbstractElasticsearchTemplate.java b/src/main/java/org/springframework/data/elasticsearch/core/AbstractElasticsearchTemplate.java index 7f2b935e0..c2bbb4173 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/AbstractElasticsearchTemplate.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/AbstractElasticsearchTemplate.java @@ -6,6 +6,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -13,11 +14,8 @@ import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.search.MultiSearchRequest; import org.elasticsearch.action.search.MultiSearchResponse; -import org.elasticsearch.action.search.SearchRequest; -import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.MoreLikeThisQueryBuilder; -import org.elasticsearch.search.suggest.SuggestBuilder; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -29,7 +27,7 @@ import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersiste import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; -import org.springframework.data.elasticsearch.core.query.DeleteQuery; +import org.springframework.data.elasticsearch.core.query.GetQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder; import org.springframework.data.elasticsearch.core.query.MoreLikeThisQuery; @@ -50,16 +48,14 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper protected @Nullable ElasticsearchConverter elasticsearchConverter; protected @Nullable RequestFactory requestFactory; - protected @Nullable IndexOperations indexOperations; // region Initialization - protected void initialize(ElasticsearchConverter elasticsearchConverter, IndexOperations indexOperations) { + protected void initialize(ElasticsearchConverter elasticsearchConverter) { Assert.notNull(elasticsearchConverter, "elasticsearchConverter must not be null."); this.elasticsearchConverter = elasticsearchConverter; requestFactory = new RequestFactory(elasticsearchConverter); - this.indexOperations = indexOperations; } protected ElasticsearchConverter createElasticsearchConverter() { @@ -78,16 +74,6 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper } // endregion - // region getter/setter - @Override - public IndexOperations getIndexOperations() { - - Assert.notNull("indexOperations are not initialized"); - - return indexOperations; - } - // endregion - // region DocumentOperations @Override @@ -147,24 +133,64 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper } @Override - public void delete(Query query, Class clazz, IndexCoordinates index) { + @Nullable + public T get(String id, Class clazz) { + return get(id, clazz, getIndexCoordinatesFor(clazz)); + } - Assert.notNull(query, "Query must not be null."); + @Override + @Nullable + public T get(GetQuery query, Class clazz, IndexCoordinates index) { + return get(query.getId(), clazz, index); + } - SearchRequest searchRequest = requestFactory.searchRequest(query, clazz, index); - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(searchRequest.source().query()); + @Override + public boolean exists(String id, Class clazz) { + return exists(id, getIndexCoordinatesFor(clazz)); + } - delete(deleteQuery, index); + @Override + public boolean exists(String id, IndexCoordinates index) { + return doExists(id, index); + } + + abstract protected boolean doExists(String id, IndexCoordinates index); + + @Override + public String delete(String id, Class entityType) { + + Assert.notNull(id, "id must not be null"); + Assert.notNull(entityType, "entityType must not be null"); + + return this.delete(id, getIndexCoordinatesFor(entityType)); + } + + @Override + public String delete(Object entity) { + return delete(entity, getIndexCoordinatesFor(entity.getClass())); + } + + @Override + public String delete(Object entity, IndexCoordinates index) { + return this.delete(getEntityId(entity), index); } // endregion // region SearchOperations + @Override + public long count(Query query, Class clazz) { + return count(query, clazz, getIndexCoordinatesFor(clazz)); + } + @Override public CloseableIterator stream(Query query, Class clazz, IndexCoordinates index) { long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis(); - return StreamQueries.streamResults(startScroll(scrollTimeInMillis, query, clazz, index), - scrollId -> continueScroll(scrollId, scrollTimeInMillis, clazz), this::searchScrollClear); + return (CloseableIterator) SearchHitSupport.unwrapSearchHits(searchForStream(query, clazz, index)); + } + + @Override + public CloseableIterator> searchForStream(Query query, Class clazz) { + return searchForStream(query, clazz, getIndexCoordinatesFor(clazz)); } @Override @@ -174,6 +200,11 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper scrollId -> searchScrollContinue(scrollId, scrollTimeInMillis, clazz), this::searchScrollClear); } + @Override + public SearchHits search(MoreLikeThisQuery query, Class clazz) { + return search(query, clazz, getIndexCoordinatesFor(clazz)); + } + @Override public SearchHits search(MoreLikeThisQuery query, Class clazz, IndexCoordinates index) { @@ -220,6 +251,28 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper return res; } + @Override + public SearchHits search(Query query, Class clazz) { + return search(query, clazz, getIndexCoordinatesFor(clazz)); + } + + /* + * internal use only, not for public API + */ + abstract protected ScrolledPage> searchScrollStart(long scrollTimeInMillis, Query query, + Class clazz, IndexCoordinates index); + + /* + * internal use only, not for public API + */ + abstract protected ScrolledPage> searchScrollContinue(@Nullable String scrollId, + long scrollTimeInMillis, Class clazz); + + /* + * internal use only, not for public API + */ + abstract protected void searchScrollClear(String scrollId); + abstract protected MultiSearchResponse.Item[] getMultiSearchResult(MultiSearchRequest request); // endregion @@ -247,9 +300,6 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper return values.toArray(valuesAsArray); } - @Override - public abstract SearchResponse suggest(SuggestBuilder suggestion, IndexCoordinates index); - /** * @param clazz the entity class * @return the IndexCoordinates defined on the entity. diff --git a/src/main/java/org/springframework/data/elasticsearch/core/DefaultIndexOperations.java b/src/main/java/org/springframework/data/elasticsearch/core/DefaultIndexOperations.java index 87aab6cd5..9a7225195 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/DefaultIndexOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/DefaultIndexOperations.java @@ -41,8 +41,10 @@ import org.elasticsearch.cluster.metadata.AliasMetaData; import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.core.client.support.AliasData; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; +import org.springframework.data.elasticsearch.core.document.Document; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.AliasQuery; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import com.fasterxml.jackson.core.type.TypeReference; @@ -60,27 +62,35 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I private RestHighLevelClient client; - public DefaultIndexOperations(RestHighLevelClient client, ElasticsearchConverter elasticsearchConverter) { - super(elasticsearchConverter); + public DefaultIndexOperations(RestHighLevelClient client, ElasticsearchConverter elasticsearchConverter, + Class boundClass) { + super(elasticsearchConverter, boundClass); + this.client = client; + } + + public DefaultIndexOperations(RestHighLevelClient client, ElasticsearchConverter elasticsearchConverter, + IndexCoordinates boundIndex) { + super(elasticsearchConverter, boundIndex); this.client = client; } @Override - public boolean createIndex(String indexName, Object settings) { + protected boolean doCreate(String indexName, @Nullable Document settings) { CreateIndexRequest request = requestFactory.createIndexRequest(indexName, settings); try { return client.indices().create(request, RequestOptions.DEFAULT).isAcknowledged(); } catch (IOException e) { - throw new ElasticsearchException("Error for creating index: " + request.toString(), e); + throw new ElasticsearchException( + "Error for creating index: " + indexName + ", client: " + client.getLowLevelClient().getNodes(), e); } } @Override - public boolean deleteIndex(String indexName) { + protected boolean doDelete(String indexName) { Assert.notNull(indexName, "No index defined for delete operation"); - if (indexExists(indexName)) { + if (doExists(indexName)) { DeleteIndexRequest request = new DeleteIndexRequest(indexName); try { return client.indices().delete(request, RequestOptions.DEFAULT).isAcknowledged(); @@ -92,7 +102,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I } @Override - public boolean indexExists(String indexName) { + protected boolean doExists(String indexName) { GetIndexRequest request = new GetIndexRequest(indexName); try { return client.indices().exists(request, RequestOptions.DEFAULT); @@ -102,7 +112,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I } @Override - public boolean putMapping(IndexCoordinates index, Object mapping) { + protected boolean doPutMapping(IndexCoordinates index, Document mapping) { Assert.notNull(index, "No index defined for putMapping()"); @@ -115,7 +125,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I } @Override - public Map getMapping(IndexCoordinates index) { + protected Map doGetMapping(IndexCoordinates index) { Assert.notNull(index, "No index defined for getMapping()"); @@ -130,7 +140,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I } @Override - public boolean addAlias(AliasQuery query, IndexCoordinates index) { + protected boolean doAddAlias(AliasQuery query, IndexCoordinates index) { IndicesAliasesRequest request = requestFactory.indicesAddAliasesRequest(query, index); try { return client.indices().updateAliases(request, RequestOptions.DEFAULT).isAcknowledged(); @@ -140,7 +150,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I } @Override - public boolean removeAlias(AliasQuery query, IndexCoordinates index) { + protected boolean doRemoveAlias(AliasQuery query, IndexCoordinates index) { Assert.notNull(index, "No index defined for Alias"); Assert.notNull(query.getAliasName(), "No alias defined"); @@ -155,7 +165,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I } @Override - public List queryForAlias(String indexName) { + protected List doQueryForAlias(String indexName) { List aliases = null; RestClient restClient = client.getLowLevelClient(); Response response; @@ -172,12 +182,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I } @Override - public Map getSettings(String indexName) { - return getSettings(indexName, false); - } - - @Override - public Map getSettings(String indexName, boolean includeDefaults) { + protected Map doGetSettings(String indexName, boolean includeDefaults) { Assert.notNull(indexName, "No index defined for getSettings"); @@ -196,7 +201,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I } @Override - public void refresh(IndexCoordinates index) { + protected void doRefresh(IndexCoordinates index) { Assert.notNull(index, "No index defined for refresh()"); diff --git a/src/main/java/org/springframework/data/elasticsearch/core/DefaultTransportIndexOperations.java b/src/main/java/org/springframework/data/elasticsearch/core/DefaultTransportIndexOperations.java index cbc485c48..c185d06ae 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/DefaultTransportIndexOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/DefaultTransportIndexOperations.java @@ -32,8 +32,10 @@ import org.elasticsearch.client.Client; import org.elasticsearch.cluster.metadata.AliasMetaData; import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; +import org.springframework.data.elasticsearch.core.document.Document; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.AliasQuery; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -47,36 +49,43 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp private final Client client; - public DefaultTransportIndexOperations(Client client, ElasticsearchConverter elasticsearchConverter) { - super(elasticsearchConverter); + public DefaultTransportIndexOperations(Client client, ElasticsearchConverter elasticsearchConverter, + Class boundClass) { + super(elasticsearchConverter, boundClass); + this.client = client; + } + + public DefaultTransportIndexOperations(Client client, ElasticsearchConverter elasticsearchConverter, + IndexCoordinates boundIndex) { + super(elasticsearchConverter, boundIndex); this.client = client; } @Override - public boolean createIndex(String indexName, Object settings) { + protected boolean doCreate(String indexName, @Nullable Document settings) { CreateIndexRequestBuilder createIndexRequestBuilder = requestFactory.createIndexRequestBuilder(client, indexName, settings); return createIndexRequestBuilder.execute().actionGet().isAcknowledged(); } @Override - public boolean deleteIndex(String indexName) { + protected boolean doDelete(String indexName) { Assert.notNull(indexName, "No index defined for delete operation"); - if (indexExists(indexName)) { + if (doExists(indexName)) { return client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet().isAcknowledged(); } return false; } @Override - public boolean indexExists(String indexName) { + protected boolean doExists(String indexName) { return client.admin().indices().exists(indicesExistsRequest(indexName)).actionGet().isExists(); } @Override - public boolean putMapping(IndexCoordinates index, Object mapping) { + protected boolean doPutMapping(IndexCoordinates index, Document mapping) { Assert.notNull(index, "No index defined for putMapping()"); @@ -85,7 +94,7 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp } @Override - public Map getMapping(IndexCoordinates index) { + protected Map doGetMapping(IndexCoordinates index) { Assert.notNull(index, "No index defined for getMapping()"); @@ -100,13 +109,13 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp } @Override - public boolean addAlias(AliasQuery query, IndexCoordinates index) { + protected boolean doAddAlias(AliasQuery query, IndexCoordinates index) { IndicesAliasesRequest.AliasActions aliasAction = requestFactory.aliasAction(query, index); return client.admin().indices().prepareAliases().addAliasAction(aliasAction).execute().actionGet().isAcknowledged(); } @Override - public boolean removeAlias(AliasQuery query, IndexCoordinates index) { + protected boolean doRemoveAlias(AliasQuery query, IndexCoordinates index) { Assert.notNull(index, "No index defined for Alias"); Assert.notNull(query.getAliasName(), "No alias defined"); @@ -116,18 +125,13 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp } @Override - public List queryForAlias(String indexName) { + protected List doQueryForAlias(String indexName) { return client.admin().indices().getAliases(new GetAliasesRequest().indices(indexName)).actionGet().getAliases() .get(indexName); } @Override - public Map getSettings(String indexName) { - return getSettings(indexName, false); - } - - @Override - public Map getSettings(String indexName, boolean includeDefaults) { + protected Map doGetSettings(String indexName, boolean includeDefaults) { Assert.notNull(indexName, "No index defined for getSettings"); @@ -144,7 +148,7 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp } @Override - public void refresh(IndexCoordinates index) { + protected void doRefresh(IndexCoordinates index) { Assert.notNull(index, "No index defined for refresh()"); diff --git a/src/main/java/org/springframework/data/elasticsearch/core/DocumentOperations.java b/src/main/java/org/springframework/data/elasticsearch/core/DocumentOperations.java index 9442236dc..f664f38c9 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/DocumentOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/DocumentOperations.java @@ -16,8 +16,8 @@ package org.springframework.data.elasticsearch.core; import java.util.List; +import java.util.Optional; -import org.elasticsearch.action.update.UpdateResponse; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.BulkOptions; import org.springframework.data.elasticsearch.core.query.DeleteQuery; @@ -25,6 +25,7 @@ import org.springframework.data.elasticsearch.core.query.GetQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.data.elasticsearch.core.query.UpdateQuery; +import org.springframework.data.elasticsearch.core.query.UpdateResponse; import org.springframework.lang.Nullable; /** @@ -68,9 +69,9 @@ public interface DocumentOperations { * saves the given entities to the given index * * @param entities must not be {@literal null} - * @param index the idnex to save the entities in, must not be {@literal null} + * @param index the index to save the entities in, must not be {@literal null} * @param the entity type - * @return the saved entites + * @return the saved entities */ Iterable save(Iterable entities, IndexCoordinates index); @@ -87,21 +88,32 @@ public interface DocumentOperations { * Index an object. Will do save or update. * * @param query the query defining the object - * @param index the index from which the object is read. + * @param index the index where the object is stored. * @return returns the document id */ String index(IndexQuery query, IndexCoordinates index); /** - * Retrieves an object from an index. + * Retrieves an object from the index specified in the entity's Document annotation. * - * @param query the query defining the id of the object to get - * @param clazz the type of the object to be returned - * @param index the index from which the object is read. - * @return the found object + * @param id the id of the object + * @param clazz the entity class, + * @param the entity type + * @return the entity */ @Nullable - T get(GetQuery query, Class clazz, IndexCoordinates index); + T get(String id, Class clazz); + + /** + * Retrieves an object from the index specified in the entity's Document annotation. + * + * @param id the id of the object + * @param clazz the entity class, + * @param index the index from which the object is read. + * @return the entity + */ + @Nullable + T get(String id, Class clazz, IndexCoordinates index); /** * Execute a multiGet against elasticsearch for the given ids. @@ -113,6 +125,24 @@ public interface DocumentOperations { */ List multiGet(Query query, Class clazz, IndexCoordinates index); + /** + * Check if an entity with given {@literal id} exists. + * + * @param id the {@literal _id} of the document to look for. + * @param clazz the domain type used. + * @return {@literal true} if a matching document exists, {@literal false} otherwise. + */ + boolean exists(String id, Class clazz); + + /** + * Check if an entity with given {@literal id} exists. + * + * @param id the {@literal _id} of the document to look for. + * @param index the target index, must not be {@literal null} + * @return {@literal true} if a matching document exists, {@literal false} otherwise. + */ + boolean exists(String id, IndexCoordinates index); + /** * Bulk index all objects. Will do save or update. * @@ -158,6 +188,32 @@ public interface DocumentOperations { */ String delete(String id, IndexCoordinates index); + /** + * Delete the one object with provided id. + * + * @param id the document ot delete + * @param entityType must not be {@literal null}. + * @return documentId of the document deleted + */ + String delete(String id, Class entityType); + + /** + * Deletes the given entity + * + * @param entity the entity to delete + * @return documentId of the document deleted + */ + String delete(Object entity); + + /** + * Deletes the given entity + * + * @param entity the entity to delete + * @param index the index from which to delete + * @return documentId of the document deleted + */ + String delete(Object entity, IndexCoordinates index); + /** * Delete all records matching the query. * @@ -168,14 +224,6 @@ public interface DocumentOperations { */ void delete(Query query, Class clazz, IndexCoordinates index); - /** - * Delete all records matching the query. - * - * @param query query defining the objects - * @param index the index where to delete the records - */ - void delete(DeleteQuery query, IndexCoordinates index); - /** * Partial update of the document. * @@ -184,4 +232,30 @@ public interface DocumentOperations { * @return the update response */ UpdateResponse update(UpdateQuery updateQuery, IndexCoordinates index); + + // region deprecated + /** + * Delete all records matching the query. + * + * @param query query defining the objects + * @param index the index where to delete the records + * @deprecated since 4.0, use {@link #delete(Query, Class, IndexCoordinates)} + */ + @Deprecated + void delete(DeleteQuery query, IndexCoordinates index); + + /** + * Retrieves an object from an index. + * + * @param query the query defining the id of the object to get + * @param clazz the type of the object to be returned + * @param index the index from which the object is read. + * @return the found object + * @deprecated since 4.0, use {@link #getById(String, Class, IndexCoordinates)} + */ + @Deprecated + @Nullable + T get(GetQuery query, Class clazz, IndexCoordinates index); + + // endregion } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java index f82529548..62c87e5ee 100755 --- a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java @@ -21,6 +21,7 @@ import java.util.Objects; import org.elasticsearch.cluster.metadata.AliasMetaData; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; +import org.springframework.data.elasticsearch.core.document.Document; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.AliasQuery; import org.springframework.lang.Nullable; @@ -40,7 +41,19 @@ import org.springframework.lang.Nullable; */ public interface ElasticsearchOperations extends DocumentOperations, SearchOperations { - IndexOperations getIndexOperations(); + /** + * get an {@link IndexOperations} that is bound to the given class + * + * @return IndexOperations + */ + IndexOperations indexOps(Class clazz); + + /** + * get an {@link IndexOperations} that is bound to the given class + * + * @return IndexOperations + */ + IndexOperations indexOps(IndexCoordinates index); ElasticsearchConverter getElasticsearchConverter(); @@ -52,11 +65,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * * @param indexName the name of the index * @return {@literal true} if the index was created - * @deprecated since 4.0, use {@link IndexOperations#createIndex(String) instead} + * @deprecated since 4.0, use {@link IndexOperations#create()} */ @Deprecated default boolean createIndex(String indexName) { - return getIndexOperations().createIndex(indexName); + return indexOps(IndexCoordinates.of(indexName)).create(); } /** @@ -65,11 +78,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param indexName the name of the index * @param settings the index settings * @return {@literal true} if the index was created - * @deprecated since 4.0, use {@link IndexOperations#createIndex(String, Object)} instead} + * @deprecated since 4.0, use {@link IndexOperations#create(Document)} */ @Deprecated default boolean createIndex(String indexName, Object settings) { - return getIndexOperations().createIndex(indexName, settings); + return indexOps(IndexCoordinates.of(indexName)).create(getDocument(settings)); } /** @@ -78,11 +91,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param clazz The entity class, must be annotated with * {@link org.springframework.data.elasticsearch.annotations.Document} * @return {@literal true} if the index was created - * @deprecated since 4.0, use {@link IndexOperations#createIndex(Class)} instead} + * @deprecated since 4.0, use {@link IndexOperations#create()} */ @Deprecated default boolean createIndex(Class clazz) { - return getIndexOperations().createIndex(clazz); + return indexOps(clazz).create(); } /** @@ -92,11 +105,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * {@link org.springframework.data.elasticsearch.annotations.Document} * @param settings the index settings * @return {@literal true} if the index was created - * @deprecated since 4.0, use {@link IndexOperations#createIndex(Class, Object)} instead} + * @deprecated since 4.0, use {@link IndexOperations#create(Document)} */ @Deprecated default boolean createIndex(Class clazz, Object settings) { - return getIndexOperations().createIndex(clazz, settings); + return indexOps(clazz).create(getDocument(settings)); } /** @@ -105,11 +118,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param clazz The entity class, must be annotated with * {@link org.springframework.data.elasticsearch.annotations.Document} * @return {@literal true} if the index was deleted - * @deprecated since 4.0, use {@link IndexOperations#deleteIndex(Class)} instead} + * @deprecated since 4.0, use {@link IndexOperations#delete()} */ @Deprecated default boolean deleteIndex(Class clazz) { - return getIndexOperations().deleteIndex(clazz); + return indexOps(clazz).delete(); } /** @@ -117,11 +130,23 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * * @param indexName the name of the index to delete * @return {@literal true} if the index was deleted - * @deprecated since 4.0, use {@link IndexOperations#deleteIndex(String)} instead} + * @deprecated since 4.0, use {@link IndexOperations#delete()} */ @Deprecated default boolean deleteIndex(String indexName) { - return getIndexOperations().deleteIndex(indexName); + return indexOps(IndexCoordinates.of(indexName)).delete(); + } + + /** + * Deletes an index for an IndexCoordinate + * + * @param index the index to delete + * @return {@literal true} if the index was deleted + * @deprecated since 4.0 use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#delete()} + */ + @Deprecated + default boolean deleteIndex(IndexCoordinates index) { + return indexOps(index).delete(); } /** @@ -129,11 +154,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * * @param indexName the name of the index * @return {@literal true} if the index exists - * @deprecated since 4.0, use {@link IndexOperations#indexExists(String)} instead} + * @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#exists()} */ @Deprecated default boolean indexExists(String indexName) { - return getIndexOperations().indexExists(indexName); + return indexOps(IndexCoordinates.of(indexName)).exists(); } /** @@ -142,11 +167,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param clazz The entity class, must be annotated with * {@link org.springframework.data.elasticsearch.annotations.Document} * @return {@literal true} if the index exists - * @deprecated since 4.0, use {@link IndexOperations#indexExists(Class)} instead} + * @deprecated since 4.0, use {@link #indexOps(Class)} and {@link IndexOperations#exists()} */ @Deprecated default boolean indexExists(Class clazz) { - return getIndexOperations().indexExists(clazz); + return indexOps(clazz).exists(); } /** @@ -155,11 +180,13 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param clazz The entity class, must be annotated with * {@link org.springframework.data.elasticsearch.annotations.Document} * @return {@literal true} if the mapping could be stored - * @deprecated since 4.0, use {@link IndexOperations#putMapping(Class)} instead} + * @deprecated since 4.0, use {@link #indexOps(Class)}, {@link IndexOperations#createMapping(Class)} and + * {@link IndexOperations#putMapping(Document)} */ @Deprecated default boolean putMapping(Class clazz) { - return getIndexOperations().putMapping(clazz); + IndexOperations indexOps = indexOps(clazz); + return indexOps.putMapping(indexOps.createMapping(clazz)); } /** @@ -169,11 +196,13 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param clazz The entity class, must be annotated with * {@link org.springframework.data.elasticsearch.annotations.Document} * @return {@literal true} if the mapping could be stored - * @deprecated since 4.0, use {@link IndexOperations#putMapping(IndexCoordinates, Class)} instead} + * @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)}, {@link IndexOperations#createMapping(Class)} and + * {@link IndexOperations#putMapping(Document)} */ @Deprecated default boolean putMapping(IndexCoordinates index, Class clazz) { - return getIndexOperations().putMapping(index, clazz); + IndexOperations indexOps = indexOps(index); + return indexOps.putMapping(indexOps.createMapping(clazz)); } /** @@ -182,11 +211,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param index the index to store the mapping to * @param mappings can be a JSON String or a {@link Map} * @return {@literal true} if the mapping could be stored - * @deprecated since 4.0, use {@link IndexOperations#putMapping(IndexCoordinates, Object)} instead} + * @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#putMapping(Document)} */ @Deprecated default boolean putMapping(IndexCoordinates index, Object mappings) { - return getIndexOperations().putMapping(index, mappings); + return indexOps(index).putMapping(getDocument(mappings)); } /** @@ -196,11 +225,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * {@link org.springframework.data.elasticsearch.annotations.Document} * @param mappings can be a JSON String or a {@link Map} * @return {@literal true} if the mapping could be stored - * @deprecated since 4.0, use {@link IndexOperations#putMapping(Class, Object)} instead} + * @deprecated since 4.0, use {@link #indexOps(Class)} and {@link IndexOperations#putMapping(Document)} */ @Deprecated default boolean putMapping(Class clazz, Object mappings) { - return getIndexOperations().putMapping(clazz, mappings); + return indexOps(clazz).putMapping(getDocument(mappings)); } /** @@ -209,11 +238,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param clazz The entity class, must be annotated with * {@link org.springframework.data.elasticsearch.annotations.Document}. * @return the mapping - * @deprecated since 4.0, use {@link IndexOperations#getMapping(Class)} instead} + * @deprecated since 4.0, use {@link #indexOps(Class)} and {@link IndexOperations#getMapping()} */ @Deprecated default Map getMapping(Class clazz) { - return getIndexOperations().getMapping(clazz); + return indexOps(clazz).getMapping(); } /** @@ -221,11 +250,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * * @param index the index to read the mapping from * @return the mapping - * @deprecated since 4.0, use {@link IndexOperations#getMapping(IndexCoordinates)} instead} + * @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#getMapping()} */ @Deprecated default Map getMapping(IndexCoordinates index) { - return getIndexOperations().getMapping(index); + return indexOps(index).getMapping(); } /** @@ -234,11 +263,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param query query defining the alias * @param index the index for which to add an alias * @return true if the alias was created - * @deprecated since 4.0, use {@link IndexOperations#addAlias(AliasQuery, IndexCoordinates)} instead} + * @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#addAlias(AliasQuery)} */ @Deprecated default boolean addAlias(AliasQuery query, IndexCoordinates index) { - return getIndexOperations().addAlias(query, index); + return indexOps(index).addAlias(query); } /** @@ -247,11 +276,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param query query defining the alias * @param index the index for which to remove an alias * @return true if the alias was removed - * @deprecated since 4.0, use {@link IndexOperations#removeAlias(AliasQuery, IndexCoordinates)} instead} + * @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} {@link IndexOperations#removeAlias(AliasQuery)} */ @Deprecated default boolean removeAlias(AliasQuery query, IndexCoordinates index) { - return getIndexOperations().removeAlias(query, index); + return indexOps(index).removeAlias(query); } /** @@ -259,11 +288,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * * @param indexName the name of the index * @return alias information - * @deprecated since 4.0, use {@link IndexOperations#queryForAlias(String)} instead} + * @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#queryForAlias()} */ @Deprecated default List queryForAlias(String indexName) { - return getIndexOperations().queryForAlias(indexName); + return indexOps(IndexCoordinates.of(indexName)).queryForAlias(); } /** @@ -271,11 +300,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * * @param indexName the name of the index * @return the settings - * @deprecated since 4.0, use {@link IndexOperations#getSettings(String)} )} instead} + * @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#getSettings()} )} */ @Deprecated default Map getSetting(String indexName) { - return getIndexOperations().getSettings(indexName); + return indexOps(IndexCoordinates.of(indexName)).getSettings(); } /** @@ -284,22 +313,48 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * @param clazz The entity class, must be annotated with * {@link org.springframework.data.elasticsearch.annotations.Document} * @return the settings - * @deprecated since 4.0, use {@link IndexOperations#getSettings(Class)} instead} + * @deprecated since 4.0, use {@link #indexOps(Class)} and {@link IndexOperations#getSettings()} */ @Deprecated default Map getSetting(Class clazz) { - return getIndexOperations().getSettings(clazz); + return indexOps(clazz).getSettings(); + } + + /** + * Get settings for a given indexName. + * + * @param indexName the name of the index + * @param includeDefaults whether or not to include all the default settings + * @deprecated since 4.0 use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#getSettings(boolean)} ()} + * @return the settings + */ + @Deprecated + default Map getSettings(String indexName, boolean includeDefaults) { + return indexOps(IndexCoordinates.of(indexName)).getSettings(includeDefaults); + } + + /** + * Get settings for a given class. + * + * @param clazz The entity class, must be annotated with + * {@link org.springframework.data.elasticsearch.annotations.Document} + * @param includeDefaults whether or not to include all the default settings + * @return the settings + * @deprecated since 4.0 use {@link #indexOps(Class)} and {@link IndexOperations#getSettings(boolean)} ()} + */ + default Map getSettings(Class clazz, boolean includeDefaults) { + return indexOps(clazz).getSettings(includeDefaults); } /** * Refresh the index(es). * * @param index the index to refresh - * @deprecated since 4.0, use {@link IndexOperations#refresh(IndexCoordinates)} instead} + * @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#refresh()} instead} */ @Deprecated default void refresh(IndexCoordinates index) { - getIndexOperations().refresh(index); + indexOps(index).refresh(); } /** @@ -307,13 +362,36 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera * * @param clazz The entity class, must be annotated with * {@link org.springframework.data.elasticsearch.annotations.Document} - * @deprecated since 4.0, use {@link IndexOperations#refresh(Class)} instead} + * @deprecated since 4.0, use {@link #indexOps(Class)} and {@link IndexOperations#refresh()} instead} */ @Deprecated default void refresh(Class clazz) { - getIndexOperations().refresh(clazz); + indexOps(clazz).refresh(); } - // endregion + + /** + * converts an object to a Document + * + * @param object + * @return + * @deprecated since 4.0, helper method for deprecated functions + */ + @Deprecated + @Nullable + default Document getDocument(Object object) { + Document document = null; + + try { + if (object instanceof String) { + document = Document.parse((String) object); + } else if (object instanceof Map) { + document = Document.from((Map) object); + } + } catch (Exception e) { + throw new IllegalArgumentException("object cannot be converted to Document", e); + } + return document; + } // endregion // region helper /** diff --git a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplate.java b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplate.java index 1dc87c027..26e617a58 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplate.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplate.java @@ -17,6 +17,7 @@ package org.springframework.data.elasticsearch.core; import java.io.IOException; import java.util.List; +import java.util.Optional; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.delete.DeleteRequest; @@ -32,7 +33,6 @@ import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.action.update.UpdateRequest; -import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.unit.TimeValue; @@ -47,10 +47,10 @@ import org.springframework.data.elasticsearch.core.document.SearchDocumentRespon import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.BulkOptions; import org.springframework.data.elasticsearch.core.query.DeleteQuery; -import org.springframework.data.elasticsearch.core.query.GetQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.data.elasticsearch.core.query.UpdateQuery; +import org.springframework.data.elasticsearch.core.query.UpdateResponse; import org.springframework.data.elasticsearch.support.SearchHitsUtil; import org.springframework.lang.Nullable; import org.springframework.util.Assert; @@ -103,9 +103,29 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate { } private void initialize(RestHighLevelClient client, ElasticsearchConverter elasticsearchConverter) { + Assert.notNull(client, "Client must not be null!"); + this.client = client; - initialize(elasticsearchConverter, new DefaultIndexOperations(client, elasticsearchConverter)); + initialize(elasticsearchConverter); + } + // endregion + + // region IndexOperations + @Override + public IndexOperations indexOps(Class clazz) { + + Assert.notNull(clazz, "clazz must not be null"); + + return new DefaultIndexOperations(client, elasticsearchConverter, clazz); + } + + @Override + public IndexOperations indexOps(IndexCoordinates index) { + + Assert.notNull(index, "index must not be null"); + + return new DefaultIndexOperations(client, elasticsearchConverter, index); } // endregion @@ -128,8 +148,8 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate { @Override @Nullable - public T get(GetQuery query, Class clazz, IndexCoordinates index) { - GetRequest request = requestFactory.getRequest(query, index); + public T get(String id, Class clazz, IndexCoordinates index) { + GetRequest request = requestFactory.getRequest(id, index); try { GetResponse response = client.get(request, RequestOptions.DEFAULT); return elasticsearchConverter.mapDocument(DocumentAdapters.from(response), clazz); @@ -153,6 +173,16 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate { } } + @Override + protected boolean doExists(String id, IndexCoordinates index) { + GetRequest request = requestFactory.getRequest(id, index); + try { + return client.get(request, RequestOptions.DEFAULT).isExists(); + } catch (IOException e) { + throw new ElasticsearchException("Error while getting for request: " + request.toString(), e); + } + } + @Override public List bulkIndex(List queries, BulkOptions bulkOptions, IndexCoordinates index) { @@ -173,6 +203,10 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate { @Override public String delete(String id, IndexCoordinates index) { + + Assert.notNull(id, "id must not be null"); + Assert.notNull(index, "index must not be null"); + DeleteRequest request = new DeleteRequest(index.getIndexName(), elasticsearchConverter.convertId(id)); try { return client.delete(request, RequestOptions.DEFAULT).getId(); @@ -182,6 +216,17 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate { } @Override + public void delete(Query query, Class clazz, IndexCoordinates index) { + DeleteByQueryRequest deleteByQueryRequest = requestFactory.deleteByQueryRequest(query, clazz, index); + try { + client.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT); + } catch (IOException e) { + throw new ElasticsearchException("Error for delete request: " + deleteByQueryRequest.toString(), e); + } + } + + @Override + @Deprecated public void delete(DeleteQuery deleteQuery, IndexCoordinates index) { DeleteByQueryRequest deleteByQueryRequest = requestFactory.deleteByQueryRequest(deleteQuery, index); try { @@ -195,7 +240,9 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate { public UpdateResponse update(UpdateQuery query, IndexCoordinates index) { UpdateRequest request = requestFactory.updateRequest(query, index); try { - return client.update(request, RequestOptions.DEFAULT); + org.elasticsearch.action.update.UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT); + UpdateResponse.Result result = UpdateResponse.Result.valueOf(updateResponse.getResult().name()); + return new UpdateResponse(result); } catch (IOException e) { throw new ElasticsearchException("Error while update for request: " + request.toString(), e); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java index b2ed56ee3..848ed4dc2 100755 --- a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java @@ -16,6 +16,7 @@ package org.springframework.data.elasticsearch.core; import java.util.List; +import java.util.Optional; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.bulk.BulkRequestBuilder; @@ -28,7 +29,6 @@ import org.elasticsearch.action.search.MultiSearchResponse; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.update.UpdateRequestBuilder; -import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.search.suggest.SuggestBuilder; @@ -41,10 +41,10 @@ import org.springframework.data.elasticsearch.core.document.SearchDocumentRespon import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.BulkOptions; import org.springframework.data.elasticsearch.core.query.DeleteQuery; -import org.springframework.data.elasticsearch.core.query.GetQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.data.elasticsearch.core.query.UpdateQuery; +import org.springframework.data.elasticsearch.core.query.UpdateResponse; import org.springframework.data.elasticsearch.support.SearchHitsUtil; import org.springframework.lang.Nullable; import org.springframework.util.Assert; @@ -97,9 +97,29 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate { } private void initialize(Client client, ElasticsearchConverter elasticsearchConverter) { + Assert.notNull(client, "Client must not be null!"); + this.client = client; - initialize(elasticsearchConverter, new DefaultTransportIndexOperations(client, elasticsearchConverter)); + initialize(elasticsearchConverter); + } + // endregion + + // region IndexOperations + @Override + public IndexOperations indexOps(Class clazz) { + + Assert.notNull(clazz, "clazz must not be null"); + + return new DefaultTransportIndexOperations(client, elasticsearchConverter, clazz); + } + + @Override + public IndexOperations indexOps(IndexCoordinates index) { + + Assert.notNull(index, "index must not be null"); + + return new DefaultTransportIndexOperations(client, elasticsearchConverter, index); } // endregion @@ -128,8 +148,8 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate { @Override @Nullable - public T get(GetQuery query, Class clazz, IndexCoordinates index) { - GetRequestBuilder getRequestBuilder = requestFactory.getRequestBuilder(client, query, index); + public T get(String id, Class clazz, IndexCoordinates index) { + GetRequestBuilder getRequestBuilder = requestFactory.getRequestBuilder(client, id, index); GetResponse response = getRequestBuilder.execute().actionGet(); return elasticsearchConverter.mapDocument(DocumentAdapters.from(response), clazz); } @@ -145,6 +165,12 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate { return elasticsearchConverter.mapDocuments(DocumentAdapters.from(builder.execute().actionGet()), clazz); } + @Override + protected boolean doExists(String id, IndexCoordinates index) { + GetRequestBuilder getRequestBuilder = requestFactory.getRequestBuilder(client, id, index); + return getRequestBuilder.execute().actionGet().isExists(); + } + @Override public List bulkIndex(List queries, BulkOptions bulkOptions, IndexCoordinates index) { @@ -165,19 +191,36 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate { @Override public String delete(String id, IndexCoordinates index) { + + Assert.notNull(id, "id must not be null"); + Assert.notNull(index, "index must not be null"); + return client.prepareDelete(index.getIndexName(), IndexCoordinates.TYPE, elasticsearchConverter.convertId(id)) .execute().actionGet().getId(); } @Override + @Deprecated public void delete(DeleteQuery deleteQuery, IndexCoordinates index) { requestFactory.deleteByQueryRequestBuilder(client, deleteQuery, index).get(); } + @Override + public void delete(Query query, Class clazz, IndexCoordinates index) { + requestFactory.deleteByQueryRequestBuilder(client, query, clazz, index).get(); + } + + @Override + public String delete(Object entity, IndexCoordinates index) { + return super.delete(entity, index); + } + @Override public UpdateResponse update(UpdateQuery query, IndexCoordinates index) { UpdateRequestBuilder updateRequestBuilder = requestFactory.updateRequestBuilderFor(client, query, index); - return updateRequestBuilder.execute().actionGet(); + org.elasticsearch.action.update.UpdateResponse updateResponse = updateRequestBuilder.execute().actionGet(); + UpdateResponse.Result result = UpdateResponse.Result.valueOf(updateResponse.getResult().name()); + return new UpdateResponse(result); } private List doBulkOperation(List queries, BulkOptions bulkOptions, IndexCoordinates index) { diff --git a/src/main/java/org/springframework/data/elasticsearch/core/IndexOperations.java b/src/main/java/org/springframework/data/elasticsearch/core/IndexOperations.java index 31f79f2c5..1eeaeb52d 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/IndexOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/IndexOperations.java @@ -19,13 +19,17 @@ import java.util.List; import java.util.Map; import org.elasticsearch.cluster.metadata.AliasMetaData; +import org.springframework.data.elasticsearch.core.document.Document; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.query.AliasQuery; /** * The operations for the * Elasticsearch Index APIs. - * + *
+ * IndexOperations are bound to an entity class or an IndexCoordinate by + * {@link ElasticsearchOperations#indexOps(IndexCoordinates)} or {@link ElasticsearchOperations#indexOps(Class)} + * * @author Peter-Josef Meisch * @author Sascha Woo * @since 4.0 @@ -33,204 +37,104 @@ import org.springframework.data.elasticsearch.core.query.AliasQuery; public interface IndexOperations { /** - * Create an index for given indexName. + * Create an index. * - * @param indexName the name of the index * @return {@literal true} if the index was created */ - boolean createIndex(String indexName); + boolean create(); /** - * Create an index for given indexName and Settings. + * Create an index for given Settings. * - * @param indexName the name of the index * @param settings the index settings * @return {@literal true} if the index was created */ - boolean createIndex(String indexName, Object settings); + boolean create(Document settings); /** - * Create an index for a class. + * Deletes the index this {@link IndexOperations} is bound to * - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document} - * @return {@literal true} if the index was created - */ - boolean createIndex(Class clazz); - - /** - * Create an index for given class and Settings. - * - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document} - * @param settings the index settings - * @return {@literal true} if the index was created - */ - boolean createIndex(Class clazz, Object settings); - - /** - * Deletes an index for given entity. - * - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document} * @return {@literal true} if the index was deleted */ - boolean deleteIndex(Class clazz); + boolean delete(); /** - * Deletes an index. + * Checks if the index this IndexOperations is bound to exists * - * @param indexName the name of the index to delete - * @return {@literal true} if the index was deleted - */ - boolean deleteIndex(String indexName); - - /** - * check if index exists. - * - * @param indexName the name of the index * @return {@literal true} if the index exists */ - boolean indexExists(String indexName); + boolean exists(); /** - * check if index is exists. - * - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document} - * @return {@literal true} if the index exists + * Refresh the index(es) this IndexOperations is bound to */ - boolean indexExists(Class clazz); + void refresh(); /** - * Create mapping for a class and store it to the index. + * Creates the index mapping for the entity this IndexOperations is bound to. * - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document} + * @return mapping object + */ + Document createMapping(); + + /** + * Creates the index mapping for the given class + * + * @param clazz the clazz to create a mapping for + * @return mapping object + */ + Document createMapping(Class clazz); + + /** + * writes a mapping to the index + * + * @param mapping the Document with the mapping definitions * @return {@literal true} if the mapping could be stored */ - boolean putMapping(Class clazz); - - /** - * Create mapping for the given class and put the mapping to the given index. - * - * @param index the index to store the mapping to - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document} - * @return {@literal true} if the mapping could be stored - */ - boolean putMapping(IndexCoordinates index, Class clazz); - - /** - * Stores a mapping to an index. - * - * @param index the index to store the mapping to - * @param mappings can be a JSON String or a {@link Map} - * @return {@literal true} if the mapping could be stored - */ - boolean putMapping(IndexCoordinates index, Object mappings); - - /** - * Create mapping for a class Stores a mapping to an index. - * - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document} - * @param mappings can be a JSON String or a {@link Map} - * @return {@literal true} if the mapping could be stored - */ - boolean putMapping(Class clazz, Object mappings); + boolean putMapping(Document mapping); /** * Get mapping for an index defined by a class. * - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document}. * @return the mapping */ - Map getMapping(Class clazz); - - /** - * Get mapping for a given index. - * - * @param index the index to read the mapping from - * @return the mapping - */ - Map getMapping(IndexCoordinates index); + Map getMapping(); /** * Add an alias. * * @param query query defining the alias - * @param index the index for which to add an alias * @return true if the alias was created */ - boolean addAlias(AliasQuery query, IndexCoordinates index); + boolean addAlias(AliasQuery query); + + /** + * Get the alias informations for a specified index. + * + * @return alias information + */ + List queryForAlias(); /** * Remove an alias. * * @param query query defining the alias - * @param index the index for which to remove an alias * @return true if the alias was removed */ - boolean removeAlias(AliasQuery query, IndexCoordinates index); + boolean removeAlias(AliasQuery query); /** - * Get the alias informations for a specified index. + * Get the index settings. * - * @param indexName the name of the index - * @return alias information + * @return the settings */ - List queryForAlias(String indexName); + Map getSettings(); /** * Get settings for a given indexName. * - * @param indexName the name of the index + * @param includeDefaults wehther or not to include all the default settings * @return the settings */ - Map getSettings(String indexName); - - /** - * Get settings for a given indexName. - * - * @param indexName the name of the index - * @param includeDefaults whether or not to include all the default settings - * @return the settings - */ - Map getSettings(String indexName, boolean includeDefaults); - - /** - * Get settings for a given class. - * - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document} - * @return the settings - */ - Map getSettings(Class clazz); - - /** - * Get settings for a given class. - * - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document} - * @param includeDefaults whether or not to include all the default settings - * @return the settings - */ - Map getSettings(Class clazz, boolean includeDefaults); - - /** - * Refresh the index(es). - * - * @param index the index to refresh - */ - void refresh(IndexCoordinates index); - - /** - * Refresh the index. - * - * @param clazz The entity class, must be annotated with - * {@link org.springframework.data.elasticsearch.annotations.Document} - */ - void refresh(Class clazz); + Map getSettings(boolean includeDefaults); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/ReactiveDocumentOperations.java b/src/main/java/org/springframework/data/elasticsearch/core/ReactiveDocumentOperations.java index d0c8b353e..955a122bb 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/ReactiveDocumentOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ReactiveDocumentOperations.java @@ -151,8 +151,37 @@ public interface ReactiveDocumentOperations { * @param entityType the domain type used for mapping the document. * @param * @return {@link Mono#empty()} if not found. + * @deprecated since 4.0 use {@link #get(String, Class)} */ - Mono findById(String id, Class entityType); + @Deprecated + default Mono findById(String id, Class entityType) { + return get(id, entityType); + } + + /** + * Fetch the entity with given {@literal id}. + * + * @param id must not be {@literal null}. + * @param index the target index, must not be {@literal null} + * @param + * @return the {@link Mono} emitting the entity or signalling completion if none found. + * @deprecated since 4.0, use {@link #get(String, Class, IndexCoordinates)} + */ + @Deprecated + default Mono findById(String id, Class entityType, IndexCoordinates index) { + return get(id, entityType, index); + } + + /** + * Find the document with the given {@literal id} mapped onto the given {@literal entityType}. + * + * @param id the {@literal _id} of the document to fetch. + * @param entityType the domain type used for mapping the document. + * @param + * @return {@link Mono#empty()} if not found. + * @since 4.0 + */ + Mono get(String id, Class entityType); /** * Fetch the entity with given {@literal id}. @@ -162,7 +191,7 @@ public interface ReactiveDocumentOperations { * @param * @return the {@link Mono} emitting the entity or signalling completion if none found. */ - Mono findById(String id, Class entityType, IndexCoordinates index); + Mono get(String id, Class entityType, IndexCoordinates index); /** * Check if an entity with given {@literal id} exists. @@ -180,6 +209,17 @@ public interface ReactiveDocumentOperations { * @param index the target index, must not be {@literal null} * @return a {@link Mono} emitting {@literal true} if a matching document exists, {@literal false} otherwise. */ + Mono exists(String id, IndexCoordinates index); + + /** + * Check if an entity with given {@literal id} exists. + * + * @param id the {@literal _id} of the document to look for. + * @param index the target index, must not be {@literal null} + * @return a {@link Mono} emitting {@literal true} if a matching document exists, {@literal false} otherwise. + * @deprecated since 4.0, use {@link #exists(String, Class)} or {@link #exists(String, IndexCoordinates)} + */ + @Deprecated Mono exists(String id, Class entityType, IndexCoordinates index); /** @@ -188,7 +228,7 @@ public interface ReactiveDocumentOperations { * @param entity must not be {@literal null}. * @return a {@link Mono} emitting the {@literal id} of the removed document. */ - Mono delete(Object entity); + Mono delete(Object entity); /** * Delete the given entity extracting index and type from entity metadata. @@ -197,7 +237,7 @@ public interface ReactiveDocumentOperations { * @param index the target index, must not be {@literal null} * @return a {@link Mono} emitting the {@literal id} of the removed document. */ - Mono delete(Object entity, IndexCoordinates index); + Mono delete(Object entity, IndexCoordinates index); /** * Delete the entity with given {@literal id}. @@ -206,32 +246,32 @@ public interface ReactiveDocumentOperations { * @param index the target index, must not be {@literal null} * @return a {@link Mono} emitting the {@literal id} of the removed document. */ - default Mono deleteById(String id, IndexCoordinates index) { + Mono delete(String id, IndexCoordinates index); - Assert.notNull(index, "Index must not be null!"); + /** + * Delete the entity with given {@literal id} extracting index and type from entity metadata. + * + * @param id must not be {@literal null}. + * @param entityType must not be {@literal null}. + * @return a {@link Mono} emitting the {@literal id} of the removed document. + * @since 4.0 + */ + Mono delete(String id, Class entityType); - return deleteById(id, Object.class, index); + /** + * Delete the entity with given {@literal id} extracting index and type from entity metadata. + * + * @param id must not be {@literal null}. + * @param entityType must not be {@literal null}. + * @param index the target index, must not be {@literal null} + * @return a {@link Mono} emitting the {@literal id} of the removed document. + * @deprecated since 4.0, use {@link #delete(String, Class)} or {@link #deleteById(String, IndexCoordinates)} + */ + @Deprecated + default Mono delete(String id, Class entityType, IndexCoordinates index) { + return delete(id, index); } - /** - * Delete the entity with given {@literal id} extracting index and type from entity metadata. - * - * @param id must not be {@literal null}. - * @param entityType must not be {@literal null}. - * @return a {@link Mono} emitting the {@literal id} of the removed document. - */ - Mono deleteById(String id, Class entityType); - - /** - * Delete the entity with given {@literal id} extracting index and type from entity metadata. - * - * @param id must not be {@literal null}. - * @param entityType must not be {@literal null}. - * @param index the target index, must not be {@literal null} - * @return a {@link Mono} emitting the {@literal id} of the removed document. - */ - Mono deleteById(String id, Class entityType, IndexCoordinates index); - /** * Delete the documents matching the given {@link Query} extracting index and type from entity metadata. * @@ -239,7 +279,7 @@ public interface ReactiveDocumentOperations { * @param entityType must not be {@literal null}. * @return a {@link Mono} emitting the number of the removed documents. */ - Mono deleteBy(Query query, Class entityType); + Mono delete(Query query, Class entityType); /** * Delete the documents matching the given {@link Query} extracting index and type from entity metadata. @@ -249,5 +289,5 @@ public interface ReactiveDocumentOperations { * @param index the target index, must not be {@literal null} * @return a {@link Mono} emitting the number of the removed documents. */ - Mono deleteBy(Query query, Class entityType, IndexCoordinates index); + Mono delete(Query query, Class entityType, IndexCoordinates index); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplate.java b/src/main/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplate.java index 8c5826362..ada81c511 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplate.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplate.java @@ -243,21 +243,31 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera } } - /** - * Customization hook on the actual execution result {@link Publisher}.
- * - * @param request the already prepared {@link GetRequest} ready to be executed. - * @return a {@link Mono} emitting the result of the operation. - */ - protected Mono doFindById(GetRequest request) { - - return Mono.from(execute(client -> client.get(request))) // - .onErrorResume(NoSuchIndexException.class, it -> Mono.empty()); + @Override + public Mono exists(String id, Class entityType) { + return doExists(id, getIndexCoordinatesFor(entityType)); } @Override - public Mono exists(String id, Class entityType) { - return exists(id, entityType, getIndexCoordinatesFor(entityType)); + public Mono exists(String id, IndexCoordinates index) { + return doExists(id, index); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#exists(String, Class, IndexCoordinates) + */ + @Override + public Mono exists(String id, Class entityType, IndexCoordinates index) { + + Assert.notNull(id, "Id must not be null!"); + + return doExists(id, index); + } + + private Mono doExists(String id, @Nullable IndexCoordinates index) { + + return Mono.defer(() -> doExists(new GetRequest(index.getIndexName(), id))); } /** @@ -320,46 +330,35 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera } @Override - public Mono findById(String id, Class entityType) { - return findById(id, entityType, getIndexCoordinatesFor(entityType)); + public Mono get(String id, Class entityType) { + return get(id, entityType, getIndexCoordinatesFor(entityType)); } - /* - * (non-Javadoc) - * @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#findById(String, Class, IndexCoordinates) - */ @Override - public Mono findById(String id, Class entityType, IndexCoordinates index) { + public Mono get(String id, Class entityType, IndexCoordinates index) { Assert.notNull(id, "Id must not be null!"); - return doFindById(id, getPersistentEntityFor(entityType), index) + return doGet(id, getPersistentEntityFor(entityType), index) .map(it -> converter.mapDocument(DocumentAdapters.from(it), entityType)); } - private Mono doFindById(String id, ElasticsearchPersistentEntity entity, IndexCoordinates index) { - + private Mono doGet(String id, ElasticsearchPersistentEntity entity, IndexCoordinates index) { return Mono.defer(() -> { - - return doFindById(new GetRequest(index.getIndexName(), id)); + return doGet(new GetRequest(index.getIndexName(), id)); }); } - /* - * (non-Javadoc) - * @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#exists(String, Class, IndexCoordinates) + /** + * Customization hook on the actual execution result {@link Publisher}.
+ * + * @param request the already prepared {@link GetRequest} ready to be executed. + * @return a {@link Mono} emitting the result of the operation. */ - @Override - public Mono exists(String id, Class entityType, IndexCoordinates index) { + protected Mono doGet(GetRequest request) { - Assert.notNull(id, "Id must not be null!"); - - return doExists(id, getPersistentEntityFor(entityType), index); - } - - private Mono doExists(String id, ElasticsearchPersistentEntity entity, @Nullable IndexCoordinates index) { - - return Mono.defer(() -> doExists(new GetRequest(index.getIndexName(), id))); + return Mono.from(execute(client -> client.get(request))) // + .onErrorResume(NoSuchIndexException.class, it -> Mono.empty()); } /* @@ -367,25 +366,11 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera * @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#delete(Object, String, String) */ @Override - public Mono delete(Object entity, IndexCoordinates index) { + public Mono delete(Object entity, IndexCoordinates index) { Entity elasticsearchEntity = operations.forEntity(entity); - return Mono.defer(() -> doDeleteById(entity, converter.convertId(elasticsearchEntity.getId()), - elasticsearchEntity.getPersistentEntity(), index)); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#delete(String, Class, IndexCoordinates) - */ - @Override - public Mono deleteById(String id, Class entityType, IndexCoordinates index) { - - Assert.notNull(id, "Id must not be null!"); - - return doDeleteById(null, id, getPersistentEntityFor(entityType), index); - + return Mono.defer(() -> doDeleteById(converter.convertId(elasticsearchEntity.getId()), index)); } @Override @@ -394,25 +379,37 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera } @Override - public Mono deleteById(String id, Class entityType) { - return deleteById(id, entityType, getIndexCoordinatesFor(entityType)); + public Mono delete(String id, Class entityType) { + + Assert.notNull(id, "id must not be null"); + Assert.notNull(entityType, "entityType must not be null"); + + return delete(id, getIndexCoordinatesFor(entityType)); } - private Mono doDeleteById(@Nullable Object source, String id, ElasticsearchPersistentEntity entity, - IndexCoordinates index) { + @Override + public Mono delete(String id, IndexCoordinates index) { + + Assert.notNull(id, "id must not be null"); + Assert.notNull(index, "index must not be null"); + + return doDeleteById(id, index); + } + + private Mono doDeleteById(String id, IndexCoordinates index) { return Mono.defer(() -> { - return doDelete(prepareDeleteRequest(source, new DeleteRequest(index.getIndexName(), id))); + return doDelete(prepareDeleteRequest(new DeleteRequest(index.getIndexName(), id))); }); } /* * (non-Javadoc) - * @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#deleteBy(Query, Class, IndexCoordinates) + * @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#delete(Query, Class, IndexCoordinates) */ @Override - public Mono deleteBy(Query query, Class entityType, IndexCoordinates index) { + public Mono delete(Query query, Class entityType, IndexCoordinates index) { Assert.notNull(query, "Query must not be null!"); @@ -421,8 +418,8 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera } @Override - public Mono deleteBy(Query query, Class entityType) { - return deleteBy(query, entityType, getIndexCoordinatesFor(entityType)); + public Mono delete(Query query, Class entityType) { + return delete(query, entityType, getIndexCoordinatesFor(entityType)); } private Flux doDeleteBy(Query query, ElasticsearchPersistentEntity entity, @@ -473,12 +470,10 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera * Customization hook to modify a generated {@link DeleteRequest} prior to its execution. Eg. by setting the * {@link WriteRequest#setRefreshPolicy(String) refresh policy} if applicable. * - * @param source the source object the {@link DeleteRequest} was derived from. My be {@literal null} if using the - * {@literal id} directly. * @param request the generated {@link DeleteRequest}. * @return never {@literal null}. */ - protected DeleteRequest prepareDeleteRequest(@Nullable Object source, DeleteRequest request) { + protected DeleteRequest prepareDeleteRequest(DeleteRequest request) { return prepareWriteRequest(request); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/RequestFactory.java b/src/main/java/org/springframework/data/elasticsearch/core/RequestFactory.java index 95113f373..e54d5aa23 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/RequestFactory.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/RequestFactory.java @@ -19,6 +19,7 @@ import static org.elasticsearch.index.query.QueryBuilders.*; import static org.springframework.util.CollectionUtils.*; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -44,8 +45,6 @@ import org.elasticsearch.client.indices.PutMappingRequest; import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.unit.TimeValue; -import org.elasticsearch.common.xcontent.XContentBuilder; -import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.query.MoreLikeThisQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; @@ -53,9 +52,10 @@ import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.reindex.DeleteByQueryAction; import org.elasticsearch.index.reindex.DeleteByQueryRequest; import org.elasticsearch.index.reindex.DeleteByQueryRequestBuilder; +import org.elasticsearch.script.Script; +import org.elasticsearch.script.ScriptType; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; -import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.GeoDistanceSortBuilder; @@ -67,6 +67,7 @@ import org.elasticsearch.search.sort.SortOrder; import org.springframework.data.domain.Sort; import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; +import org.springframework.data.elasticsearch.core.document.Document; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; @@ -180,31 +181,27 @@ class RequestFactory { } @SuppressWarnings("unchecked") - public CreateIndexRequest createIndexRequest(String indexName, Object settings) { + public CreateIndexRequest createIndexRequest(String indexName, @Nullable Document settings) { CreateIndexRequest request = new CreateIndexRequest(indexName); - if (settings instanceof String) { - request.settings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE); - } else if (settings instanceof Map) { - request.settings((Map) settings); - } else if (settings instanceof XContentBuilder) { - request.settings((XContentBuilder) settings); + + if (settings != null) { + request.settings(settings); } return request; } @SuppressWarnings("unchecked") - public CreateIndexRequestBuilder createIndexRequestBuilder(Client client, String indexName, Object settings) { + public CreateIndexRequestBuilder createIndexRequestBuilder(Client client, String indexName, + @Nullable Document settings) { CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(indexName); - if (settings instanceof String) { - createIndexRequestBuilder.setSettings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE); - } else if (settings instanceof Map) { - createIndexRequestBuilder.setSettings((Map) settings); - } else if (settings instanceof XContentBuilder) { - createIndexRequestBuilder.setSettings((XContentBuilder) settings); + + if (settings != null) { + createIndexRequestBuilder.setSettings(settings); } return createIndexRequestBuilder; } + @Deprecated public DeleteByQueryRequest deleteByQueryRequest(DeleteQuery deleteQuery, IndexCoordinates index) { DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(index.getIndexNames()) // .setQuery(deleteQuery.getQuery()) // @@ -220,6 +217,25 @@ class RequestFactory { return deleteByQueryRequest; } + public DeleteByQueryRequest deleteByQueryRequest(Query query, Class clazz, IndexCoordinates index) { + SearchRequest searchRequest = searchRequest(query, clazz, index); + DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(index.getIndexNames()) // + .setQuery(searchRequest.source().query()) // + .setAbortOnVersionConflict(false) // + .setRefresh(true); + + if (query.isLimiting()) { + deleteByQueryRequest.setBatchSize(query.getMaxResults()); + } + + if (query.hasScrollTime()) { + deleteByQueryRequest.setScroll(TimeValue.timeValueMillis(query.getScrollTime().toMillis())); + } + + return deleteByQueryRequest; + } + + @Deprecated public DeleteByQueryRequestBuilder deleteByQueryRequestBuilder(Client client, DeleteQuery deleteQuery, IndexCoordinates index) { DeleteByQueryRequestBuilder requestBuilder = new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE) // @@ -236,14 +252,37 @@ class RequestFactory { return requestBuilder; } - public GetRequest getRequest(GetQuery query, IndexCoordinates index) { - return new GetRequest(index.getIndexName(), query.getId()); + public DeleteByQueryRequestBuilder deleteByQueryRequestBuilder(Client client, Query query, Class clazz, + IndexCoordinates index) { + SearchRequest searchRequest = searchRequest(query, clazz, index); + DeleteByQueryRequestBuilder requestBuilder = new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE) // + .source(index.getIndexNames()) // + .filter(searchRequest.source().query()) // + .abortOnVersionConflict(false) // + .refresh(true); + + SearchRequestBuilder source = requestBuilder.source(); + + if (query.isLimiting()) { + source.setSize(query.getMaxResults()); + } + + if (query.hasScrollTime()) { + source.setScroll(TimeValue.timeValueMillis(query.getScrollTime().toMillis())); + } + + return requestBuilder; } - public GetRequestBuilder getRequestBuilder(Client client, GetQuery query, IndexCoordinates index) { - return client.prepareGet(index.getIndexName(), null, query.getId()); + public GetRequest getRequest(String id, IndexCoordinates index) { + return new GetRequest(index.getIndexName(), id); } + public GetRequestBuilder getRequestBuilder(Client client, String id, IndexCoordinates index) { + return client.prepareGet(index.getIndexName(), null, id); + } + + @Nullable public HighlightBuilder highlightBuilder(Query query) { HighlightBuilder highlightBuilder = query.getHighlightQuery().map(HighlightQuery::getHighlightBuilder).orElse(null); @@ -420,39 +459,40 @@ class RequestFactory { public UpdateRequest updateRequest(UpdateQuery query, IndexCoordinates index) { - Assert.notNull(query.getId(), "No Id define for Query"); - Assert.notNull(query.getUpdateRequest(), "No UpdateRequest define for Query"); + UpdateRequest updateRequest = new UpdateRequest(index.getIndexName(), query.getId()); - UpdateRequest queryUpdateRequest = query.getUpdateRequest(); + if (query.getScript() != null) { + Map params = query.getParams(); - UpdateRequest updateRequest = new UpdateRequest(index.getIndexName(), query.getId()) // - .routing(queryUpdateRequest.routing()) // - .retryOnConflict(queryUpdateRequest.retryOnConflict()) // - .timeout(queryUpdateRequest.timeout()) // - .waitForActiveShards(queryUpdateRequest.waitForActiveShards()) // - .setRefreshPolicy(queryUpdateRequest.getRefreshPolicy()) // - .waitForActiveShards(queryUpdateRequest.waitForActiveShards()) // - .scriptedUpsert(queryUpdateRequest.scriptedUpsert()) // - .docAsUpsert(queryUpdateRequest.docAsUpsert()); - - if (query.DoUpsert()) { - updateRequest.docAsUpsert(true); + if (params == null) { + params = new HashMap<>(); + } + Script script = new Script(ScriptType.INLINE, query.getLang(), query.getScript(), params); + updateRequest.script(script); } - if (queryUpdateRequest.script() != null) { - updateRequest.script(queryUpdateRequest.script()); + if (query.getDocument() != null) { + updateRequest.doc(query.getDocument()); } - if (queryUpdateRequest.doc() != null) { - updateRequest.doc(queryUpdateRequest.doc()); + if (query.getUpsert() != null) { + updateRequest.upsert(query.getUpsert()); } - if (queryUpdateRequest.upsertRequest() != null) { - updateRequest.upsert(queryUpdateRequest.upsertRequest()); + if (query.getRouting() != null) { + updateRequest.routing(query.getRouting()); } - if (queryUpdateRequest.fetchSource() != null) { - updateRequest.fetchSource(queryUpdateRequest.fetchSource()); + if (query.getScriptedUpsert() != null) { + updateRequest.scriptedUpsert(query.getScriptedUpsert()); + } + + if (query.getDocAsUpsert() != null) { + updateRequest.docAsUpsert(query.getDocAsUpsert()); + } + + if (query.getFetchSource() != null) { + updateRequest.fetchSource(query.getFetchSource()); } return updateRequest; @@ -460,41 +500,41 @@ class RequestFactory { public UpdateRequestBuilder updateRequestBuilderFor(Client client, UpdateQuery query, IndexCoordinates index) { - Assert.notNull(query.getId(), "No Id define for Query"); - Assert.notNull(query.getUpdateRequest(), "No UpdateRequest define for Query"); + UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate(index.getIndexName(), IndexCoordinates.TYPE, + query.getId()); - UpdateRequest queryUpdateRequest = query.getUpdateRequest(); + if (query.getScript() != null) { + Map params = query.getParams(); - UpdateRequestBuilder updateRequestBuilder = client - .prepareUpdate(index.getIndexName(), IndexCoordinates.TYPE, query.getId()) // - .setRouting(queryUpdateRequest.routing()) // - .setRetryOnConflict(queryUpdateRequest.retryOnConflict()) // - .setTimeout(queryUpdateRequest.timeout()) // - .setWaitForActiveShards(queryUpdateRequest.waitForActiveShards()) // - .setRefreshPolicy(queryUpdateRequest.getRefreshPolicy()) // - .setWaitForActiveShards(queryUpdateRequest.waitForActiveShards()) // - .setScriptedUpsert(queryUpdateRequest.scriptedUpsert()) // - .setDocAsUpsert(queryUpdateRequest.docAsUpsert()); - - if (query.DoUpsert()) { - updateRequestBuilder.setDocAsUpsert(true); + if (params == null) { + params = new HashMap<>(); + } + Script script = new Script(ScriptType.INLINE, query.getLang(), query.getScript(), params); + updateRequestBuilder.setScript(script); } - if (queryUpdateRequest.script() != null) { - updateRequestBuilder.setScript(queryUpdateRequest.script()); + if (query.getDocument() != null) { + updateRequestBuilder.setDoc(query.getDocument()); } - if (queryUpdateRequest.doc() != null) { - updateRequestBuilder.setDoc(queryUpdateRequest.doc()); + if (query.getUpsert() != null) { + updateRequestBuilder.setUpsert(query.getUpsert()); } - if (queryUpdateRequest.upsertRequest() != null) { - updateRequestBuilder.setUpsert(queryUpdateRequest.upsertRequest()); + if (query.getRouting() != null) { + updateRequestBuilder.setRouting(query.getRouting()); } - FetchSourceContext fetchSourceContext = queryUpdateRequest.fetchSource(); - if (fetchSourceContext != null) { - updateRequestBuilder.setFetchSource(fetchSourceContext.includes(), fetchSourceContext.excludes()); + if (query.getScriptedUpsert() != null) { + updateRequestBuilder.setScriptedUpsert(query.getScriptedUpsert()); + } + + if (query.getDocAsUpsert() != null) { + updateRequestBuilder.setDocAsUpsert(query.getDocAsUpsert()); + } + + if (query.getFetchSource() != null) { + updateRequestBuilder.setFetchSource(query.getFetchSource()); } return updateRequestBuilder; @@ -569,29 +609,17 @@ class RequestFactory { } @SuppressWarnings("unchecked") - public PutMappingRequest putMappingRequest(IndexCoordinates index, Object mapping) { + public PutMappingRequest putMappingRequest(IndexCoordinates index, Document mapping) { PutMappingRequest request = new PutMappingRequest(index.getIndexName()); - if (mapping instanceof String) { - request.source(String.valueOf(mapping), XContentType.JSON); - } else if (mapping instanceof Map) { - request.source((Map) mapping); - } else if (mapping instanceof XContentBuilder) { - request.source((XContentBuilder) mapping); - } + request.source(mapping); return request; } @SuppressWarnings("rawtypes") - public PutMappingRequestBuilder putMappingRequestBuilder(Client client, IndexCoordinates index, Object mapping) { + public PutMappingRequestBuilder putMappingRequestBuilder(Client client, IndexCoordinates index, Document mapping) { PutMappingRequestBuilder requestBuilder = client.admin().indices().preparePutMapping(index.getIndexName()) .setType(IndexCoordinates.TYPE); - if (mapping instanceof String) { - requestBuilder.setSource(String.valueOf(mapping), XContentType.JSON); - } else if (mapping instanceof Map) { - requestBuilder.setSource((Map) mapping); - } else if (mapping instanceof XContentBuilder) { - requestBuilder.setSource((XContentBuilder) mapping); - } + requestBuilder.setSource(mapping); return requestBuilder; } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/SearchOperations.java b/src/main/java/org/springframework/data/elasticsearch/core/SearchOperations.java index 4c173264b..9346d7e59 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/SearchOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/SearchOperations.java @@ -50,6 +50,15 @@ public interface SearchOperations { return count(query, null, index); } + /** + * return number of elements found by given query + * + * @param query the query to execute + * @param clazz the entity clazz used for property mapping and index name extraction + * @return count + */ + long count(Query query, Class clazz); + /** * return number of elements found by given query * @@ -211,50 +220,6 @@ public interface SearchOperations { return search(query, clazz, index).map(SearchHit::getId).toList(); } - /** - * Returns scrolled page for given query - * - * @param scrollTimeInMillis duration of the scroll time - * @param query The search query. - * @param clazz The class of entity to retrieve. - * @param index the index to run the query against - * @return scrolled page result - * @deprecated since 4.0, use {@link #searchScrollStart(long, Query, Class, IndexCoordinates)}. - */ - @Deprecated - default ScrolledPage startScroll(long scrollTimeInMillis, Query query, Class clazz, - IndexCoordinates index) { - return (ScrolledPage) SearchHitSupport - .unwrapSearchHits(searchScrollStart(scrollTimeInMillis, query, clazz, index)); - } - - /** - * Returns next scrolled page. - * - * @param scrollId the scroll id - * @param scrollTimeInMillis duration of the scroll time - * @param clazz The class of entity to retrieve. - * @return scrolled page result - * @deprecated since 4.0, use {@link #searchScrollContinue(String, long, Class)}. - */ - @SuppressWarnings("unchecked") - @Deprecated - default ScrolledPage continueScroll(@Nullable String scrollId, long scrollTimeInMillis, Class clazz) { - return (ScrolledPage) SearchHitSupport - .unwrapSearchHits(searchScrollContinue(scrollId, scrollTimeInMillis, clazz)); - } - - /** - * Clears the search contexts associated with specified scroll ids. - * - * @param scrollId the scroll id - * @deprecated since 4.0, use {@link #searchScrollClear(String)}. - */ - @Deprecated - default void clearScroll(String scrollId) { - searchScrollClear(scrollId); - } - /** * more like this query to search for documents that are "like" a specific document. * @@ -271,8 +236,32 @@ public interface SearchOperations { AggregatedPage> aggregatedPage = SearchHitSupport.page(searchHits, query.getPageable()); return (AggregatedPage) SearchHitSupport.unwrapSearchHits(aggregatedPage); } + + // endregion + /** + * Does a suggest query + * + * @param suggestion the query + * @param index the index to run the query against + * @return the suggest response + */ + SearchResponse suggest(SuggestBuilder suggestion, IndexCoordinates index); + + /** + * Execute the query against elasticsearch and return the first returned object. + * + * @param query the query to execute + * @param clazz the entity clazz used for property mapping and indexname extraction + * @return the first found object + */ + @Nullable + default SearchHit searchOne(Query query, Class clazz) { + List> content = search(query, clazz).getSearchHits(); + return content.isEmpty() ? null : content.get(0); + } + /** * Execute the query against elasticsearch and return the first returned object. * @@ -308,6 +297,16 @@ public interface SearchOperations { */ List> multiSearch(List queries, List> classes, IndexCoordinates index); + /** + * Execute the criteria query against elasticsearch and return result as {@link SearchHits} + * + * @param element return type + * @param query the query to execute + * @param clazz the entity clazz used for property mapping and index name extraction + * @return SearchHits containing the list of found objects + */ + SearchHits search(Query query, Class clazz); + /** * Execute the criteria query against elasticsearch and return result as {@link SearchHits} * @@ -319,6 +318,16 @@ public interface SearchOperations { */ SearchHits search(Query query, Class clazz, IndexCoordinates index); + /** + * more like this query to search for documents that are "like" a specific document. + * + * @param element return type + * @param query the query to execute + * @param clazz the entity clazz used for property mapping and index name extraction + * @return SearchHits containing the list of found objects + */ + SearchHits search(MoreLikeThisQuery query, Class clazz); + /** * more like this query to search for documents that are "like" a specific document. * @@ -331,34 +340,16 @@ public interface SearchOperations { SearchHits search(MoreLikeThisQuery query, Class clazz, IndexCoordinates index); /** - * Returns scrolled page for given query + * Executes the given {@link Query} against elasticsearch and return result as {@link CloseableIterator}. + *

* - * @param scrollTimeInMillis duration of the scroll time - * @param query The search query. - * @param clazz The class of entity to retrieve. - * @param index the index to run the query against - * @return scrolled page result + * @param element return type + * @param query the query to execute + * @param clazz the entity clazz used for property mapping and index name extraction + * @return a {@link CloseableIterator} that wraps an Elasticsearch scroll context that needs to be closed in case of * + * error. */ - ScrolledPage> searchScrollStart(long scrollTimeInMillis, Query query, Class clazz, - IndexCoordinates index); - - /** - * Returns next scrolled page - * - * @param scrollId the scroll id - * @param scrollTimeInMillis duration of the scroll time - * @param clazz The class of entity to retrieve. - * @return scrolled page result - */ - ScrolledPage> searchScrollContinue(@Nullable String scrollId, long scrollTimeInMillis, - Class clazz); - - /** - * Clears the search contexts associated with specified scroll ids. - * - * @param scrollId the scroll id - */ - void searchScrollClear(String scrollId); + CloseableIterator> searchForStream(Query query, Class clazz); /** * Executes the given {@link Query} against elasticsearch and return result as {@link CloseableIterator}. @@ -372,13 +363,4 @@ public interface SearchOperations { * error. */ CloseableIterator> searchForStream(Query query, Class clazz, IndexCoordinates index); - - /** - * Does a suggest query - * - * @param suggestion the query - * @param index the index to run the query against - * @return the suggest response - */ - SearchResponse suggest(SuggestBuilder suggestion, IndexCoordinates index); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/document/Document.java b/src/main/java/org/springframework/data/elasticsearch/core/document/Document.java index 1c5c856cc..82c91ccfc 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/document/Document.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/document/Document.java @@ -58,7 +58,7 @@ public interface Document extends Map { * @param map source map containing key-value pairs and sub-documents. must not be {@literal null}. * @return a new {@link Document}. */ - static Document from(Map map) { + static Document from(Map map) { Assert.notNull(map, "Map must not be null"); diff --git a/src/main/java/org/springframework/data/elasticsearch/core/document/MapDocument.java b/src/main/java/org/springframework/data/elasticsearch/core/document/MapDocument.java index 665629197..a9f114969 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/document/MapDocument.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/document/MapDocument.java @@ -46,7 +46,7 @@ class MapDocument implements Document { this(new LinkedHashMap<>()); } - MapDocument(Map documentAsMap) { + MapDocument(Map documentAsMap) { this.documentAsMap = new LinkedHashMap<>(documentAsMap); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/AbstractQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/AbstractQuery.java index 5853c7123..3bb80a398 100755 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/AbstractQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/AbstractQuery.java @@ -17,6 +17,7 @@ package org.springframework.data.elasticsearch.core.query; import static java.util.Collections.*; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -56,6 +57,7 @@ abstract class AbstractQuery implements Query { @Nullable protected Integer maxResults; @Nullable protected HighlightQuery highlightQuery; private boolean trackTotalHits = false; + @Nullable private Duration scrollTime; @Override @Nullable @@ -226,4 +228,15 @@ abstract class AbstractQuery implements Query { public boolean getTrackTotalHits() { return trackTotalHits; } + + @Nullable + @Override + public Duration getScrollTime() { + return scrollTime; + } + + @Override + public void setScrollTime(@Nullable Duration scrollTime) { + this.scrollTime = scrollTime; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/CriteriaQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/CriteriaQuery.java index b68f9d1d1..47de35a8b 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/CriteriaQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/CriteriaQuery.java @@ -16,7 +16,6 @@ package org.springframework.data.elasticsearch.core.query; import org.springframework.data.domain.Pageable; -import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -29,9 +28,7 @@ import org.springframework.util.Assert; */ public class CriteriaQuery extends AbstractQuery { - private @Nullable Criteria criteria; - - private CriteriaQuery() {} + private Criteria criteria; public CriteriaQuery(Criteria criteria) { this(criteria, Pageable.unpaged()); @@ -48,7 +45,7 @@ public class CriteriaQuery extends AbstractQuery { } public static Query fromQuery(CriteriaQuery source) { - return fromQuery(source, new CriteriaQuery()); + return fromQuery(source, new CriteriaQuery(source.criteria)); } public static T fromQuery(CriteriaQuery source, T destination) { @@ -56,9 +53,7 @@ public class CriteriaQuery extends AbstractQuery { Assert.notNull(source, "source must not be null"); Assert.notNull(destination, "destination must not be null"); - if (source.getCriteria() != null) { - destination.addCriteria(source.getCriteria()); - } + destination.addCriteria(source.getCriteria()); if (source.getSort() != null) { destination.addSort(source.getSort()); @@ -69,16 +64,13 @@ public class CriteriaQuery extends AbstractQuery { @SuppressWarnings("unchecked") public final T addCriteria(Criteria criteria) { + Assert.notNull(criteria, "Cannot add null criteria."); - if (this.criteria == null) { - this.criteria = criteria; - } else { - this.criteria.and(criteria); - } + + this.criteria.and(criteria); return (T) this; } - @Nullable public Criteria getCriteria() { return this.criteria; } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/DeleteQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/DeleteQuery.java index 9e57522f1..1dc5179ad 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/DeleteQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/DeleteQuery.java @@ -24,7 +24,9 @@ import org.springframework.lang.Nullable; * @author Rizwan Idrees * @author Mohsin Husen * @author Peter-Josef Meisch + * @deprecated since 4.0, use {@link Query} implementations and set {@link Query#setScrollTimeInMillis(Long)} and {@link Query#getMaxResults()} */ +@Deprecated public class DeleteQuery { @Nullable private QueryBuilder query; diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/GetQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/GetQuery.java index 38f02bd75..7874c9769 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/GetQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/GetQuery.java @@ -21,7 +21,9 @@ package org.springframework.data.elasticsearch.core.query; * @author Rizwan Idrees * @author Mohsin Husen * @author Peter-Josef Meisch + * @deprecated since 4.0 */ +@Deprecated public class GetQuery { public GetQuery(String id) { diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/IndexQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/IndexQuery.java index b949720e3..5865571e4 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/IndexQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/IndexQuery.java @@ -69,7 +69,12 @@ public class IndexQuery { this.source = source; } + /** + * @deprecated from 4.0. Elasticsearch 7 does not support the parent id in an index request. parent/child relations + * must be modeled using the join datatype. Setting it here will have no effect. + */ @Nullable + @Deprecated public String getParentId() { return parentId; } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQuery.java index 71245a8c3..28702eb83 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQuery.java @@ -94,6 +94,7 @@ public class NativeSearchQuery extends AbstractQuery { return filter; } + @Nullable public List getElasticsearchSorts() { return sorts; } @@ -103,6 +104,7 @@ public class NativeSearchQuery extends AbstractQuery { return highlightBuilder; } + @Nullable public HighlightBuilder.Field[] getHighlightFields() { return highlightFields; } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/Query.java b/src/main/java/org/springframework/data/elasticsearch/core/query/Query.java index ff0ebc37b..62656dd29 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/Query.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/Query.java @@ -15,6 +15,7 @@ */ package org.springframework.data.elasticsearch.core.query; +import java.time.Duration; import java.util.Collection; import java.util.List; import java.util.Optional; @@ -45,7 +46,7 @@ public interface Query { Pageable DEFAULT_PAGE = PageRequest.of(0, DEFAULT_PAGE_SIZE); /** - * Get get a {@link Query} that matches all documents in the index. + * Get a {@link Query} that matches all documents in the index. * * @return new instance of {@link Query}. * @since 3.2 @@ -229,4 +230,29 @@ public interface Query { * @since 4.0 */ boolean getTrackTotalHits(); + + /** + * For queries that are used in delete request, these are internally handled by Elasticsearch as scroll/bulk delete queries. + * + * @return the scrolltime settings + * @since 4.0 + */ + @Nullable + Duration getScrollTime(); + + /** + * For queries that are used in delete request, these are internally handled by Elasticsearch as scroll/bulk delete queries. + * + * @param scrollTime the scrolltime settings + * @since 4.0 + */ + void setScrollTime(@Nullable Duration scrollTime); + + /** + * @return {@literal true} if scrollTimeMillis is set. + * @since 4.0 + */ + default boolean hasScrollTime() { + return getScrollTime() != null; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQuery.java index dac5aa425..a346bf344 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQuery.java @@ -15,43 +15,168 @@ */ package org.springframework.data.elasticsearch.core.query; -import org.elasticsearch.action.update.UpdateRequest; +import java.util.Map; + +import org.springframework.data.elasticsearch.core.document.Document; import org.springframework.lang.Nullable; /** + * Defines an update request. + * * @author Rizwan Idrees * @author Mohsin Husen * @author Peter-Josef Meisch + * @see params) { + this.params = params; + return this; + } + + public Builder withDocument(Document document) { + this.document = document; + return this; + } + + public Builder withUpsert(Document upsert) { + this.upsert = upsert; + return this; + } + + public Builder withLang(String lang) { + this.lang = lang; + return this; + } + + public Builder withRouting(String routing) { + this.routing = routing; + return this; + } + + public Builder withScriptedUpsert(Boolean scriptedUpsert) { + this.scriptedUpsert = scriptedUpsert; + return this; + } + + public Builder withDocAsUpsert(Boolean docAsUpsert) { + this.docAsUpsert = docAsUpsert; + return this; + } + + public Builder withFetchSource(Boolean fetchSource) { + this.fetchSource = fetchSource; + return this; + } + + public UpdateQuery build() { + + if (script == null && document == null) { + throw new IllegalArgumentException("either script or document must be set"); + } + return new UpdateQuery(id, script, params, document, upsert, lang, routing, scriptedUpsert, docAsUpsert, + fetchSource); + } } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQueryBuilder.java b/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQueryBuilder.java deleted file mode 100644 index 1e116e69a..000000000 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQueryBuilder.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2013-2020 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.elasticsearch.core.query; - -import org.elasticsearch.action.index.IndexRequest; -import org.elasticsearch.action.update.UpdateRequest; -import org.springframework.lang.Nullable; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - * @author Peter-Josef Meisch - */ -public class UpdateQueryBuilder { - - @Nullable private String id; - @Nullable private UpdateRequest updateRequest; - @Nullable private IndexRequest indexRequest; - private boolean doUpsert; - - public UpdateQueryBuilder withId(String id) { - this.id = id; - return this; - } - - public UpdateQueryBuilder withUpdateRequest(UpdateRequest updateRequest) { - this.updateRequest = updateRequest; - return this; - } - - public UpdateQueryBuilder withIndexRequest(IndexRequest indexRequest) { - this.indexRequest = indexRequest; - return this; - } - - public UpdateQueryBuilder withDoUpsert(boolean doUpsert) { - this.doUpsert = doUpsert; - return this; - } - - public UpdateQuery build() { - UpdateQuery updateQuery = new UpdateQuery(); - updateQuery.setId(id); - if (this.indexRequest != null) { - if (this.updateRequest == null) { - updateRequest = new UpdateRequest(); - } - updateRequest.doc(indexRequest); - } - updateQuery.setUpdateRequest(updateRequest); - updateQuery.setDoUpsert(doUpsert); - return updateQuery; - } -} diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateResponse.java b/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateResponse.java new file mode 100644 index 000000000..ada659e81 --- /dev/null +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateResponse.java @@ -0,0 +1,45 @@ +/* + * Copyright 2020 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.elasticsearch.core.query; + +import org.springframework.util.Assert; + +/** + * Response data from an update request ({@link UpdateQuery}). Currently contains only the result status value from + * Elasticsearch. Should be extended if further information is needed. + * + * @author Peter-Josef Meisch + * @since 4.0 + */ +public class UpdateResponse { + + private Result result; + + public UpdateResponse(Result result) { + + Assert.notNull(result, "result must not be null"); + + this.result = result; + } + + public Result getResult() { + return result; + } + + public enum Result { + CREATED, UPDATED, DELETED, NOT_FOUND, NOOP; + } +} diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/query/AbstractReactiveElasticsearchRepositoryQuery.java b/src/main/java/org/springframework/data/elasticsearch/repository/query/AbstractReactiveElasticsearchRepositoryQuery.java index 09f8999b1..dcfd49b1e 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/query/AbstractReactiveElasticsearchRepositoryQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/query/AbstractReactiveElasticsearchRepositoryQuery.java @@ -116,7 +116,7 @@ abstract class AbstractReactiveElasticsearchRepositoryQuery implements Repositor ReactiveElasticsearchOperations operations) { if (isDeleteQuery()) { - return (query, type, targetType, indexCoordinates) -> operations.deleteBy(query, type, indexCoordinates); + return (query, type, targetType, indexCoordinates) -> operations.delete(query, type, indexCoordinates); } else if (isCountQuery()) { return (query, type, targetType, indexCoordinates) -> operations.count(query, type, indexCoordinates); } else if (isExistsQuery()) { diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchPartQuery.java b/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchPartQuery.java index 528701e41..c78f5e34d 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchPartQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchPartQuery.java @@ -82,7 +82,7 @@ public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery if (tree.isDelete()) { result = countOrGetDocumentsForDelete(query, accessor); elasticsearchOperations.delete(query, clazz, index); - elasticsearchOperations.getIndexOperations().refresh(index); + elasticsearchOperations.indexOps(index).refresh(); } else if (queryMethod.isPageQuery()) { query.setPageable(accessor.getPageable()); SearchHits searchHits = elasticsearchOperations.search(query, clazz, index); diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/AbstractElasticsearchRepository.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/AbstractElasticsearchRepository.java index c3ca2a834..b33bdc564 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/AbstractElasticsearchRepository.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/AbstractElasticsearchRepository.java @@ -44,9 +44,6 @@ import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; -import org.springframework.data.elasticsearch.core.query.DeleteQuery; -import org.springframework.data.elasticsearch.core.query.GetQuery; -import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.MoreLikeThisQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; @@ -79,23 +76,18 @@ public abstract class AbstractElasticsearchRepository implements Elastics protected ElasticsearchOperations operations; protected IndexOperations indexOperations; - protected @Nullable Class entityClass; + protected Class entityClass; protected @Nullable ElasticsearchEntityInformation entityInformation; - public AbstractElasticsearchRepository(ElasticsearchOperations operations) { - Assert.notNull(operations, "ElasticsearchOperations must not be null."); - this.operations = operations; - this.indexOperations = operations.getIndexOperations(); - } - public AbstractElasticsearchRepository(ElasticsearchEntityInformation metadata, ElasticsearchOperations operations) { - this(operations); + this.operations = operations; Assert.notNull(metadata, "ElasticsearchEntityInformation must not be null!"); this.entityInformation = metadata; - setEntityClass(this.entityInformation.getJavaType()); + this.entityClass = this.entityInformation.getJavaType(); + this.indexOperations = operations.indexOps(this.entityClass); try { if (createIndexAndMapping()) { createIndex(); @@ -107,11 +99,11 @@ public abstract class AbstractElasticsearchRepository implements Elastics } private void createIndex() { - indexOperations.createIndex(getEntityClass()); + indexOperations.create(); } private void putMapping() { - indexOperations.putMapping(getEntityClass()); + indexOperations.putMapping(indexOperations.createMapping(entityClass)); } private boolean createIndexAndMapping() { @@ -123,8 +115,7 @@ public abstract class AbstractElasticsearchRepository implements Elastics @Override public Optional findById(ID id) { - GetQuery query = new GetQuery(stringIdRepresentation(id)); - return Optional.ofNullable(operations.get(query, getEntityClass(), getIndexCoordinates())); + return Optional.ofNullable(operations.get(stringIdRepresentation(id), getEntityClass(), getIndexCoordinates())); } @Override @@ -180,7 +171,7 @@ public abstract class AbstractElasticsearchRepository implements Elastics Assert.notNull(entity, "Cannot save 'null' entity."); operations.save(entity, getIndexCoordinates()); - indexOperations.refresh(getIndexCoordinates()); + operations.indexOps(entity.getClass()).refresh(); return entity; } @@ -203,15 +194,16 @@ public abstract class AbstractElasticsearchRepository implements Elastics Assert.notNull(entities, "Cannot insert 'null' as a List."); - operations.save(entities, getIndexCoordinates()); - indexOperations.refresh(getIndexCoordinates()); + IndexCoordinates indexCoordinates = getIndexCoordinates(); + operations.save(entities, indexCoordinates); + operations.indexOps(indexCoordinates).refresh(); return entities; } @Override public boolean existsById(ID id) { - return findById(id).isPresent(); + return operations.exists(stringIdRepresentation(id), getIndexCoordinates()); } @SuppressWarnings("unchecked") @@ -273,7 +265,7 @@ public abstract class AbstractElasticsearchRepository implements Elastics IndexCoordinates indexCoordinates = getIndexCoordinates(); doDelete(id, indexCoordinates); - indexOperations.refresh(indexCoordinates); + indexOperations.refresh(); } @Override @@ -283,7 +275,7 @@ public abstract class AbstractElasticsearchRepository implements Elastics IndexCoordinates indexCoordinates = getIndexCoordinates(); doDelete(extractIdFromBean(entity), indexCoordinates); - indexOperations.refresh(indexCoordinates); + indexOperations.refresh(); } @Override @@ -303,11 +295,11 @@ public abstract class AbstractElasticsearchRepository implements Elastics if (idsQueryBuilder.ids().isEmpty()) { return; } - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(idsQueryBuilder); - operations.delete(deleteQuery, indexCoordinates); - indexOperations.refresh(indexCoordinates); + Query query = new NativeSearchQueryBuilder().withQuery(idsQueryBuilder).build(); + + operations.delete(query, getEntityClass(), indexCoordinates); + indexOperations.refresh(); } private void doDelete(@Nullable ID id, IndexCoordinates indexCoordinates) { @@ -318,19 +310,18 @@ public abstract class AbstractElasticsearchRepository implements Elastics @Override public void deleteAll() { - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(matchAllQuery()); IndexCoordinates indexCoordinates = getIndexCoordinates(); - operations.delete(deleteQuery, indexCoordinates); - indexOperations.refresh(indexCoordinates); + Query query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); + + operations.delete(query, getEntityClass(), indexCoordinates); + indexOperations.refresh(); } @Override public void refresh() { - indexOperations.refresh(getEntityClass()); + indexOperations.refresh(); } - @SuppressWarnings("unchecked") private Class resolveReturnedClassFromGenericType() { ParameterizedType parameterizedType = resolveReturnedClassFromGenericType(getClass()); @@ -367,11 +358,6 @@ public abstract class AbstractElasticsearchRepository implements Elastics return entityClass != null; } - public final void setEntityClass(Class entityClass) { - Assert.notNull(entityClass, "EntityClass must not be null."); - this.entityClass = entityClass; - } - @Nullable protected ID extractIdFromBean(T entity) { return entityInformation.getId(entity); @@ -389,7 +375,6 @@ public abstract class AbstractElasticsearchRepository implements Elastics protected abstract @Nullable String stringIdRepresentation(@Nullable ID id); - private IndexCoordinates getIndexCoordinates() { return operations.getIndexCoordinatesFor(getEntityClass()); } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepository.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepository.java index 2a4e51863..006bbded0 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepository.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepository.java @@ -35,10 +35,6 @@ public class SimpleElasticsearchRepository extends AbstractElasticsearchR super(metadata, elasticsearchOperations); } - public SimpleElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) { - super(elasticsearchOperations); - } - @Override protected @Nullable String stringIdRepresentation(@Nullable ID id) { return operations.stringIdRepresentation(id); diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleReactiveElasticsearchRepository.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleReactiveElasticsearchRepository.java index 9de865e0a..d75ed583c 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleReactiveElasticsearchRepository.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleReactiveElasticsearchRepository.java @@ -79,7 +79,7 @@ public class SimpleReactiveElasticsearchRepository implements ReactiveEla public Mono findById(ID id) { Assert.notNull(id, "Id must not be null!"); - return elasticsearchOperations.findById(convertId(id), entityInformation.getJavaType(), + return elasticsearchOperations.get(convertId(id), entityInformation.getJavaType(), entityInformation.getIndexCoordinates()); } @@ -154,7 +154,7 @@ public class SimpleReactiveElasticsearchRepository implements ReactiveEla Assert.notNull(id, "Id must not be null!"); return elasticsearchOperations - .deleteById(convertId(id), entityInformation.getJavaType(), entityInformation.getIndexCoordinates()) // + .delete(convertId(id), entityInformation.getIndexCoordinates()) // .then(); } @@ -200,7 +200,7 @@ public class SimpleReactiveElasticsearchRepository implements ReactiveEla }) // .flatMap(query -> { - return elasticsearchOperations.deleteBy(query, entityInformation.getJavaType(), + return elasticsearchOperations.delete(query, entityInformation.getJavaType(), entityInformation.getIndexCoordinates()); }) // .then(); @@ -210,7 +210,7 @@ public class SimpleReactiveElasticsearchRepository implements ReactiveEla public Mono deleteAll() { return elasticsearchOperations - .deleteBy(Query.findAll(), entityInformation.getJavaType(), entityInformation.getIndexCoordinates()) // + .delete(Query.findAll(), entityInformation.getJavaType(), entityInformation.getIndexCoordinates()) // .then(); } diff --git a/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java b/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java index 8e8150f18..e57bb32fc 100644 --- a/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java @@ -30,6 +30,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import org.apache.lucene.search.join.ScoreMode; import org.elasticsearch.index.query.BoolQueryBuilder; @@ -44,10 +45,8 @@ import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.InnerField; import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; -import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; -import org.springframework.data.elasticsearch.core.query.GetQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; @@ -68,13 +67,12 @@ import org.springframework.test.context.ContextConfiguration; public class NestedObjectTests { @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, Book.class); - IndexInitializer.init(indexOperations, Person.class); - IndexInitializer.init(indexOperations, PersonMultipleLevelNested.class); + IndexInitializer.init(operations.indexOps(Book.class)); + IndexInitializer.init(operations.indexOps(Person.class)); + IndexInitializer.init(operations.indexOps(PersonMultipleLevelNested.class)); } @Test @@ -126,7 +124,7 @@ public class NestedObjectTests { IndexCoordinates index = IndexCoordinates.of("test-index-person").withTypes("user"); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(Person.class); + operations.indexOps(Person.class).refresh(); QueryBuilder builder = nestedQuery("car", boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None); @@ -146,11 +144,10 @@ public class NestedObjectTests { // when operations.bulkIndex(indexQueries, IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user")); - indexOperations.refresh(PersonMultipleLevelNested.class); + operations.indexOps(PersonMultipleLevelNested.class).refresh(); // then - GetQuery getQuery = new GetQuery("1"); - PersonMultipleLevelNested personIndexed = operations.get(getQuery, PersonMultipleLevelNested.class, + PersonMultipleLevelNested personIndexed = operations.get("1", PersonMultipleLevelNested.class, IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user")); assertThat(personIndexed).isNotNull(); } @@ -166,7 +163,7 @@ public class NestedObjectTests { IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user")); // then - Map mapping = indexOperations.getMapping(PersonMultipleLevelNested.class); + Map mapping = operations.indexOps(PersonMultipleLevelNested.class).getMapping(); assertThat(mapping).isNotNull(); Map propertyMap = (Map) mapping.get("properties"); @@ -184,7 +181,7 @@ public class NestedObjectTests { // when IndexCoordinates index = IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user"); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(PersonMultipleLevelNested.class); + operations.indexOps(PersonMultipleLevelNested.class).refresh(); // then BoolQueryBuilder builder = boolQuery(); @@ -324,7 +321,7 @@ public class NestedObjectTests { IndexCoordinates index = IndexCoordinates.of("test-index-person").withTypes("user"); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(Person.class); + operations.indexOps(Person.class).refresh(); // when QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")), ScoreMode.None); @@ -373,7 +370,7 @@ public class NestedObjectTests { // when IndexCoordinates index = IndexCoordinates.of("test-index-book-nested-objects").withTypes("book"); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(Book.class); + operations.indexOps(Book.class).refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() diff --git a/src/test/java/org/springframework/data/elasticsearch/config/notnested/EnableElasticsearchRepositoriesTests.java b/src/test/java/org/springframework/data/elasticsearch/config/notnested/EnableElasticsearchRepositoriesTests.java index 37c3dbf04..6b5855602 100644 --- a/src/test/java/org/springframework/data/elasticsearch/config/notnested/EnableElasticsearchRepositoriesTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/notnested/EnableElasticsearchRepositoriesTests.java @@ -39,6 +39,7 @@ import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.Score; import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration; @@ -74,17 +75,19 @@ public class EnableElasticsearchRepositoriesTests implements ApplicationContextA @EnableElasticsearchRepositories static class Config {} - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + private IndexOperations indexOperations; @Autowired private SampleElasticsearchRepository repository; @Autowired(required = false) private SampleRepository nestedRepository; - interface SampleRepository extends Repository {} + interface SampleRepository extends Repository {} @BeforeEach public void before() { - IndexInitializer.init(indexOperations, SampleEntity.class); + indexOperations = operations.indexOps(SampleEntity.class); + IndexInitializer.init(indexOperations); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplateTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplateTests.java index 781f427c2..0abe01445 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplateTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplateTests.java @@ -23,14 +23,11 @@ import lombok.Builder; import lombok.Data; import org.elasticsearch.ElasticsearchStatusException; -import org.elasticsearch.action.index.IndexRequest; -import org.elasticsearch.common.xcontent.XContentType; import org.junit.jupiter.api.Test; 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.query.UpdateQuery; -import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.test.context.ContextConfiguration; @@ -57,16 +54,15 @@ public class ElasticsearchRestTemplateTests extends ElasticsearchTemplateTests { public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() { // when - IndexRequest indexRequest = new IndexRequest(); - indexRequest.source("{}", XContentType.JSON); - UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)).withIndexRequest(indexRequest).build(); + org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document + .create(); + UpdateQuery updateQuery = UpdateQuery.builder(randomNumeric(5)).withDocument(document).build(); assertThatThrownBy(() -> operations.update(updateQuery, index)).isInstanceOf(ElasticsearchStatusException.class); } @Data @Builder - @Document(indexName = "test-index-sample-core-rest-template", replicas = 0, - refreshInterval = "-1") + @Document(indexName = "test-index-sample-core-rest-template", replicas = 0, refreshInterval = "-1") static class SampleEntity { @Id private String id; diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java index f1bc0ad99..4c2d7a541 100755 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java @@ -19,6 +19,7 @@ import static org.apache.commons.lang.RandomStringUtils.*; import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.springframework.data.elasticsearch.annotations.FieldType.*; +import static org.springframework.data.elasticsearch.core.document.Document.*; import static org.springframework.data.elasticsearch.utils.IndexBuilder.*; import lombok.AllArgsConstructor; @@ -37,11 +38,11 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import org.assertj.core.util.Lists; -import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.update.UpdateRequest; @@ -112,20 +113,23 @@ public abstract class ElasticsearchTemplateTests { protected final IndexCoordinates index = IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME); @Autowired protected ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @BeforeEach public void before() { + indexOperations = operations.indexOps(SampleEntity.class); deleteIndices(); - indexOperations.createIndex(SampleEntity.class); - indexOperations.putMapping(SampleEntity.class); + indexOperations.create(); + indexOperations.putMapping(indexOperations.createMapping(SampleEntity.class)); - indexOperations.createIndex(SampleEntityUUIDKeyed.class); - indexOperations.putMapping(SampleEntityUUIDKeyed.class); + IndexOperations indexOpsSampleEntityUUIDKeyed = operations.indexOps(SampleEntityUUIDKeyed.class); + indexOpsSampleEntityUUIDKeyed.create(); + indexOpsSampleEntityUUIDKeyed.putMapping(indexOpsSampleEntityUUIDKeyed.createMapping(SampleEntityUUIDKeyed.class)); - indexOperations.createIndex(SearchHitsEntity.class); - indexOperations.putMapping(SearchHitsEntity.class); + IndexOperations indexOpsSearchHitsEntity = operations.indexOps(SearchHitsEntity.class); + indexOpsSearchHitsEntity.create(); + indexOpsSearchHitsEntity.putMapping(indexOpsSearchHitsEntity.createMapping(SearchHitsEntity.class)); } @AfterEach @@ -136,16 +140,16 @@ public abstract class ElasticsearchTemplateTests { private void deleteIndices() { - indexOperations.deleteIndex(SampleEntity.class); - indexOperations.deleteIndex(SampleEntityUUIDKeyed.class); - indexOperations.deleteIndex(UseServerConfigurationEntity.class); - indexOperations.deleteIndex(SampleMappingEntity.class); - indexOperations.deleteIndex(Book.class); - indexOperations.deleteIndex(INDEX_1_NAME); - indexOperations.deleteIndex(INDEX_2_NAME); - indexOperations.deleteIndex(INDEX_3_NAME); - indexOperations.deleteIndex(SearchHitsEntity.class); - indexOperations.deleteIndex(HighlightEntity.class); + indexOperations.delete(); + operations.indexOps(SampleEntityUUIDKeyed.class).delete(); + operations.indexOps(UseServerConfigurationEntity.class).delete(); + operations.indexOps(SampleMappingEntity.class).delete(); + operations.indexOps(Book.class).delete(); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).delete(); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).delete(); + operations.indexOps(IndexCoordinates.of(INDEX_3_NAME)).delete(); + operations.indexOps(SearchHitsEntity.class).delete(); + operations.indexOps(HighlightEntity.class).delete(); } @Test // DATAES-106 @@ -158,7 +162,8 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); + ; CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); // when @@ -179,7 +184,8 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); + ; NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); // when @@ -200,11 +206,9 @@ public abstract class ElasticsearchTemplateTests { operations.index(indexQuery, index); // when - GetQuery getQuery = new GetQuery(documentId); - SampleEntity sampleEntity1 = operations.get(getQuery, SampleEntity.class, index); + SampleEntity sampleEntity1 = operations.get(documentId, SampleEntity.class, index); // then - assertThat(sampleEntity1).isNotNull(); assertThat(sampleEntity1).isEqualTo(sampleEntity); } @@ -225,7 +229,7 @@ public abstract class ElasticsearchTemplateTests { List indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2)); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when NativeSearchQuery query = new NativeSearchQueryBuilder().withIds(Arrays.asList(documentId, documentId2)).build(); @@ -254,7 +258,7 @@ public abstract class ElasticsearchTemplateTests { List indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2)); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when NativeSearchQuery query = new NativeSearchQueryBuilder().withIds(Arrays.asList(documentId, documentId2)) @@ -276,7 +280,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); @@ -300,7 +304,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQueryWithValidPreference = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPreference("_local").build(); @@ -324,7 +328,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQueryWithInvalidPreference = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPreference("_only_nodes:oops").build(); @@ -345,7 +349,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery idxQuery = new IndexQueryBuilder().withId(sampleEntity.getId()).withObject(sampleEntity).build(); operations.index(idxQuery, IndexCoordinates.of(INDEX_1_NAME).withTypes("test-type")); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withIndicesOptions(IndicesOptions.lenientExpandOpen()).build(); @@ -377,7 +381,7 @@ public abstract class ElasticsearchTemplateTests { indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2)); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); @@ -402,11 +406,14 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); - IndexRequest indexRequest = new IndexRequest(); - indexRequest.source("message", messageAfterUpdate); - UpdateQuery updateQuery = new UpdateQueryBuilder().withId(documentId).withIndexRequest(indexRequest).build(); + org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document + .create(); + document.put("message", messageAfterUpdate); + UpdateQuery updateQuery = UpdateQuery.builder(documentId) // + .withDocument(document) // + .build(); List queries = new ArrayList<>(); queries.add(updateQuery); @@ -415,8 +422,7 @@ public abstract class ElasticsearchTemplateTests { operations.bulkUpdate(queries, index); // then - GetQuery getQuery = new GetQuery(documentId); - SampleEntity indexedEntity = operations.get(getQuery, SampleEntity.class, index); + SampleEntity indexedEntity = operations.get(documentId, SampleEntity.class, index); assertThat(indexedEntity.getMessage()).isEqualTo(messageAfterUpdate); } @@ -434,7 +440,7 @@ public abstract class ElasticsearchTemplateTests { // when operations.delete(documentId, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); @@ -457,7 +463,7 @@ public abstract class ElasticsearchTemplateTests { // when operations.delete(documentId, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); @@ -476,13 +482,12 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(termQuery("id", documentId)); - operations.delete(deleteQuery, index); - indexOperations.refresh(SampleEntity.class); + Query query = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); + operations.delete(query, SampleEntity.class, index); + indexOperations.refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); @@ -502,21 +507,19 @@ public abstract class ElasticsearchTemplateTests { IndexQuery idxQuery1 = new IndexQueryBuilder().withId(randomNumeric(5)).withObject(sampleEntity).build(); operations.index(idxQuery1, IndexCoordinates.of(INDEX_1_NAME).withTypes("test-type")); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); IndexQuery idxQuery2 = new IndexQueryBuilder().withId(randomNumeric(5)).withObject(sampleEntity).build(); operations.index(idxQuery2, IndexCoordinates.of(INDEX_2_NAME).withTypes("test-type")); - indexOperations.refresh(IndexCoordinates.of(INDEX_2_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).refresh(); // when - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(termQuery("message", "foo")); + Query query = new NativeSearchQueryBuilder().withQuery(termQuery("message", "foo")).build(); + operations.delete(query, SampleEntity.class, IndexCoordinates.of("test-index-*").withTypes(TYPE_NAME)); - operations.delete(deleteQuery, IndexCoordinates.of("test-index-*").withTypes(TYPE_NAME)); - - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_2_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("message", "foo")).build(); @@ -536,21 +539,20 @@ public abstract class ElasticsearchTemplateTests { IndexQuery idxQuery1 = new IndexQueryBuilder().withId(randomNumeric(5)).withObject(sampleEntity).build(); operations.index(idxQuery1, IndexCoordinates.of(INDEX_1_NAME).withTypes("test-type")); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); IndexQuery idxQuery2 = new IndexQueryBuilder().withId(randomNumeric(5)).withObject(sampleEntity).build(); operations.index(idxQuery2, IndexCoordinates.of(INDEX_2_NAME).withTypes("test-type")); - indexOperations.refresh(IndexCoordinates.of(INDEX_2_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).refresh(); // when - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(termQuery("message", "negative")); + Query query = new NativeSearchQueryBuilder().withQuery(termQuery("message", "negative")).build(); - operations.delete(deleteQuery, IndexCoordinates.of("test-index-*").withTypes(TYPE_NAME)); + operations.delete(query, SampleEntity.class, IndexCoordinates.of("test-index-*").withTypes(TYPE_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_2_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("message", "positive")).build(); @@ -568,7 +570,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFilter(boolQuery().filter(termQuery("id", documentId))).build(); @@ -603,7 +605,7 @@ public abstract class ElasticsearchTemplateTests { indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2, sampleEntity3)); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withSort(new FieldSortBuilder("rate").order(SortOrder.ASC)).build(); @@ -639,7 +641,7 @@ public abstract class ElasticsearchTemplateTests { indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2, sampleEntity3)); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withSort(new FieldSortBuilder("rate").order(SortOrder.ASC)) @@ -678,7 +680,7 @@ public abstract class ElasticsearchTemplateTests { indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2, sampleEntity3)); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPageable(PageRequest.of(0, 10, Sort.by(Sort.Order.asc("message").nullsFirst()))).build(); @@ -716,7 +718,7 @@ public abstract class ElasticsearchTemplateTests { indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2, sampleEntity3)); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPageable(PageRequest.of(0, 10, Sort.by(Sort.Order.asc("message").nullsLast()))).build(); @@ -740,7 +742,7 @@ public abstract class ElasticsearchTemplateTests { SampleEntity.builder().id("3").message("blue").build()); operations.bulkIndex(getIndexQueries(entities), index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() // .withQuery(matchQuery("message", "green")) // @@ -767,7 +769,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); @@ -794,7 +796,7 @@ public abstract class ElasticsearchTemplateTests { indexQuery.setObject(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); Map params = new HashMap<>(); params.put("factor", 2); @@ -821,7 +823,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); StringQuery stringQuery = new StringQuery(matchAllQuery().toString(), PageRequest.of(0, 10)); @@ -847,7 +849,7 @@ public abstract class ElasticsearchTemplateTests { indexQuery.setObject(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); StringQuery stringQuery = new StringQuery(matchAllQuery().toString(), PageRequest.of(0, 10), Sort.by(Order.asc("message"))); @@ -870,7 +872,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); StringQuery stringQuery = new StringQuery(termQuery("id", documentId).toString()); @@ -887,7 +889,7 @@ public abstract class ElasticsearchTemplateTests { // when // creation is done in setup method - Map setting = indexOperations.getSettings(SampleEntity.class); + Map setting = indexOperations.getSettings(); // then assertThat(setting.get("index.number_of_shards")).isEqualTo("1"); @@ -905,7 +907,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("test")); // when @@ -926,12 +928,12 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("test")); // when operations.delete(criteriaQuery, SampleEntity.class, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); @@ -953,7 +955,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withFields("message") .build(); @@ -981,7 +983,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); FetchSourceFilterBuilder sourceFilter = new FetchSourceFilterBuilder(); sourceFilter.withIncludes("message"); @@ -1022,7 +1024,7 @@ public abstract class ElasticsearchTemplateTests { getIndexQuery( SampleEntity.builder().id(documentId2).message(sampleMessage).version(System.currentTimeMillis()).build()), index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); MoreLikeThisQuery moreLikeThisQuery = new MoreLikeThisQuery(); moreLikeThisQuery.setId(documentId2); @@ -1047,20 +1049,21 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.setPageable(PageRequest.of(0, 10)); - ScrolledPage> scroll = operations.searchScrollStart(1000, criteriaQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + criteriaQuery, SampleEntity.class, index); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); - scroll = operations.searchScrollContinue(scroll.getScrollId(), 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scroll.getScrollId(), 1000, + SampleEntity.class); } - operations.searchScrollClear(scroll.getScrollId()); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scroll.getScrollId()); assertThat(sampleEntities).hasSize(30); } @@ -1072,21 +1075,22 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPageable(PageRequest.of(0, 10)).build(); - ScrolledPage> scroll = operations.searchScrollStart(1000, searchQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + searchQuery, SampleEntity.class, index); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); - scroll = operations.searchScrollContinue(scroll.getScrollId(), 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scroll.getScrollId(), 1000, + SampleEntity.class); } - operations.searchScrollClear(scroll.getScrollId()); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scroll.getScrollId()); assertThat(sampleEntities).hasSize(30); } @@ -1098,23 +1102,23 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.addFields("message"); criteriaQuery.setPageable(PageRequest.of(0, 10)); - ScrolledPage> scroll = operations.searchScrollStart(1000, criteriaQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + criteriaQuery, SampleEntity.class, index); String scrollId = scroll.getScrollId(); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); scrollId = scroll.getScrollId(); - scroll = operations.searchScrollContinue(scrollId, 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scrollId, 1000, SampleEntity.class); } - operations.searchScrollClear(scrollId); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scrollId); assertThat(sampleEntities).hasSize(30); } @@ -1126,22 +1130,22 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withFields("message") .withQuery(matchAllQuery()).withPageable(PageRequest.of(0, 10)).build(); - ScrolledPage> scroll = operations.searchScrollStart(1000, searchQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + searchQuery, SampleEntity.class, index); String scrollId = scroll.getScrollId(); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); scrollId = scroll.getScrollId(); - scroll = operations.searchScrollContinue(scrollId, 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scrollId, 1000, SampleEntity.class); } - operations.searchScrollClear(scrollId); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scrollId); assertThat(sampleEntities).hasSize(30); } @@ -1153,22 +1157,22 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.setPageable(PageRequest.of(0, 10)); - ScrolledPage> scroll = operations.searchScrollStart(1000, criteriaQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + criteriaQuery, SampleEntity.class, index); String scrollId = scroll.getScrollId(); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); scrollId = scroll.getScrollId(); - scroll = operations.searchScrollContinue(scrollId, 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scrollId, 1000, SampleEntity.class); } - operations.searchScrollClear(scrollId); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scrollId); assertThat(sampleEntities).hasSize(30); } @@ -1180,22 +1184,22 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPageable(PageRequest.of(0, 10)).build(); - ScrolledPage> scroll = operations.searchScrollStart(1000, searchQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + searchQuery, SampleEntity.class, index); String scrollId = scroll.getScrollId(); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); scrollId = scroll.getScrollId(); - scroll = operations.searchScrollContinue(scrollId, 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scrollId, 1000, SampleEntity.class); } - operations.searchScrollClear(scrollId); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scrollId); assertThat(sampleEntities).hasSize(30); } @@ -1207,22 +1211,22 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.setPageable(PageRequest.of(0, 10)); - ScrolledPage> scroll = operations.searchScrollStart(1000, criteriaQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + criteriaQuery, SampleEntity.class, index); String scrollId = scroll.getScrollId(); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); scrollId = scroll.getScrollId(); - scroll = operations.searchScrollContinue(scrollId, 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scrollId, 1000, SampleEntity.class); } - operations.searchScrollClear(scrollId); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scrollId); assertThat(sampleEntities).hasSize(30); } @@ -1234,22 +1238,22 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPageable(PageRequest.of(0, 10)).build(); - ScrolledPage> scroll = operations.searchScrollStart(1000, searchQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + searchQuery, SampleEntity.class, index); String scrollId = scroll.getScrollId(); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); scrollId = scroll.getScrollId(); - scroll = operations.searchScrollContinue(scrollId, 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scrollId, 1000, SampleEntity.class); } - operations.searchScrollClear(scrollId); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scrollId); assertThat(sampleEntities).hasSize(30); } @@ -1261,7 +1265,7 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); @@ -1317,7 +1321,7 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery singleCriteriaQuery = new CriteriaQuery(new Criteria("message").contains("test")); CriteriaQuery multipleCriteriaQuery = new CriteriaQuery( @@ -1354,7 +1358,7 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); SearchHits sampleEntities = operations.search(stringQuery, SampleEntity.class, index); @@ -1367,14 +1371,14 @@ public abstract class ElasticsearchTemplateTests { public void shouldPutMappingForGivenEntity() { // given - Class entity = SampleEntity.class; - indexOperations.deleteIndex(entity); - indexOperations.createIndex(entity); + Class entityClass = SampleEntity.class; + operations.indexOps(entityClass).delete(); + operations.indexOps(entityClass).create(); // when // then - assertThat(indexOperations.putMapping(entity)).isTrue(); + assertThat(indexOperations.putMapping(indexOperations.createMapping(entityClass))).isTrue(); } @Test // DATAES-305 @@ -1382,14 +1386,15 @@ public abstract class ElasticsearchTemplateTests { // given Class entity = SampleEntity.class; - indexOperations.deleteIndex(INDEX_1_NAME); - indexOperations.createIndex(INDEX_1_NAME); + IndexOperations indexOperations1 = operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)); + indexOperations1.delete(); + indexOperations1.create(); // when - indexOperations.putMapping(IndexCoordinates.of(INDEX_1_NAME).withTypes(TYPE_NAME), entity); + indexOperations1.putMapping(indexOperations1.createMapping(entity)); // then - Map mapping = indexOperations.getMapping(IndexCoordinates.of(INDEX_1_NAME).withTypes(TYPE_NAME)); + Map mapping = indexOperations.getMapping(); assertThat(mapping.get("properties")).isNotNull(); } @@ -1400,10 +1405,10 @@ public abstract class ElasticsearchTemplateTests { Class clazz = SampleEntity.class; // when - indexOperations.deleteIndex(clazz); + indexOperations.delete(); // then - assertThat(indexOperations.indexExists(clazz)).isFalse(); + assertThat(indexOperations.exists()).isFalse(); } @Test @@ -1420,18 +1425,20 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); - IndexRequest indexRequest = new IndexRequest(); - indexRequest.source("message", messageAfterUpdate); - UpdateQuery updateQuery = new UpdateQueryBuilder().withId(documentId).withIndexRequest(indexRequest).build(); + org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document + .create(); + document.put("message", messageAfterUpdate); + UpdateQuery updateQuery = UpdateQuery.builder(documentId)// + .withDocument(document) // + .build(); // when operations.update(updateQuery, index); // then - GetQuery getQuery = new GetQuery(documentId); - SampleEntity indexedEntity = operations.get(getQuery, SampleEntity.class, index); + SampleEntity indexedEntity = operations.get(documentId, SampleEntity.class, index); assertThat(indexedEntity.getMessage()).isEqualTo(messageAfterUpdate); } @@ -1443,13 +1450,13 @@ public abstract class ElasticsearchTemplateTests { doc.put("id", "1"); doc.put("message", "test"); - UpdateRequest updateRequest = new UpdateRequest() // - .doc(doc) // - .upsert(doc); + org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document + .from(doc); - UpdateQuery updateQuery = new UpdateQueryBuilder() // - .withId("1") // - .withUpdateRequest(updateRequest).build(); + UpdateQuery updateQuery = UpdateQuery.builder("1") // + .withDocument(document) // + .withUpsert(document) // + .build(); // when UpdateRequest request = getRequestFactory().updateRequest(updateQuery, IndexCoordinates.of("index")); @@ -1466,11 +1473,13 @@ public abstract class ElasticsearchTemplateTests { doc.put("id", "1"); doc.put("message", "test"); - UpdateRequest updateRequest = new UpdateRequest().doc(doc).fetchSource(FetchSourceContext.FETCH_SOURCE); + org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document + .from(doc); - UpdateQuery updateQuery = new UpdateQueryBuilder() // - .withId("1") // - .withUpdateRequest(updateRequest).build(); + UpdateQuery updateQuery = UpdateQuery.builder("1") // + .withDocument(document) // + .withFetchSource(true) // + .build(); // when UpdateRequest request = getRequestFactory().updateRequest(updateQuery, IndexCoordinates.of("index")); @@ -1485,19 +1494,20 @@ public abstract class ElasticsearchTemplateTests { // given String documentId = randomNumeric(5); - String message = "test message"; - IndexRequest indexRequest = new IndexRequest(); - indexRequest.source("message", message); - UpdateQuery updateQuery = new UpdateQueryBuilder().withId(documentId).withDoUpsert(true) - .withIndexRequest(indexRequest).build(); + org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document + .create(); + document.put("message", "test message"); + UpdateQuery updateQuery = UpdateQuery.builder(documentId) // + .withDocument(document) // + .withDocAsUpsert(true) // + .build(); // when operations.update(updateQuery, index); // then - GetQuery getQuery = new GetQuery(documentId); - SampleEntity indexedEntity = operations.get(getQuery, SampleEntity.class, index); - assertThat(indexedEntity.getMessage()).isEqualTo(message); + SampleEntity indexedEntity = operations.get(documentId, SampleEntity.class, index); + assertThat(indexedEntity.getMessage()).isEqualTo("test message"); } @Test // DATAES-671 @@ -1513,19 +1523,20 @@ public abstract class ElasticsearchTemplateTests { IndexCoordinates index = IndexCoordinates.of(INDEX_1_NAME).withTypes("test-type"); operations.index(idxQuery, index); - indexOperations.refresh(index); + operations.indexOps(index).refresh(); // when NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withIndicesOptions(IndicesOptions.lenientExpandOpen()).build(); - ScrolledPage> scroll = operations.searchScrollStart(scrollTimeInMillis, searchQuery, - SampleEntity.class, index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations) + .searchScrollStart(scrollTimeInMillis, searchQuery, SampleEntity.class, index); List> entities = new ArrayList<>(scroll.getContent()); while (scroll.hasContent()) { - scroll = operations.searchScrollContinue(scroll.getScrollId(), scrollTimeInMillis, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scroll.getScrollId(), + scrollTimeInMillis, SampleEntity.class); entities.addAll(scroll.getContent()); } @@ -1546,7 +1557,7 @@ public abstract class ElasticsearchTemplateTests { indexQueries.add(buildIndex(SampleEntity.builder().id("3").message("ac").build())); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when List queries = new ArrayList<>(); @@ -1567,17 +1578,18 @@ public abstract class ElasticsearchTemplateTests { // given Class clazz = Book.class; - indexOperations.deleteIndex(clazz); - indexOperations.createIndex(clazz); - indexOperations.putMapping(clazz); - indexOperations.refresh(clazz); + IndexOperations bookIndexOperations = operations.indexOps(Book.class); + bookIndexOperations.delete(); + bookIndexOperations.create(); + indexOperations.putMapping(indexOperations.createMapping(clazz)); + bookIndexOperations.refresh(); IndexCoordinates bookIndex = IndexCoordinates.of("test-index-book-core-template").withTypes("book"); operations.index(buildIndex(SampleEntity.builder().id("1").message("ab").build()), index); operations.index(buildIndex(Book.builder().id("2").description("bc").build()), bookIndex); - indexOperations.refresh(SampleEntity.class); - indexOperations.refresh(clazz); + indexOperations.refresh(); + bookIndexOperations.refresh(); // when List queries = new ArrayList<>(); @@ -1609,13 +1621,12 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(termQuery("id", documentId)); - operations.delete(deleteQuery, index); - indexOperations.refresh(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)); + Query query = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); + operations.delete(query, SampleEntity.class, index); + operations.indexOps(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)).refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); @@ -1634,7 +1645,7 @@ public abstract class ElasticsearchTemplateTests { // when operations.index(indexQuery, IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME)); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", indexQuery.getId())) .build(); @@ -1664,7 +1675,7 @@ public abstract class ElasticsearchTemplateTests { List entities = createSampleEntitiesWithMessage("Test message", 30); // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("message", "message")) .withPageable(PageRequest.of(0, 100)).build(); // then @@ -1682,7 +1693,7 @@ public abstract class ElasticsearchTemplateTests { indexQueries.add(buildIndex(SampleEntity.builder().id("3").message("ac").build())); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() @@ -1707,7 +1718,7 @@ public abstract class ElasticsearchTemplateTests { indexQueries.add(buildIndex(SampleEntity.builder().id("3").message("ac xz hi").build())); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("message", "xz")) @@ -1738,8 +1749,7 @@ public abstract class ElasticsearchTemplateTests { // then assertThat(sampleEntity.getId()).isEqualTo(documentId); - GetQuery getQuery = new GetQuery(documentId); - SampleEntity result = operations.get(getQuery, SampleEntity.class, index); + SampleEntity result = operations.get(documentId, SampleEntity.class, index); assertThat(result.getId()).isEqualTo(documentId); } @@ -1768,7 +1778,7 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); @@ -1812,7 +1822,7 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(indexQueries, index); - indexOperations.refresh(index); + indexOperations.refresh(); // then NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); @@ -1835,7 +1845,7 @@ public abstract class ElasticsearchTemplateTests { .withObject(entity); operations.index(indexQueryBuilder.build(), index); - indexOperations.refresh(index); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); // when @@ -1846,7 +1856,7 @@ public abstract class ElasticsearchTemplateTests { // reindex with same version operations.index(indexQueryBuilder.build(), index); - indexOperations.refresh(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)); + operations.indexOps(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)).refresh(); // reindex with version one below assertThatThrownBy(() -> operations.index(indexQueryBuilder.withVersion(entity.getVersion() - 1).build(), index)) @@ -1864,7 +1874,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = new IndexQueryBuilder().withId(documentId).withObject(sampleEntity).build(); operations.index(indexQuery, IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)); + operations.indexOps(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)).refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); @@ -1886,7 +1896,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); // when @@ -1906,7 +1916,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); // when @@ -1926,7 +1936,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); // when @@ -1946,7 +1956,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); // when @@ -1975,8 +1985,8 @@ public abstract class ElasticsearchTemplateTests { operations.index(indexQuery1, IndexCoordinates.of(INDEX_1_NAME).withTypes("test-type")); operations.index(indexQuery2, IndexCoordinates.of(INDEX_2_NAME).withTypes("test-type")); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_2_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); @@ -2006,8 +2016,8 @@ public abstract class ElasticsearchTemplateTests { operations.index(indexQuery1, IndexCoordinates.of(INDEX_1_NAME).withTypes("test-type")); operations.index(indexQuery2, IndexCoordinates.of(INDEX_2_NAME).withTypes("test-type")); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_2_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); @@ -2019,24 +2029,26 @@ public abstract class ElasticsearchTemplateTests { } private void cleanUpIndices() { - indexOperations.deleteIndex(INDEX_1_NAME); - indexOperations.deleteIndex(INDEX_2_NAME); - indexOperations.createIndex(INDEX_1_NAME); - indexOperations.createIndex(INDEX_2_NAME); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME, INDEX_2_NAME)); + IndexOperations indexOperations1 = operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)); + indexOperations1.delete(); + IndexOperations indexOperations2 = operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)); + indexOperations2.delete(); + indexOperations1.create(); + indexOperations2.create(); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME, INDEX_2_NAME)).refresh(); } @Test // DATAES-71 public void shouldCreatedIndexWithSpecifiedIndexName() { // given - indexOperations.deleteIndex(INDEX_3_NAME); + operations.indexOps(IndexCoordinates.of(INDEX_3_NAME)).delete(); // when - indexOperations.createIndex(INDEX_3_NAME); + operations.indexOps(IndexCoordinates.of(INDEX_3_NAME)).create(); // then - assertThat(indexOperations.indexExists(INDEX_3_NAME)).isTrue(); + assertThat(operations.indexOps(IndexCoordinates.of(INDEX_3_NAME)).exists()).isTrue(); } @Test // DATAES-72 @@ -2044,14 +2056,15 @@ public abstract class ElasticsearchTemplateTests { // given String indexName = "some-random-index"; - indexOperations.createIndex(indexName); - indexOperations.refresh(IndexCoordinates.of(indexName)); + IndexCoordinates index = IndexCoordinates.of(indexName); + operations.indexOps(index).create(); + operations.indexOps(index).refresh(); // when - indexOperations.deleteIndex(indexName); + operations.indexOps(index).delete(); // then - assertThat(indexOperations.indexExists(indexName)).isFalse(); + assertThat(operations.indexOps(index).exists()).isFalse(); } @Test // DATAES-106 @@ -2073,8 +2086,8 @@ public abstract class ElasticsearchTemplateTests { operations.index(indexQuery1, IndexCoordinates.of(INDEX_1_NAME).withTypes("test-type")); operations.index(indexQuery2, IndexCoordinates.of(INDEX_2_NAME).withTypes("test-type")); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_2_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); @@ -2104,8 +2117,8 @@ public abstract class ElasticsearchTemplateTests { operations.index(indexQuery1, IndexCoordinates.of(INDEX_1_NAME).withTypes("test-type")); operations.index(indexQuery2, IndexCoordinates.of(INDEX_2_NAME).withTypes("test-type")); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_2_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); @@ -2126,7 +2139,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); // when @@ -2144,7 +2157,7 @@ public abstract class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); // when @@ -2163,14 +2176,15 @@ public abstract class ElasticsearchTemplateTests { + " \"tokenizer\": \"uax_url_email\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + '}'; - indexOperations.deleteIndex(INDEX_3_NAME); + IndexOperations indexOperations3 = operations.indexOps(IndexCoordinates.of(INDEX_3_NAME)); + indexOperations3.delete(); // when - indexOperations.createIndex(INDEX_3_NAME, settings); + operations.indexOps(IndexCoordinates.of(INDEX_3_NAME)).create(parse(settings)); // then - Map map = indexOperations.getSettings(INDEX_3_NAME); - assertThat(indexOperations.indexExists(INDEX_3_NAME)).isTrue(); + Map map = indexOperations3.getSettings(); + assertThat(indexOperations3.exists()).isTrue(); assertThat(map.containsKey("index.analysis.analyzer.emailAnalyzer.tokenizer")).isTrue(); assertThat(map.get("index.analysis.analyzer.emailAnalyzer.tokenizer")).isEqualTo("uax_url_email"); } @@ -2182,8 +2196,8 @@ public abstract class ElasticsearchTemplateTests { // delete , create and apply mapping in before method // then - Map map = indexOperations.getSettings(SampleEntity.class); - assertThat(indexOperations.indexExists(SampleEntity.class)).isTrue(); + Map map = indexOperations.getSettings(); + assertThat(indexOperations.exists()).isTrue(); assertThat(map.containsKey("index.refresh_interval")).isTrue(); assertThat(map.containsKey("index.number_of_replicas")).isTrue(); assertThat(map.containsKey("index.number_of_shards")).isTrue(); @@ -2206,14 +2220,14 @@ public abstract class ElasticsearchTemplateTests { + " }\n" + " }\n" + " }\n" + '}'; // when - indexOperations.deleteIndex(SampleEntity.class); - indexOperations.createIndex(SampleEntity.class, settings); - indexOperations.putMapping(SampleEntity.class); - indexOperations.refresh(SampleEntity.class); + indexOperations.delete(); + indexOperations.create(parse(settings)); + indexOperations.putMapping(indexOperations.createMapping(SampleEntity.class)); + indexOperations.refresh(); // then - Map map = indexOperations.getSettings(SampleEntity.class); - assertThat(indexOperations.indexExists(INDEX_NAME_SAMPLE_ENTITY)).isTrue(); + Map map = indexOperations.getSettings(); + assertThat(operations.indexOps(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)).exists()).isTrue(); assertThat(map.containsKey("index.number_of_replicas")).isTrue(); assertThat(map.containsKey("index.number_of_shards")).isTrue(); assertThat((String) map.get("index.number_of_replicas")).isEqualTo("0"); @@ -2238,8 +2252,8 @@ public abstract class ElasticsearchTemplateTests { operations.index(indexQuery1, IndexCoordinates.of(INDEX_1_NAME).withTypes("test-type")); operations.index(indexQuery2, IndexCoordinates.of(INDEX_2_NAME).withTypes("test-type")); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_2_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); @@ -2266,8 +2280,8 @@ public abstract class ElasticsearchTemplateTests { operations.index(indexQuery1, IndexCoordinates.of(INDEX_1_NAME).withTypes("hetro")); operations.index(indexQuery2, IndexCoordinates.of(INDEX_2_NAME).withTypes("hetro")); - indexOperations.refresh(IndexCoordinates.of(INDEX_1_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_2_NAME)); + operations.indexOps(IndexCoordinates.of(INDEX_1_NAME)).refresh(); + operations.indexOps(IndexCoordinates.of(INDEX_2_NAME)).refresh(); // when NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); @@ -2279,15 +2293,15 @@ public abstract class ElasticsearchTemplateTests { @Test public void shouldCreateIndexUsingServerDefaultConfiguration() { - // given + IndexOperations indexOps = operations.indexOps(UseServerConfigurationEntity.class); // when - boolean created = indexOperations.createIndex(UseServerConfigurationEntity.class); + boolean created = indexOps.create(); // then assertThat(created).isTrue(); - Map setting = indexOperations.getSettings(UseServerConfigurationEntity.class); + Map setting = indexOps.getSettings(); assertThat(setting.get("index.number_of_shards")).isEqualTo("1"); assertThat(setting.get("index.number_of_replicas")).isEqualTo("1"); } @@ -2298,7 +2312,7 @@ public abstract class ElasticsearchTemplateTests { // given // when - Map mapping = indexOperations.getMapping(SampleEntity.class); + Map mapping = indexOperations.getMapping(); // then assertThat(mapping).isNotNull(); @@ -2321,13 +2335,12 @@ public abstract class ElasticsearchTemplateTests { indexQueries.add(getIndexQuery(SampleEntity.builder().id(remainingDocumentId).message("some other message") .version(System.currentTimeMillis()).build())); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(idsQuery().addIds(documentIdToDelete)); - operations.delete(deleteQuery, index); - indexOperations.refresh(SampleEntity.class); + Query query = new NativeSearchQueryBuilder().withQuery(idsQuery().addIds(documentIdToDelete)).build(); + operations.delete(query, SampleEntity.class, index); + indexOperations.refresh(); // then // document with id "remainingDocumentId" should still be indexed @@ -2353,12 +2366,12 @@ public abstract class ElasticsearchTemplateTests { indexQueries.add(getIndexQuery(SampleEntity.builder().id(remainingDocumentId).message("some other message") .version(System.currentTimeMillis()).build())); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("id").is(documentIdToDelete)); operations.delete(criteriaQuery, SampleEntity.class, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then // document with id "remainingDocumentId" should still be indexed @@ -2383,11 +2396,11 @@ public abstract class ElasticsearchTemplateTests { indexQueries.add(getIndexQuery(SampleEntity.builder().id(remainingDocumentId).message("some other message") .version(System.currentTimeMillis()).build())); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when operations.delete(documentIdToDelete, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then // document with id "remainingDocumentId" should still be indexed @@ -2412,20 +2425,21 @@ public abstract class ElasticsearchTemplateTests { .version(System.currentTimeMillis()).build())); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("message")); criteriaQuery.setPageable(PageRequest.of(0, 10)); - ScrolledPage> scroll = operations.searchScrollStart(1000, criteriaQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + criteriaQuery, SampleEntity.class, index); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); - scroll = operations.searchScrollContinue(scroll.getScrollId(), 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scroll.getScrollId(), 1000, + SampleEntity.class); } - operations.searchScrollClear(scroll.getScrollId()); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scroll.getScrollId()); // then assertThat(sampleEntities).hasSize(2); @@ -2449,20 +2463,21 @@ public abstract class ElasticsearchTemplateTests { .version(System.currentTimeMillis()).build())); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("message", "message")) .withPageable(PageRequest.of(0, 10)).build(); - ScrolledPage> scroll = operations.searchScrollStart(1000, searchQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + searchQuery, SampleEntity.class, index); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); - scroll = operations.searchScrollContinue(scroll.getScrollId(), 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scroll.getScrollId(), 1000, + SampleEntity.class); } - operations.searchScrollClear(scroll.getScrollId()); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scroll.getScrollId()); // then assertThat(sampleEntities).hasSize(2); @@ -2479,7 +2494,7 @@ public abstract class ElasticsearchTemplateTests { // when operations.bulkIndex(entities, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // then SourceFilter sourceFilter = new FetchSourceFilter(new String[] { "id" }, new String[] {}); @@ -2487,14 +2502,15 @@ public abstract class ElasticsearchTemplateTests { NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPageable(PageRequest.of(0, 10)).withSourceFilter(sourceFilter).build(); - ScrolledPage> scroll = operations.searchScrollStart(1000, searchQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + searchQuery, SampleEntity.class, index); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); - scroll = operations.searchScrollContinue(scroll.getScrollId(), 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scroll.getScrollId(), 1000, + SampleEntity.class); } - operations.searchScrollClear(scroll.getScrollId()); + ((AbstractElasticsearchTemplate) operations).searchScrollClear(scroll.getScrollId()); assertThat(sampleEntities).hasSize(3); assertThat(sampleEntities.stream().map(SearchHit::getContent).map(SampleEntity::getId).collect(Collectors.toList())) .doesNotContain((String) null); @@ -2526,19 +2542,20 @@ public abstract class ElasticsearchTemplateTests { indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2, sampleEntity3)); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withSort(new FieldSortBuilder("rate").order(SortOrder.ASC)) .withSort(new FieldSortBuilder("message").order(SortOrder.DESC)).withPageable(PageRequest.of(0, 10)).build(); // when - ScrolledPage> scroll = operations.searchScrollStart(1000, searchQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + searchQuery, SampleEntity.class, index); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); - scroll = operations.searchScrollContinue(scroll.getScrollId(), 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scroll.getScrollId(), 1000, + SampleEntity.class); } // then @@ -2573,7 +2590,7 @@ public abstract class ElasticsearchTemplateTests { indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2, sampleEntity3)); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPageable( @@ -2581,12 +2598,13 @@ public abstract class ElasticsearchTemplateTests { .build(); // when - ScrolledPage> scroll = operations.searchScrollStart(1000, searchQuery, SampleEntity.class, - index); + ScrolledPage> scroll = ((AbstractElasticsearchTemplate) operations).searchScrollStart(1000, + searchQuery, SampleEntity.class, index); List> sampleEntities = new ArrayList<>(); while (scroll.hasContent()) { sampleEntities.addAll(scroll.getContent()); - scroll = operations.searchScrollContinue(scroll.getScrollId(), 1000, SampleEntity.class); + scroll = ((AbstractElasticsearchTemplate) operations).searchScrollContinue(scroll.getScrollId(), 1000, + SampleEntity.class); } // then @@ -2612,7 +2630,7 @@ public abstract class ElasticsearchTemplateTests { List indexQueries = getIndexQueries(Arrays.asList(sampleEntity, sampleEntity2, sampleEntity3)); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withCollapseField("rate") .build(); @@ -2651,10 +2669,10 @@ public abstract class ElasticsearchTemplateTests { .build(); // when - indexOperations.addAlias(aliasQuery, IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)); + indexOperations.addAlias(aliasQuery); // then - List aliases = indexOperations.queryForAlias(INDEX_NAME_SAMPLE_ENTITY); + List aliases = indexOperations.queryForAlias(); assertThat(aliases).isNotNull(); assertThat(aliases.get(0).alias()).isEqualTo(aliasName); } @@ -2678,8 +2696,8 @@ public abstract class ElasticsearchTemplateTests { // when IndexCoordinates index = IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY); - indexOperations.addAlias(aliasQuery1, index); - indexOperations.addAlias(aliasQuery2, index); + indexOperations.addAlias(aliasQuery1); + indexOperations.addAlias(aliasQuery2); String documentId = randomNumeric(5); SampleEntity entity = SampleEntity.builder() // @@ -2696,7 +2714,7 @@ public abstract class ElasticsearchTemplateTests { operations.index(indexQuery, IndexCoordinates.of(alias1).withTypes(TYPE_NAME)); // then - List aliasMetaData = indexOperations.queryForAlias(INDEX_NAME_SAMPLE_ENTITY); + List aliasMetaData = indexOperations.queryForAlias(); assertThat(aliasMetaData).isNotEmpty(); AliasMetaData aliasMetaData1 = aliasMetaData.get(0); @@ -2710,8 +2728,8 @@ public abstract class ElasticsearchTemplateTests { assertThat(aliasMetaData2.searchRouting()).isEqualTo("1"); // cleanup - indexOperations.removeAlias(aliasQuery1, index); - indexOperations.removeAlias(aliasQuery2, index); + indexOperations.removeAlias(aliasQuery1); + indexOperations.removeAlias(aliasQuery2); } @Test // DATAES-70 @@ -2727,7 +2745,7 @@ public abstract class ElasticsearchTemplateTests { .build(); // when - indexOperations.addAlias(aliasQuery, index); + indexOperations.addAlias(aliasQuery); String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder() // @@ -2742,7 +2760,7 @@ public abstract class ElasticsearchTemplateTests { .build(); operations.index(indexQuery, IndexCoordinates.of(alias).withTypes(TYPE_NAME)); - indexOperations.refresh(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)); + operations.indexOps(IndexCoordinates.of(INDEX_NAME_SAMPLE_ENTITY)).refresh(); NativeSearchQuery query = new NativeSearchQueryBuilder() // .withQuery(matchAllQuery()) // @@ -2751,7 +2769,7 @@ public abstract class ElasticsearchTemplateTests { long count = operations.count(query, IndexCoordinates.of(alias)); // then - List aliases = indexOperations.queryForAlias(INDEX_NAME_SAMPLE_ENTITY); + List aliases = indexOperations.queryForAlias(); assertThat(aliases).isNotNull(); AliasMetaData aliasMetaData = aliases.get(0); assertThat(aliasMetaData.alias()).isEqualTo(alias); @@ -2760,7 +2778,7 @@ public abstract class ElasticsearchTemplateTests { assertThat(count).isEqualTo(1); // cleanup - indexOperations.removeAlias(aliasQuery, index); + indexOperations.removeAlias(aliasQuery); } @Test // DATAES-541 @@ -2775,14 +2793,14 @@ public abstract class ElasticsearchTemplateTests { .build(); // when - indexOperations.addAlias(aliasQuery, index); - List aliases = indexOperations.queryForAlias(INDEX_NAME_SAMPLE_ENTITY); + indexOperations.addAlias(aliasQuery); + List aliases = indexOperations.queryForAlias(); assertThat(aliases).isNotNull(); assertThat(aliases.get(0).alias()).isEqualTo(aliasName); // then - indexOperations.removeAlias(aliasQuery, index); - aliases = indexOperations.queryForAlias(INDEX_NAME_SAMPLE_ENTITY); + indexOperations.removeAlias(aliasQuery); + aliases = indexOperations.queryForAlias(); assertThat(aliases).isEmpty(); } @@ -2827,7 +2845,7 @@ public abstract class ElasticsearchTemplateTests { // given // when - Map map = indexOperations.getSettings(SampleEntity.class); + Map map = indexOperations.getSettings(); // then assertThat(map).doesNotContainKey("index.max_result_window"); @@ -2838,7 +2856,7 @@ public abstract class ElasticsearchTemplateTests { // given // when - Map map = indexOperations.getSettings(SampleEntity.class, true); + Map map = indexOperations.getSettings(true); // then assertThat(map).containsKey("index.max_result_window"); @@ -2850,7 +2868,7 @@ public abstract class ElasticsearchTemplateTests { SearchHitsEntity entity = SearchHitsEntity.builder().id("1").number(1000L).keyword("thousands").build(); IndexQuery indexQuery = new IndexQueryBuilder().withId(entity.getId()).withObject(entity).build(); operations.index(indexQuery, index); - indexOperations.refresh(index); + operations.indexOps(index).refresh(); NativeSearchQuery query = new NativeSearchQueryBuilder() // .withQuery(matchAllQuery()) // @@ -2888,7 +2906,7 @@ public abstract class ElasticsearchTemplateTests { .build(); IndexQuery indexQuery = new IndexQueryBuilder().withId(entity.getId()).withObject(entity).build(); operations.index(indexQuery, index); - indexOperations.refresh(index); + operations.indexOps(index).refresh(); NativeSearchQuery query = new NativeSearchQueryBuilder() // .withQuery(termQuery("message", "message")) // @@ -2916,9 +2934,9 @@ public abstract class ElasticsearchTemplateTests { entity.setMessage("message"); operations.save(entity, index); - indexOperations.refresh(index); + indexOperations.refresh(); - SampleEntity result = operations.get(new GetQuery(id), SampleEntity.class, index); + SampleEntity result = operations.get(id, SampleEntity.class, index); assertThat(result).isEqualTo(entity); } @@ -2932,9 +2950,9 @@ public abstract class ElasticsearchTemplateTests { entity.setMessage("message"); operations.save(entity); - indexOperations.refresh(index); + indexOperations.refresh(); - SampleEntity result = operations.get(new GetQuery(id), SampleEntity.class, index); + SampleEntity result = operations.get(id, SampleEntity.class, index); assertThat(result).isEqualTo(entity); } @@ -2953,10 +2971,10 @@ public abstract class ElasticsearchTemplateTests { entity2.setMessage("message"); operations.save(Arrays.asList(entity1, entity2), index); - indexOperations.refresh(index); + indexOperations.refresh(); - SampleEntity result1 = operations.get(new GetQuery(id1), SampleEntity.class, index); - SampleEntity result2 = operations.get(new GetQuery(id2), SampleEntity.class, index); + SampleEntity result1 = operations.get(id1, SampleEntity.class, index); + SampleEntity result2 = operations.get(id2, SampleEntity.class, index); assertThat(result1).isEqualTo(entity1); assertThat(result2).isEqualTo(entity2); @@ -2976,15 +2994,43 @@ public abstract class ElasticsearchTemplateTests { entity2.setMessage("message"); operations.save(Arrays.asList(entity1, entity2)); - indexOperations.refresh(index); + indexOperations.refresh(); - SampleEntity result1 = operations.get(new GetQuery(id1), SampleEntity.class, index); - SampleEntity result2 = operations.get(new GetQuery(id2), SampleEntity.class, index); + SampleEntity result1 = operations.get(id1, SampleEntity.class, index); + SampleEntity result2 = operations.get(id2, SampleEntity.class, index); assertThat(result1).isEqualTo(entity1); assertThat(result2).isEqualTo(entity2); } + @Test // DATAES-745 + void shouldDoExistsWithEntity() { + String id = "42"; + SampleEntity entity = new SampleEntity(); + entity.setId(id); + entity.setVersion(42L); + entity.setMessage("message"); + + operations.save(entity); + indexOperations.refresh(); + + assertThat(operations.exists("42", SampleEntity.class)).isTrue(); + } + + @Test // DATAES-745 + void shouldDoExistsWithIndexCoordinates() { + String id = "42"; + SampleEntity entity = new SampleEntity(); + entity.setId(id); + entity.setVersion(42L); + entity.setMessage("message"); + + operations.save(entity); + indexOperations.refresh(); + + assertThat(operations.exists("42", index)).isTrue(); + } + protected RequestFactory getRequestFactory() { return ((AbstractElasticsearchTemplate) operations).getRequestFactory(); } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTransportTemplateTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTransportTemplateTests.java index 02c3c55ba..5c2e2469f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTransportTemplateTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTransportTemplateTests.java @@ -21,10 +21,8 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*; import lombok.Data; -import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.client.Client; -import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.engine.DocumentMissingException; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -38,7 +36,6 @@ 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.core.query.UpdateQueryBuilder; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.test.context.ContextConfiguration; @@ -56,9 +53,9 @@ public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTe @Test public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() { // when - IndexRequest indexRequest = new IndexRequest(); - indexRequest.source("{}", XContentType.JSON); - UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)).withIndexRequest(indexRequest).build(); + org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document + .create(); + UpdateQuery updateQuery = UpdateQuery.builder(randomNumeric(5)).withDocument(document).build(); assertThatThrownBy(() -> operations.update(updateQuery, index)).isInstanceOf(DocumentMissingException.class); } @@ -87,8 +84,7 @@ public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTe } @Data - @Document(indexName = "test-index-sample-core-transport-template", replicas = 0, - refreshInterval = "-1") + @Document(indexName = "test-index-sample-core-transport-template", replicas = 0, refreshInterval = "-1") static class SampleEntity { @Id private String id; diff --git a/src/test/java/org/springframework/data/elasticsearch/core/LogEntityTests.java b/src/test/java/org/springframework/data/elasticsearch/core/LogEntityTests.java index 0b450777c..1b816daeb 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/LogEntityTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/LogEntityTests.java @@ -62,11 +62,12 @@ public class LogEntityTests { private final IndexCoordinates index = IndexCoordinates.of("test-index-log-core").withTypes("test-log-type"); @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @BeforeEach public void before() throws ParseException { - IndexInitializer.init(indexOperations, LogEntity.class); + indexOperations = operations.indexOps(LogEntity.class); + IndexInitializer.init(indexOperations); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); IndexQuery indexQuery1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse("2013-10-18 18:01")) @@ -82,12 +83,12 @@ public class LogEntityTests { .code(2).ip("10.10.10.4").buildIndex(); operations.bulkIndex(Arrays.asList(indexQuery1, indexQuery2, indexQuery3, indexQuery4), index); - indexOperations.refresh(LogEntity.class); + indexOperations.refresh(); } @AfterEach void after() { - indexOperations.deleteIndex(LogEntity.class); + indexOperations.delete(); } @Test // DATAES-66 diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateTests.java index f560315c6..6312888d5 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateTests.java @@ -40,7 +40,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import org.elasticsearch.ElasticsearchStatusException; -import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortOrder; import org.junit.jupiter.api.AfterEach; @@ -66,7 +65,6 @@ import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.StringQuery; import org.springframework.data.elasticsearch.core.query.UpdateQuery; -import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder; import org.springframework.data.elasticsearch.junit.junit4.ElasticsearchVersion; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.util.StringUtils; @@ -89,16 +87,18 @@ public class ReactiveElasticsearchTemplateTests { private ElasticsearchRestTemplate restTemplate; private ReactiveElasticsearchTemplate template; + private IndexOperations indexOperations; @BeforeEach public void setUp() { + restTemplate = new ElasticsearchRestTemplate(TestUtils.restHighLevelClient()); + indexOperations = restTemplate.indexOps(SampleEntity.class); deleteIndices(); - restTemplate = new ElasticsearchRestTemplate(TestUtils.restHighLevelClient()); - restTemplate.createIndex(SampleEntity.class); - restTemplate.putMapping(SampleEntity.class); - restTemplate.refresh(SampleEntity.class); + indexOperations.create(); + indexOperations.putMapping(indexOperations.createMapping(SampleEntity.class)); + indexOperations.refresh(); template = new ReactiveElasticsearchTemplate(TestUtils.reactiveClient(), restTemplate.getElasticsearchConverter()); } @@ -142,7 +142,7 @@ public class ReactiveElasticsearchTemplateTests { .expectNextCount(1)// .verifyComplete(); - restTemplate.refresh(SampleEntity.class); + indexOperations.refresh(); SearchHits result = restTemplate.search( new CriteriaQuery(Criteria.where("message").is(sampleEntity.getMessage())), SampleEntity.class, @@ -161,7 +161,7 @@ public class ReactiveElasticsearchTemplateTests { assertThat(it.getId()).isNotNull(); - restTemplate.refresh(SampleEntity.class); + indexOperations.refresh(); assertThat(TestUtils.documentWithId(it.getId()).existsIn(DEFAULT_INDEX)).isTrue(); }) // .verifyComplete(); @@ -205,27 +205,27 @@ public class ReactiveElasticsearchTemplateTests { } @Test // DATAES-519 - public void findByIdShouldCompleteWhenIndexDoesNotExist() { + public void getByIdShouldCompleteWhenIndexDoesNotExist() { - template.findById("foo", SampleEntity.class, IndexCoordinates.of("no-such-index").withTypes("test-type")) // + template.get("foo", SampleEntity.class, IndexCoordinates.of("no-such-index").withTypes("test-type")) // .as(StepVerifier::create) // .verifyComplete(); } @Test // DATAES-504 - public void findByIdShouldReturnEntity() { + public void getByIdShouldReturnEntity() { SampleEntity sampleEntity = randomEntity("some message"); index(sampleEntity); - template.findById(sampleEntity.getId(), SampleEntity.class) // + template.get(sampleEntity.getId(), SampleEntity.class) // .as(StepVerifier::create) // .expectNext(sampleEntity) // .verifyComplete(); } @Test // DATAES-504 - public void findByIdWhenIdIsAutogeneratedShouldHaveIdSetCorrectly() { + public void getByIdWhenIdIsAutogeneratedShouldHaveIdSetCorrectly() { SampleEntity sampleEntity = new SampleEntity(); sampleEntity.setMessage("some message"); @@ -234,32 +234,32 @@ public class ReactiveElasticsearchTemplateTests { assertThat(sampleEntity.getId()).isNotNull(); - template.findById(sampleEntity.getId(), SampleEntity.class) // + template.get(sampleEntity.getId(), SampleEntity.class) // .as(StepVerifier::create) // .consumeNextWith(it -> assertThat(it.getId()).isEqualTo(sampleEntity.getId())) // .verifyComplete(); } @Test // DATAES-504 - public void findByIdShouldCompleteWhenNotingFound() { + public void getByIdShouldCompleteWhenNotingFound() { SampleEntity sampleEntity = randomEntity("some message"); index(sampleEntity); - template.findById("foo", SampleEntity.class) // + template.get("foo", SampleEntity.class) // .as(StepVerifier::create) // .verifyComplete(); } @Test // DATAES-504 - public void findByIdShouldErrorForNullId() { + public void getByIdShouldErrorForNullId() { assertThatThrownBy(() -> { - template.findById(null, SampleEntity.class); + template.get(null, SampleEntity.class); }).isInstanceOf(IllegalArgumentException.class); } @Test // DATAES-504 - public void findByIdWithExplicitIndexNameShouldOverwriteMetadata() { + public void getByIdWithExplicitIndexNameShouldOverwriteMetadata() { SampleEntity sampleEntity = randomEntity("some message"); @@ -269,16 +269,16 @@ public class ReactiveElasticsearchTemplateTests { IndexCoordinates alternateIndex = IndexCoordinates.of(ALTERNATE_INDEX).withTypes("test-type"); restTemplate.index(indexQuery, alternateIndex); - restTemplate.refresh(SampleEntity.class); + indexOperations.refresh(); - restTemplate.refresh(defaultIndex); - restTemplate.refresh(alternateIndex); + restTemplate.indexOps(defaultIndex).refresh(); + restTemplate.indexOps(alternateIndex).refresh(); - template.findById(sampleEntity.getId(), SampleEntity.class, defaultIndex) // + template.get(sampleEntity.getId(), SampleEntity.class, defaultIndex) // .as(StepVerifier::create) // .verifyComplete(); - template.findById(sampleEntity.getId(), SampleEntity.class, alternateIndex) // + template.get(sampleEntity.getId(), SampleEntity.class, alternateIndex) // .as(StepVerifier::create)// .expectNextCount(1) // .verifyComplete(); @@ -520,20 +520,20 @@ public class ReactiveElasticsearchTemplateTests { } @Test // DATAES-519 - public void deleteByIdShouldCompleteWhenIndexDoesNotExist() { + public void deleteShouldCompleteWhenIndexDoesNotExist() { - template.deleteById("does-not-exists", SampleEntity.class, IndexCoordinates.of("no-such-index")) // + template.delete("does-not-exists", IndexCoordinates.of("no-such-index")) // .as(StepVerifier::create)// .verifyComplete(); } @Test // DATAES-504 - public void deleteByIdShouldRemoveExistingDocumentById() { + public void deleteShouldRemoveExistingDocumentById() { SampleEntity sampleEntity = randomEntity("test message"); index(sampleEntity); - template.deleteById(sampleEntity.getId(), SampleEntity.class) // + template.delete(sampleEntity.getId(), SampleEntity.class) // .as(StepVerifier::create)// .expectNext(sampleEntity.getId()) // .verifyComplete(); @@ -545,7 +545,7 @@ public class ReactiveElasticsearchTemplateTests { SampleEntity sampleEntity = randomEntity("test message"); index(sampleEntity); - template.deleteById(sampleEntity.getId(), IndexCoordinates.of(DEFAULT_INDEX).withTypes("test-type")) // + template.delete(sampleEntity.getId(), IndexCoordinates.of(DEFAULT_INDEX).withTypes("test-type")) // .as(StepVerifier::create)// .expectNext(sampleEntity.getId()) // .verifyComplete(); @@ -564,7 +564,7 @@ public class ReactiveElasticsearchTemplateTests { } @Test // DATAES-504 - public void deleteByIdShouldCompleteWhenNothingDeleted() { + public void deleteShouldCompleteWhenNothingDeleted() { SampleEntity sampleEntity = randomEntity("test message"); @@ -579,7 +579,7 @@ public class ReactiveElasticsearchTemplateTests { CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("test")); - template.deleteBy(query, SampleEntity.class) // + template.delete(query, SampleEntity.class) // .as(StepVerifier::create) // .expectNext(0L) // .verifyComplete(); @@ -606,7 +606,7 @@ public class ReactiveElasticsearchTemplateTests { .withQuery(termQuery("message", "test")) // .build(); - template.deleteBy(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) // + template.delete(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) // .as(StepVerifier::create) // .expectNext(2L) // .verifyComplete(); @@ -635,7 +635,7 @@ public class ReactiveElasticsearchTemplateTests { .withQuery(termQuery("message", "negative")) // .build(); - template.deleteBy(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) // + template.delete(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) // .as(StepVerifier::create) // .expectNext(0L) // .verifyComplete(); @@ -651,7 +651,7 @@ public class ReactiveElasticsearchTemplateTests { CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("test")); - template.deleteBy(query, SampleEntity.class) // + template.delete(query, SampleEntity.class) // .as(StepVerifier::create) // .expectNext(2L) // .verifyComplete(); @@ -665,7 +665,7 @@ public class ReactiveElasticsearchTemplateTests { CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("luke")); - template.deleteBy(query, SampleEntity.class) // + template.delete(query, SampleEntity.class) // .as(StepVerifier::create) // .expectNext(0L) // .verifyComplete(); @@ -763,17 +763,19 @@ public class ReactiveElasticsearchTemplateTests { entity2.rate = 2; index(entity2); - IndexRequest indexRequest1 = new IndexRequest(); - indexRequest1.source("message", "updated 1"); - UpdateQuery updateQuery1 = new UpdateQueryBuilder() // - .withId(entity1.getId()) // - .withIndexRequest(indexRequest1).build(); + org.springframework.data.elasticsearch.core.document.Document document1 = org.springframework.data.elasticsearch.core.document.Document + .create(); + document1.put("message", "updated 1"); + UpdateQuery updateQuery1 = UpdateQuery.builder(entity1.getId()) // + .withDocument(document1) // + .build(); - IndexRequest indexRequest2 = new IndexRequest(); - indexRequest2.source("message", "updated 2"); - UpdateQuery updateQuery2 = new UpdateQueryBuilder() // - .withId(entity2.getId()) // - .withIndexRequest(indexRequest2).build(); + org.springframework.data.elasticsearch.core.document.Document document2 = org.springframework.data.elasticsearch.core.document.Document + .create(); + document2.put("message", "updated 2"); + UpdateQuery updateQuery2 = UpdateQuery.builder(entity2.getId()) // + .withDocument(document2) // + .build(); List queries = Arrays.asList(updateQuery1, updateQuery2); template.bulkUpdate(queries, IndexCoordinates.of(DEFAULT_INDEX)).block(); @@ -858,7 +860,7 @@ public class ReactiveElasticsearchTemplateTests { restTemplate.bulkIndex(getIndexQueries(entities), indexCoordinates); } - restTemplate.refresh(SampleEntity.class); + indexOperations.refresh(); } @Data diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateUnitTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateUnitTests.java index 7e0b30e3a..a1a412790 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateUnitTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateUnitTests.java @@ -170,7 +170,7 @@ public class ReactiveElasticsearchTemplateUnitTests { ArgumentCaptor captor = ArgumentCaptor.forClass(DeleteRequest.class); when(client.delete(captor.capture())).thenReturn(Mono.empty()); - template.deleteById("id", index) // + template.delete("id", index) // .as(StepVerifier::create) // .verifyComplete(); @@ -185,7 +185,7 @@ public class ReactiveElasticsearchTemplateUnitTests { template.setRefreshPolicy(RefreshPolicy.WAIT_UNTIL); - template.deleteById("id", index) // + template.delete("id", index) // .as(StepVerifier::create) // .verifyComplete(); @@ -198,7 +198,7 @@ public class ReactiveElasticsearchTemplateUnitTests { ArgumentCaptor captor = ArgumentCaptor.forClass(DeleteByQueryRequest.class); when(client.deleteBy(captor.capture())).thenReturn(Mono.empty()); - template.deleteBy(new StringQuery(QueryBuilders.matchAllQuery().toString()), Object.class, index) // + template.delete(new StringQuery(QueryBuilders.matchAllQuery().toString()), Object.class, index) // .as(StepVerifier::create) // .verifyComplete(); @@ -213,7 +213,7 @@ public class ReactiveElasticsearchTemplateUnitTests { template.setRefreshPolicy(RefreshPolicy.NONE); - template.deleteBy(new StringQuery(QueryBuilders.matchAllQuery().toString()), Object.class, index) // + template.delete(new StringQuery(QueryBuilders.matchAllQuery().toString()), Object.class, index) // .as(StepVerifier::create) // .verifyComplete(); @@ -226,7 +226,7 @@ public class ReactiveElasticsearchTemplateUnitTests { ArgumentCaptor captor = ArgumentCaptor.forClass(DeleteByQueryRequest.class); when(client.deleteBy(captor.capture())).thenReturn(Mono.empty()); - template.deleteBy(new StringQuery(QueryBuilders.matchAllQuery().toString()), Object.class, index) // + template.delete(new StringQuery(QueryBuilders.matchAllQuery().toString()), Object.class, index) // .as(StepVerifier::create) // .verifyComplete(); @@ -241,7 +241,7 @@ public class ReactiveElasticsearchTemplateUnitTests { template.setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN); - template.deleteBy(new StringQuery(QueryBuilders.matchAllQuery().toString()), Object.class, index) // + template.delete(new StringQuery(QueryBuilders.matchAllQuery().toString()), Object.class, index) // .as(StepVerifier::create) // .verifyComplete(); diff --git a/src/test/java/org/springframework/data/elasticsearch/core/aggregation/ElasticsearchTemplateAggregationTests.java b/src/test/java/org/springframework/data/elasticsearch/core/aggregation/ElasticsearchTemplateAggregationTests.java index a606f2027..911fb6e12 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/aggregation/ElasticsearchTemplateAggregationTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/aggregation/ElasticsearchTemplateAggregationTests.java @@ -77,11 +77,12 @@ public class ElasticsearchTemplateAggregationTests { static final String INDEX_NAME = "test-index-articles-core-aggregation"; @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, ArticleEntity.class); + indexOperations = operations.indexOps(ArticleEntity.class); + IndexInitializer.init(indexOperations); IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").subject("computing") .addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10) @@ -101,12 +102,12 @@ public class ElasticsearchTemplateAggregationTests { operations.index(article2, index); operations.index(article3, index); operations.index(article4, index); - operations.refresh(ArticleEntity.class); + indexOperations.refresh(); } @AfterEach public void after() { - indexOperations.deleteIndex(ArticleEntity.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionTests.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionTests.java index 0cb33dfc2..2acfb331a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionTests.java @@ -37,7 +37,6 @@ import org.springframework.data.elasticsearch.annotations.CompletionField; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.core.AbstractElasticsearchTemplate; 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.core.query.IndexQuery; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; @@ -63,18 +62,17 @@ public class ElasticsearchTemplateCompletionTests { static class Config {} @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; @BeforeEach private void setup() { - IndexInitializer.init(indexOperations, CompletionEntity.class); - IndexInitializer.init(indexOperations, AnnotatedCompletionEntity.class); + IndexInitializer.init(operations.indexOps(CompletionEntity.class)); + IndexInitializer.init(operations.indexOps(AnnotatedCompletionEntity.class)); } @AfterEach void after() { - indexOperations.deleteIndex("test-index-annotated-completion"); - indexOperations.deleteIndex("test-index-core-completion"); + operations.indexOps(CompletionEntity.class).delete(); + operations.indexOps(AnnotatedCompletionEntity.class).delete(); } private void loadCompletionObjectEntities() { @@ -90,7 +88,7 @@ public class ElasticsearchTemplateCompletionTests { .buildIndex()); operations.bulkIndex(indexQueries, IndexCoordinates.of("test-index-core-completion").withTypes("completion-type")); - operations.refresh(CompletionEntity.class); + operations.indexOps(CompletionEntity.class).refresh(); } private void loadAnnotatedCompletionObjectEntities() { @@ -111,7 +109,7 @@ public class ElasticsearchTemplateCompletionTests { operations.bulkIndex(indexQueries, IndexCoordinates.of("test-index-annotated-completion").withTypes("annotated-completion-type")); - operations.refresh(AnnotatedCompletionEntity.class); + operations.indexOps(AnnotatedCompletionEntity.class).refresh(); } private void loadAnnotatedCompletionObjectEntitiesWithWeights() { @@ -128,7 +126,7 @@ public class ElasticsearchTemplateCompletionTests { operations.bulkIndex(indexQueries, IndexCoordinates.of("test-index-annotated-completion").withTypes("annotated-completion-type")); - operations.refresh(AnnotatedCompletionEntity.class); + operations.indexOps(AnnotatedCompletionEntity.class).refresh(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionWithContextsTests.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionWithContextsTests.java index da770d38d..77bdc2d9b 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionWithContextsTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionWithContextsTests.java @@ -67,21 +67,22 @@ public class ElasticsearchTemplateCompletionWithContextsTests { static class Config {} @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @BeforeEach void setup() { - indexOperations.deleteIndex(ContextCompletionEntity.class); + indexOperations = operations.indexOps(ContextCompletionEntity.class); + indexOperations.delete(); } @AfterEach void after() { - indexOperations.deleteIndex(ContextCompletionEntity.class); + indexOperations.delete(); } private void loadContextCompletionObjectEntities() { - IndexInitializer.init(indexOperations, ContextCompletionEntity.class); + IndexInitializer.init(indexOperations); NonDocumentEntity nonDocumentEntity = new NonDocumentEntity(); nonDocumentEntity.setSomeField1("foo"); @@ -111,7 +112,7 @@ public class ElasticsearchTemplateCompletionWithContextsTests { operations.bulkIndex(indexQueries, IndexCoordinates.of("test-index-context-completion").withTypes("context-completion-type")); - operations.refresh(ContextCompletionEntity.class); + operations.indexOps(ContextCompletionEntity.class).refresh(); } @Test // DATAES-536 diff --git a/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java b/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java index 573c356d6..0d5bf827a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java @@ -39,7 +39,6 @@ import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.GeoPointField; 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; @@ -78,18 +77,17 @@ public class ElasticsearchTemplateGeoTests { .withTypes("geo-class-point-type"); @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, AuthorMarkerEntity.class); - IndexInitializer.init(indexOperations, LocationMarkerEntity.class); + IndexInitializer.init(operations.indexOps(AuthorMarkerEntity.class)); + IndexInitializer.init(operations.indexOps(LocationMarkerEntity.class)); } @AfterEach void after() { - indexOperations.deleteIndex(AuthorMarkerEntity.class); - indexOperations.deleteIndex(LocationMarkerEntity.class); + operations.indexOps(AuthorMarkerEntity.class).delete(); + operations.indexOps(LocationMarkerEntity.class).delete(); } private void loadClassBaseEntities() { @@ -100,7 +98,7 @@ public class ElasticsearchTemplateGeoTests { indexQueries.add(new AuthorMarkerEntityBuilder("2").name("Mohsin Husen").location(51.5171d, 0.1062d).buildIndex()); indexQueries.add(new AuthorMarkerEntityBuilder("3").name("Rizwan Idrees").location(51.5171d, 0.1062d).buildIndex()); operations.bulkIndex(indexQueries, authorMarkerIndex); - operations.refresh(AuthorMarkerEntity.class); + operations.indexOps(AuthorMarkerEntity.class).refresh(); } private void loadAnnotationBaseEntities() { @@ -132,7 +130,7 @@ public class ElasticsearchTemplateGeoTests { indexQueries.add(buildIndex(location3)); operations.bulkIndex(indexQueries, locationMarkerIndex); - operations.refresh(LocationMarkerEntity.class); + operations.indexOps(LocationMarkerEntity.class).refresh(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/core/index/MappingBuilderTests.java b/src/test/java/org/springframework/data/elasticsearch/core/index/MappingBuilderTests.java index d409c5322..2427311f7 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/index/MappingBuilderTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/index/MappingBuilderTests.java @@ -84,28 +84,27 @@ import org.springframework.test.context.ContextConfiguration; public class MappingBuilderTests extends MappingContextBaseTests { @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @BeforeEach public void before() { - - indexOperations.deleteIndex(StockPrice.class); - indexOperations.deleteIndex(SimpleRecursiveEntity.class); - indexOperations.deleteIndex(StockPrice.class); - indexOperations.deleteIndex(SampleInheritedEntity.class); - indexOperations.deleteIndex(User.class); - indexOperations.deleteIndex(Group.class); - indexOperations.deleteIndex(Book.class); - indexOperations.deleteIndex(NormalizerEntity.class); - indexOperations.deleteIndex(CopyToEntity.class); + 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 public void shouldNotFailOnCircularReference() { - indexOperations.createIndex(SimpleRecursiveEntity.class); - indexOperations.putMapping(SimpleRecursiveEntity.class); - indexOperations.refresh(SimpleRecursiveEntity.class); + operations.indexOps(SimpleRecursiveEntity.class).create(); + indexOperations.putMapping(indexOperations.createMapping(SimpleRecursiveEntity.class)); + indexOperations.refresh(); } @Test // DATAES-568 @@ -136,10 +135,11 @@ public class MappingBuilderTests extends MappingContextBaseTests { public void shouldAddStockPriceDocumentToIndex() { // Given + IndexOperations indexOps = operations.indexOps(StockPrice.class); // When - indexOperations.createIndex(StockPrice.class); - indexOperations.putMapping(StockPrice.class); + indexOps.create(); + indexOps.putMapping(indexOps.createMapping(StockPrice.class)); String symbol = "AU"; double price = 2.34; String id = "abc"; @@ -150,7 +150,7 @@ public class MappingBuilderTests extends MappingContextBaseTests { .symbol(symbol) // .price(BigDecimal.valueOf(price)) // .build()), index); - indexOperations.refresh(StockPrice.class); + operations.indexOps(StockPrice.class).refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); SearchHits result = operations.search(searchQuery, StockPrice.class, index); @@ -186,19 +186,19 @@ public class MappingBuilderTests extends MappingContextBaseTests { @Test // DATAES-76 public void shouldAddSampleInheritedEntityDocumentToIndex() { - // given + IndexCoordinates index = IndexCoordinates.of("test-index-sample-inherited-mapping-builder").withTypes("mapping"); + IndexOperations indexOps = operations.indexOps(index); // when - indexOperations.createIndex(SampleInheritedEntity.class); - indexOperations.putMapping(SampleInheritedEntity.class); + indexOps.create(); + indexOps.putMapping(indexOps.createMapping(SampleInheritedEntity.class)); Date createdDate = new Date(); String message = "msg"; String id = "abc"; - IndexCoordinates index = IndexCoordinates.of("test-index-sample-inherited-mapping-builder").withTypes("mapping"); operations.index(new SampleInheritedEntityBuilder(id).createdDate(createdDate).message(message).buildIndex(), index); - operations.refresh(SampleInheritedEntity.class); + operations.indexOps(SampleInheritedEntity.class).refresh(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); SearchHits result = operations.search(searchQuery, SampleInheritedEntity.class, index); @@ -231,10 +231,13 @@ public class MappingBuilderTests extends MappingContextBaseTests { public void shouldHandleReverseRelationship() { // given - indexOperations.createIndex(User.class); - indexOperations.putMapping(User.class); - indexOperations.createIndex(Group.class); - indexOperations.putMapping(Group.class); + IndexOperations indexOpsUser = operations.indexOps(User.class); + indexOpsUser.create(); + indexOpsUser.putMapping(indexOpsUser.createMapping(User.class)); + + IndexOperations indexOpsGroup = operations.indexOps(Group.class); + indexOpsGroup.create(); + indexOpsGroup.putMapping(indexOpsGroup.createMapping(Group.class)); // when @@ -245,8 +248,9 @@ public class MappingBuilderTests extends MappingContextBaseTests { public void shouldMapBooks() { // given - indexOperations.createIndex(Book.class); - indexOperations.putMapping(Book.class); + IndexOperations indexOps = operations.indexOps(Book.class); + indexOps.create(); + indexOps.putMapping(indexOps.createMapping(Book.class)); // when @@ -257,11 +261,12 @@ public class MappingBuilderTests extends MappingContextBaseTests { public void shouldUseBothAnalyzer() { // given - indexOperations.createIndex(Book.class); - indexOperations.putMapping(Book.class); + IndexOperations indexOps = this.operations.indexOps(Book.class); + indexOps.create(); + indexOps.putMapping(indexOps.createMapping(Book.class)); // when - Map mapping = operations.getMapping(Book.class); + Map mapping = indexOps.getMapping(); Map descriptionMapping = (Map) ((Map) mapping.get("properties")).get("description"); Map prefixDescription = (Map) ((Map) descriptionMapping.get("fields")).get("prefix"); @@ -298,11 +303,12 @@ public class MappingBuilderTests extends MappingContextBaseTests { public void shouldUseCopyTo() { // given - indexOperations.createIndex(CopyToEntity.class); - indexOperations.putMapping(CopyToEntity.class); + IndexOperations indexOps = operations.indexOps(CopyToEntity.class); + indexOps.create(); + indexOps.putMapping(indexOps.createMapping(CopyToEntity.class)); // when - Map mapping = operations.getMapping(CopyToEntity.class); + Map mapping = indexOps.getMapping(); Map properties = (Map) mapping.get("properties"); Map fieldFirstName = (Map) properties.get("firstName"); Map fieldLastName = (Map) properties.get("lastName"); diff --git a/src/test/java/org/springframework/data/elasticsearch/core/query/CriteriaQueryTests.java b/src/test/java/org/springframework/data/elasticsearch/core/query/CriteriaQueryTests.java index a0a34b3ec..c83367f1c 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/query/CriteriaQueryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/query/CriteriaQueryTests.java @@ -67,19 +67,20 @@ public class CriteriaQueryTests { private final IndexCoordinates index = IndexCoordinates.of("test-index-sample-core-query").withTypes("test-type"); @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @BeforeEach public void before() { - indexOperations.deleteIndex(SampleEntity.class); - indexOperations.createIndex(SampleEntity.class); - indexOperations.putMapping(SampleEntity.class); - indexOperations.refresh(SampleEntity.class); + indexOperations = operations.indexOps(SampleEntity.class); + indexOperations.delete(); + indexOperations.create(); + indexOperations.putMapping(indexOperations.createMapping(SampleEntity.class)); + indexOperations.refresh(); } @AfterEach void after() { - indexOperations.deleteIndex(SampleEntity.class); + indexOperations.delete(); } @Test @@ -96,7 +97,7 @@ public class CriteriaQueryTests { indexQuery.setId(documentId); indexQuery.setObject(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery( new Criteria("message").contains("test").and("message").contains("some")); @@ -139,7 +140,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery( new Criteria("message").contains("some").or("message").contains("test")); @@ -170,7 +171,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().and(new Criteria("message").contains("some"))); // when @@ -201,7 +202,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().or(new Criteria("message").contains("some"))); // when @@ -230,7 +231,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message")); // when @@ -272,7 +273,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message")); // when @@ -314,7 +315,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); Criteria criteria = new Criteria("message").endsWith("end"); CriteriaQuery criteriaQuery = new CriteriaQuery(criteria); @@ -356,7 +357,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); Criteria criteria = new Criteria("message").startsWith("start"); CriteriaQuery criteriaQuery = new CriteriaQuery(criteria); @@ -398,7 +399,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("contains")); // when @@ -439,7 +440,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").expression("+elasticsearch || test")); // when @@ -480,7 +481,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery( new Criteria("message").startsWith("some").endsWith("search").contains("message").is("some message search")); @@ -522,7 +523,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("foo").not()); // when @@ -566,7 +567,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100, 150)); // when @@ -608,7 +609,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(350, null)); // when @@ -651,7 +652,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(null, 550)); // when @@ -694,7 +695,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").lessThanEqual(750)); // when @@ -737,7 +738,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").greaterThanEqual(950)); // when @@ -780,7 +781,7 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1)); // when @@ -801,7 +802,7 @@ public class CriteriaQueryTests { indexQueries.add(buildIndex(SampleEntity.builder().id("3").message("ac").build())); operations.bulkIndex(indexQueries, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); // when CriteriaQuery criteriaQuery = new CriteriaQuery( @@ -828,7 +829,7 @@ public class CriteriaQueryTests { indexQuery.setId(documentId); indexQuery.setObject(sampleEntity); operations.index(indexQuery, index); - indexOperations.refresh(SampleEntity.class); + indexOperations.refresh(); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("Hello World!")); diff --git a/src/test/java/org/springframework/data/elasticsearch/immutable/ImmutableElasticsearchRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/immutable/ImmutableElasticsearchRepositoryTests.java index b4d4a949a..74e6308a1 100644 --- a/src/test/java/org/springframework/data/elasticsearch/immutable/ImmutableElasticsearchRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/immutable/ImmutableElasticsearchRepositoryTests.java @@ -29,6 +29,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; 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.junit.jupiter.ElasticsearchTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; @@ -57,10 +58,10 @@ public class ImmutableElasticsearchRepositoryTests { @BeforeEach public void before() { - - operations.deleteIndex(ImmutableEntity.class); - operations.createIndex(ImmutableEntity.class); - operations.refresh(ImmutableEntity.class); + IndexOperations indexOperations = operations.indexOps(ImmutableEntity.class); + indexOperations.delete(); + indexOperations.create(); + indexOperations.refresh(); } @Test // DATAES-281 diff --git a/src/test/java/org/springframework/data/elasticsearch/junit/jupiter/ElasticsearchTemplateConfiguration.java b/src/test/java/org/springframework/data/elasticsearch/junit/jupiter/ElasticsearchTemplateConfiguration.java index a7f88efb7..8795f3c81 100644 --- a/src/test/java/org/springframework/data/elasticsearch/junit/jupiter/ElasticsearchTemplateConfiguration.java +++ b/src/test/java/org/springframework/data/elasticsearch/junit/jupiter/ElasticsearchTemplateConfiguration.java @@ -19,9 +19,7 @@ import org.elasticsearch.client.Client; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.elasticsearch.config.ElasticsearchConfigurationSupport; -import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; /** @@ -43,9 +41,4 @@ public class ElasticsearchTemplateConfiguration extends ElasticsearchConfigurati ElasticsearchConverter elasticsearchConverter) { return new ElasticsearchTemplate(elasticsearchClient, elasticsearchConverter); } - - @Bean - IndexOperations indexOperations(ElasticsearchOperations elasticsearchOperations) { - return elasticsearchOperations.getIndexOperations(); - } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexCustomMethodRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexCustomMethodRepositoryTests.java index 8b0633828..0ebf14e2e 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexCustomMethodRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexCustomMethodRepositoryTests.java @@ -29,6 +29,7 @@ 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.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; @@ -52,16 +53,19 @@ public class ComplexCustomMethodRepositoryTests { @Autowired private ComplexElasticsearchRepository complexRepository; - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, SampleEntity.class); + indexOperations = operations.indexOps(SampleEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(SampleEntity.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexCustomMethodRepositoryManualWiringTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexCustomMethodRepositoryManualWiringTests.java index 86944a0f1..4af00a9bc 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexCustomMethodRepositoryManualWiringTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexCustomMethodRepositoryManualWiringTests.java @@ -29,6 +29,7 @@ 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.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; @@ -51,16 +52,18 @@ public class ComplexCustomMethodRepositoryManualWiringTests { @Autowired private ComplexElasticsearchRepositoryManualWiring complexRepository; - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, SampleEntity.class); + indexOperations = operations.indexOps(SampleEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(SampleEntity.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryBaseTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryBaseTests.java index 75f0e044b..fa95ca6bd 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryBaseTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryBaseTests.java @@ -49,6 +49,7 @@ import org.springframework.data.elasticsearch.annotations.Field; 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; @@ -80,16 +81,18 @@ public abstract class CustomMethodRepositoryBaseTests { @Autowired private SampleStreamingCustomMethodRepository streamingRepository; - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, SampleEntity.class); + indexOperations = operations.indexOps(SampleEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(SampleEntity.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepositoryTests.java index 544fe2e27..ea69d7f33 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepositoryTests.java @@ -30,6 +30,7 @@ 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.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; @@ -56,16 +57,18 @@ public class DoubleIDRepositoryTests { @Autowired private DoubleIDRepository repository; - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, DoubleIDEntity.class); + indexOperations = operations.indexOps(DoubleIDEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach public void after() { - indexOperations.deleteIndex(DoubleIDEntity.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/dynamicindex/DynamicIndexEntityTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/dynamicindex/DynamicIndexEntityTests.java index 469b25186..1db09a7ff 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/dynamicindex/DynamicIndexEntityTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/dynamicindex/DynamicIndexEntityTests.java @@ -26,7 +26,9 @@ 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.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; @@ -56,15 +58,17 @@ public class DynamicIndexEntityTests { @Autowired private DynamicIndexRepository repository; - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + private IndexOperations indexOperations; @Autowired private IndexNameProvider indexNameProvider; @BeforeEach public void init() { + indexOperations = operations.indexOps(IndexCoordinates.of("index1")); deleteIndexes(); - indexOperations.createIndex("index1"); - indexOperations.createIndex("index2"); + operations.indexOps(IndexCoordinates.of("index1")).create(); + operations.indexOps(IndexCoordinates.of("index2")).create(); } @AfterEach @@ -74,8 +78,8 @@ public class DynamicIndexEntityTests { private void deleteIndexes() { - indexOperations.deleteIndex("index1"); - indexOperations.deleteIndex("index2"); + indexOperations.delete(); + operations.indexOps(IndexCoordinates.of("index2")).delete(); } @Test // DATAES-456 diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepositoryTests.java index 5f20dbb99..a3d2fd2bc 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepositoryTests.java @@ -35,6 +35,7 @@ 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.GeoPointField; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; @@ -62,18 +63,20 @@ public class SpringDataGeoRepositoryTests { @EnableElasticsearchRepositories(considerNestedRepositories = true) static class Config {} - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + private IndexOperations indexOperations; @Autowired SpringDataGeoRepository repository; @BeforeEach public void init() { - IndexInitializer.init(indexOperations, GeoEntity.class); + indexOperations = operations.indexOps(GeoEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(GeoEntity.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepositoryTests.java index 8a3f5ae88..03f889152 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepositoryTests.java @@ -30,6 +30,7 @@ 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.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; @@ -56,16 +57,19 @@ public class IntegerIDRepositoryTests { @Autowired private IntegerIDRepository repository; - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, IntegerIDEntity.class); + indexOperations = operations.indexOps(IntegerIDEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(IntegerIDEntity.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/nestedobject/InnerObjectTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/nestedobject/InnerObjectTests.java index 0118ba8dd..1e6c6e564 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/nestedobject/InnerObjectTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/nestedobject/InnerObjectTests.java @@ -41,6 +41,7 @@ import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.InnerField; import org.springframework.data.elasticsearch.annotations.MultiField; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; @@ -65,16 +66,19 @@ public class InnerObjectTests { @Autowired private SampleElasticSearchBookRepository bookRepository; - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, Book.class); + indexOperations = operations.indexOps(Book.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(Book.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/dynamic/DynamicSettingAndMappingEntityRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/dynamic/DynamicSettingAndMappingEntityRepositoryTests.java index 0d8e38bc4..b19050ad9 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/dynamic/DynamicSettingAndMappingEntityRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/dynamic/DynamicSettingAndMappingEntityRepositoryTests.java @@ -16,6 +16,7 @@ package org.springframework.data.elasticsearch.repositories.setting.dynamic; import static org.assertj.core.api.Assertions.*; +import static org.springframework.data.elasticsearch.core.document.Document.*; import java.util.Map; @@ -61,18 +62,19 @@ public class DynamicSettingAndMappingEntityRepositoryTests { static class Config {} @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @Autowired private DynamicSettingAndMappingEntityRepository repository; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, DynamicSettingAndMappingEntity.class); + indexOperations = operations.indexOps(DynamicSettingAndMappingEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(DynamicSettingAndMappingEntity.class); + indexOperations.delete(); } @Test // DATAES-64 @@ -82,8 +84,8 @@ public class DynamicSettingAndMappingEntityRepositoryTests { // delete , create and apply mapping in before method // then - assertThat(indexOperations.indexExists(DynamicSettingAndMappingEntity.class)).isTrue(); - Map map = indexOperations.getSettings(DynamicSettingAndMappingEntity.class); + assertThat(indexOperations.exists()).isTrue(); + Map map = indexOperations.getSettings(); assertThat(map.containsKey("index.number_of_replicas")).isTrue(); assertThat(map.containsKey("index.number_of_shards")).isTrue(); assertThat(map.containsKey("index.analysis.analyzer.emailAnalyzer.tokenizer")).isTrue(); @@ -134,7 +136,7 @@ public class DynamicSettingAndMappingEntityRepositoryTests { // delete , create and apply mapping in before method // when - Map mapping = indexOperations.getMapping(DynamicSettingAndMappingEntity.class); + Map mapping = indexOperations.getMapping(); // then Map properties = (Map) mapping.get("properties"); @@ -149,9 +151,9 @@ public class DynamicSettingAndMappingEntityRepositoryTests { public void shouldCreateMappingWithSpecifiedMappings() { // given - indexOperations.deleteIndex(DynamicSettingAndMappingEntity.class); - indexOperations.createIndex(DynamicSettingAndMappingEntity.class); - indexOperations.refresh(DynamicSettingAndMappingEntity.class); + indexOperations.delete(); + indexOperations.create(); + indexOperations.refresh(); // when String mappings = "{\n" + // @@ -159,11 +161,11 @@ public class DynamicSettingAndMappingEntityRepositoryTests { " \"email\" : {\"type\" : \"text\", \"analyzer\" : \"emailAnalyzer\" }\n" + // " }\n" + // '}'; - indexOperations.putMapping(DynamicSettingAndMappingEntity.class, mappings); - indexOperations.refresh(DynamicSettingAndMappingEntity.class); + indexOperations.putMapping(parse(mappings)); + indexOperations.refresh(); // then - Map mapping = indexOperations.getMapping(DynamicSettingAndMappingEntity.class); + Map mapping = indexOperations.getMapping(); Map properties = (Map) mapping.get("properties"); assertThat(mapping).isNotNull(); assertThat(properties).isNotNull(); @@ -178,7 +180,7 @@ public class DynamicSettingAndMappingEntityRepositoryTests { // given // then - Map mapping = indexOperations.getMapping(DynamicSettingAndMappingEntity.class); + Map mapping = indexOperations.getMapping(); Map properties = (Map) mapping.get("properties"); assertThat(mapping).isNotNull(); assertThat(properties).isNotNull(); diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/fielddynamic/FieldDynamicMappingEntityRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/fielddynamic/FieldDynamicMappingEntityRepositoryTests.java index 267b6ce0d..1daeadef1 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/fielddynamic/FieldDynamicMappingEntityRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/fielddynamic/FieldDynamicMappingEntityRepositoryTests.java @@ -53,16 +53,17 @@ public class FieldDynamicMappingEntityRepositoryTests { static class Config {} @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, FieldDynamicMappingEntity.class); + indexOperations = operations.indexOps(FieldDynamicMappingEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(FieldDynamicMappingEntity.class); + indexOperations.delete(); } @Test // DATAES-209 diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELEntityTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELEntityTests.java index 8ac6c018b..ac3fe0a52 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELEntityTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELEntityTests.java @@ -55,16 +55,17 @@ public class SpELEntityTests { @Autowired private SpELRepository repository; @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, SpELEntity.class); + indexOperations = operations.indexOps(SpELEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex("test-index-abz-*"); + operations.indexOps(IndexCoordinates.of("test-index-abz-*")).delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepositoryTests.java index 1da59ef11..22ffaa154 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepositoryTests.java @@ -60,16 +60,17 @@ public class SynonymRepositoryTests { @Autowired private SynonymRepository repository; @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, SynonymEntity.class); + indexOperations = operations.indexOps(SynonymEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(SynonymEntity.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/uuidkeyed/UUIDElasticsearchRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/uuidkeyed/UUIDElasticsearchRepositoryTests.java index f70facbf6..c789aa015 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/uuidkeyed/UUIDElasticsearchRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/uuidkeyed/UUIDElasticsearchRepositoryTests.java @@ -45,6 +45,7 @@ import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; @@ -76,16 +77,18 @@ public class UUIDElasticsearchRepositoryTests { @Autowired private SampleUUIDKeyedElasticsearchRepository repository; - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, SampleEntityUUIDKeyed.class); + indexOperations = operations.indexOps(SampleEntityUUIDKeyed.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(SampleEntityUUIDKeyed.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/query/keywords/QueryKeywordsTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/query/keywords/QueryKeywordsTests.java index cac633f21..6354ee8fd 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/query/keywords/QueryKeywordsTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/query/keywords/QueryKeywordsTests.java @@ -37,6 +37,7 @@ 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.annotations.FieldType; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; @@ -65,11 +66,13 @@ class QueryKeywordsTests { @Autowired private ProductRepository repository; - @Autowired private IndexOperations indexOperations; + @Autowired ElasticsearchOperations operations; + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, Product.class); + indexOperations = operations.indexOps(Product.class); + IndexInitializer.init(indexOperations); Product product1 = Product.builder().id("1").name("Sugar").text("Cane sugar").price(1.0f).available(false) .sortName("sort5").build(); @@ -89,7 +92,7 @@ class QueryKeywordsTests { @AfterEach void after() { - indexOperations.deleteIndex(Product.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/simple/SimpleElasticsearchRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/support/simple/SimpleElasticsearchRepositoryTests.java index ef31e8434..54b943f4d 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/simple/SimpleElasticsearchRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/support/simple/SimpleElasticsearchRepositoryTests.java @@ -81,16 +81,17 @@ public class SimpleElasticsearchRepositoryTests { @Autowired private SampleElasticsearchRepository repository; @Autowired private ElasticsearchOperations operations; - @Autowired private IndexOperations indexOperations; + private IndexOperations indexOperations; @BeforeEach public void before() { - IndexInitializer.init(indexOperations, SampleEntity.class); + indexOperations = operations.indexOps(SampleEntity.class); + IndexInitializer.init(indexOperations); } @AfterEach void after() { - indexOperations.deleteIndex(SampleEntity.class); + indexOperations.delete(); } @Test diff --git a/src/test/java/org/springframework/data/elasticsearch/utils/IndexInitializer.java b/src/test/java/org/springframework/data/elasticsearch/utils/IndexInitializer.java index 9cd564bcb..f5b950728 100644 --- a/src/test/java/org/springframework/data/elasticsearch/utils/IndexInitializer.java +++ b/src/test/java/org/springframework/data/elasticsearch/utils/IndexInitializer.java @@ -32,27 +32,22 @@ public class IndexInitializer { * * @param operations * @param clazz - * @deprecated since 4.0, use {@link IndexInitializer#init(IndexOperations, Class)} + * @deprecated since 4.0, use {@link IndexInitializer#init(IndexOperations)} */ @Deprecated public static void init(ElasticsearchOperations operations, Class clazz) { - IndexOperations indexOperations = operations.getIndexOperations(); - indexOperations.deleteIndex(clazz); - indexOperations.createIndex(clazz); - indexOperations.putMapping(clazz); - indexOperations.refresh(clazz); + init(operations.indexOps(clazz)); } /** * Initialize a fresh index with mappings for {@link Class}. Drops the index if it exists before creation. * - * @param operations - * @param clazz + * @param indexOperations */ - public static void init(IndexOperations operations, Class clazz) { - operations.deleteIndex(clazz); - operations.createIndex(clazz); - operations.putMapping(clazz); - operations.refresh(clazz); + public static void init(IndexOperations indexOperations) { + indexOperations.delete(); + indexOperations.create(); + indexOperations.putMapping(indexOperations.createMapping()); + indexOperations.refresh(); } }