Dataes 745 consolidate operations api

Original PR: #396
This commit is contained in:
Peter-Josef Meisch 2020-02-25 22:01:40 +01:00 committed by GitHub
parent 1f56a9b9fe
commit 96ebc72dd1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
63 changed files with 1813 additions and 1301 deletions

View File

@ -19,7 +19,6 @@ import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
/** /**
@ -48,9 +47,4 @@ public abstract class AbstractElasticsearchConfiguration extends ElasticsearchCo
public ElasticsearchOperations elasticsearchOperations(ElasticsearchConverter elasticsearchConverter) { public ElasticsearchOperations elasticsearchOperations(ElasticsearchConverter elasticsearchConverter) {
return new ElasticsearchRestTemplate(elasticsearchClient(), elasticsearchConverter); return new ElasticsearchRestTemplate(elasticsearchClient(), elasticsearchConverter);
} }
@Bean
public IndexOperations indexOperations(ElasticsearchOperations elasticsearchOperations) {
return elasticsearchOperations.getIndexOperations();
}
} }

View File

@ -18,20 +18,26 @@ package org.springframework.data.elasticsearch.core;
import static org.springframework.util.StringUtils.*; import static org.springframework.util.StringUtils.*;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse; 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.collect.MapBuilder;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.annotations.Mapping; import org.springframework.data.elasticsearch.annotations.Mapping;
import org.springframework.data.elasticsearch.annotations.Setting; import org.springframework.data.elasticsearch.annotations.Setting;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; 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.index.MappingBuilder;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
/** /**
@ -48,88 +54,145 @@ abstract class AbstractDefaultIndexOperations implements IndexOperations {
protected final ElasticsearchConverter elasticsearchConverter; protected final ElasticsearchConverter elasticsearchConverter;
protected final RequestFactory requestFactory; 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; this.elasticsearchConverter = elasticsearchConverter;
requestFactory = new RequestFactory(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 // region IndexOperations
@Override
public boolean createIndex(String indexName) {
return createIndex(indexName, null);
}
@Override @Override
public boolean createIndex(Class<?> clazz) { public boolean create() {
String indexName = getRequiredPersistentEntity(clazz).getIndexCoordinates().getIndexName(); if (boundClass != null) {
if (clazz.isAnnotationPresent(Setting.class)) { Class<?> clazz = boundClass;
String settingPath = clazz.getAnnotation(Setting.class).settingPath(); String indexName = boundIndex.getIndexName();
if (hasText(settingPath)) { if (clazz.isAnnotationPresent(Setting.class)) {
String settings = ResourceUtil.readFileFromClasspath(settingPath); String settingPath = clazz.getAnnotation(Setting.class).settingPath();
if (hasText(settings)) { if (hasText(settingPath)) {
return createIndex(indexName, settings); 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 @Override
public boolean createIndex(Class<?> clazz, Object settings) { public boolean create(Document settings) {
return createIndex(getRequiredPersistentEntity(clazz).getIndexCoordinates().getIndexName(), 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<String, Object> getMapping() {
return doGetMapping(boundIndex);
}
abstract protected Map<String, Object> doGetMapping(IndexCoordinates index);
@Override
public Map<String, Object> getSettings() {
return getSettings(false);
} }
@Override @Override
public boolean deleteIndex(Class<?> clazz) { public Map<String, Object> getSettings(boolean includeDefaults) {
return deleteIndex(getRequiredPersistentEntity(clazz).getIndexCoordinates().getIndexName()); return doGetSettings(boundIndex.getIndexName(), includeDefaults);
}
protected abstract Map<String, Object> 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<AliasMetaData> queryForAlias() {
return doQueryForAlias(boundIndex.getIndexName());
}
protected abstract List<AliasMetaData> 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 @Override
public boolean indexExists(Class<?> clazz) { public Document createMapping(Class<?> clazz) {
return indexExists(getIndexCoordinatesFor(clazz).getIndexName()); return buildMapping(clazz);
} }
@Override protected Document buildMapping(Class<?> clazz) {
public Map<String, Object> getMapping(Class<?> clazz) {
return getMapping(getIndexCoordinatesFor(clazz));
}
@Override
public boolean putMapping(Class<?> clazz) {
return putMapping(clazz, buildMapping(clazz));
}
@Override
public <T> boolean putMapping(Class<T> clazz, Object mapping) {
return putMapping(getIndexCoordinatesFor(clazz), mapping);
}
@Override
public boolean putMapping(IndexCoordinates index, Class<?> clazz) {
return putMapping(index, buildMapping(clazz));
}
@Override
public Map<String, Object> getSettings(Class<?> clazz) {
return getSettings(clazz, false);
}
@Override
public Map<String, Object> 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) {
// load mapping specified in Mapping annotation if present // load mapping specified in Mapping annotation if present
if (clazz.isAnnotationPresent(Mapping.class)) { if (clazz.isAnnotationPresent(Mapping.class)) {
@ -139,7 +202,7 @@ abstract class AbstractDefaultIndexOperations implements IndexOperations {
String mappings = ResourceUtil.readFileFromClasspath(mappingPath); String mappings = ResourceUtil.readFileFromClasspath(mappingPath);
if (!StringUtils.isEmpty(mappings)) { if (!StringUtils.isEmpty(mappings)) {
return mappings; return Document.parse(mappings);
} }
} else { } else {
LOGGER.info("mappingPath in @Mapping has to be defined. Building mappings using @Field"); 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 // build mapping from field annotations
try { try {
return new MappingBuilder(elasticsearchConverter).buildPropertyMapping(clazz); String mapping = new MappingBuilder(elasticsearchConverter).buildPropertyMapping(clazz);
return Document.parse(mapping);
} catch (Exception e) { } catch (Exception e) {
throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e); throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e);
} }
@ -156,15 +220,18 @@ abstract class AbstractDefaultIndexOperations implements IndexOperations {
// endregion // endregion
// region Helper functions // region Helper functions
private <T> Map getDefaultSettings(ElasticsearchPersistentEntity<T> persistentEntity) { private <T> Document getDefaultSettings(ElasticsearchPersistentEntity<T> persistentEntity) {
if (persistentEntity.isUseServerConfiguration()) if (persistentEntity.isUseServerConfiguration()) {
return new HashMap(); return Document.create();
}
return new MapBuilder<String, String>().put("index.number_of_shards", String.valueOf(persistentEntity.getShards())) Map<String, String> map = new MapBuilder<String, String>()
.put("index.number_of_shards", String.valueOf(persistentEntity.getShards()))
.put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas())) .put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas()))
.put("index.refresh_interval", persistentEntity.getRefreshInterval()) .put("index.refresh_interval", persistentEntity.getRefreshInterval())
.put("index.store.type", persistentEntity.getIndexStoreType()).map(); .put("index.store.type", persistentEntity.getIndexStoreType()).map();
return Document.from(map);
} }
ElasticsearchPersistentEntity<?> getRequiredPersistentEntity(Class<?> clazz) { ElasticsearchPersistentEntity<?> getRequiredPersistentEntity(Class<?> clazz) {

View File

@ -6,6 +6,7 @@ import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; 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.bulk.BulkResponse;
import org.elasticsearch.action.search.MultiSearchRequest; import org.elasticsearch.action.search.MultiSearchRequest;
import org.elasticsearch.action.search.MultiSearchResponse; 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.common.unit.TimeValue;
import org.elasticsearch.index.query.MoreLikeThisQueryBuilder; import org.elasticsearch.index.query.MoreLikeThisQueryBuilder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; 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.ElasticsearchPersistentProperty;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; 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.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder; import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.MoreLikeThisQuery; import org.springframework.data.elasticsearch.core.query.MoreLikeThisQuery;
@ -50,16 +48,14 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
protected @Nullable ElasticsearchConverter elasticsearchConverter; protected @Nullable ElasticsearchConverter elasticsearchConverter;
protected @Nullable RequestFactory requestFactory; protected @Nullable RequestFactory requestFactory;
protected @Nullable IndexOperations indexOperations;
// region Initialization // region Initialization
protected void initialize(ElasticsearchConverter elasticsearchConverter, IndexOperations indexOperations) { protected void initialize(ElasticsearchConverter elasticsearchConverter) {
Assert.notNull(elasticsearchConverter, "elasticsearchConverter must not be null."); Assert.notNull(elasticsearchConverter, "elasticsearchConverter must not be null.");
this.elasticsearchConverter = elasticsearchConverter; this.elasticsearchConverter = elasticsearchConverter;
requestFactory = new RequestFactory(elasticsearchConverter); requestFactory = new RequestFactory(elasticsearchConverter);
this.indexOperations = indexOperations;
} }
protected ElasticsearchConverter createElasticsearchConverter() { protected ElasticsearchConverter createElasticsearchConverter() {
@ -78,16 +74,6 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
} }
// endregion // endregion
// region getter/setter
@Override
public IndexOperations getIndexOperations() {
Assert.notNull("indexOperations are not initialized");
return indexOperations;
}
// endregion
// region DocumentOperations // region DocumentOperations
@Override @Override
@ -147,24 +133,64 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
} }
@Override @Override
public void delete(Query query, Class<?> clazz, IndexCoordinates index) { @Nullable
public <T> T get(String id, Class<T> clazz) {
return get(id, clazz, getIndexCoordinatesFor(clazz));
}
Assert.notNull(query, "Query must not be null."); @Override
@Nullable
public <T> T get(GetQuery query, Class<T> clazz, IndexCoordinates index) {
return get(query.getId(), clazz, index);
}
SearchRequest searchRequest = requestFactory.searchRequest(query, clazz, index); @Override
DeleteQuery deleteQuery = new DeleteQuery(); public boolean exists(String id, Class<?> clazz) {
deleteQuery.setQuery(searchRequest.source().query()); 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 // endregion
// region SearchOperations // region SearchOperations
@Override
public long count(Query query, Class<?> clazz) {
return count(query, clazz, getIndexCoordinatesFor(clazz));
}
@Override @Override
public <T> CloseableIterator<T> stream(Query query, Class<T> clazz, IndexCoordinates index) { public <T> CloseableIterator<T> stream(Query query, Class<T> clazz, IndexCoordinates index) {
long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis(); long scrollTimeInMillis = TimeValue.timeValueMinutes(1).millis();
return StreamQueries.streamResults(startScroll(scrollTimeInMillis, query, clazz, index), return (CloseableIterator<T>) SearchHitSupport.unwrapSearchHits(searchForStream(query, clazz, index));
scrollId -> continueScroll(scrollId, scrollTimeInMillis, clazz), this::searchScrollClear); }
@Override
public <T> CloseableIterator<SearchHit<T>> searchForStream(Query query, Class<T> clazz) {
return searchForStream(query, clazz, getIndexCoordinatesFor(clazz));
} }
@Override @Override
@ -174,6 +200,11 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
scrollId -> searchScrollContinue(scrollId, scrollTimeInMillis, clazz), this::searchScrollClear); scrollId -> searchScrollContinue(scrollId, scrollTimeInMillis, clazz), this::searchScrollClear);
} }
@Override
public <T> SearchHits<T> search(MoreLikeThisQuery query, Class<T> clazz) {
return search(query, clazz, getIndexCoordinatesFor(clazz));
}
@Override @Override
public <T> SearchHits<T> search(MoreLikeThisQuery query, Class<T> clazz, IndexCoordinates index) { public <T> SearchHits<T> search(MoreLikeThisQuery query, Class<T> clazz, IndexCoordinates index) {
@ -220,6 +251,28 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
return res; return res;
} }
@Override
public <T> SearchHits<T> search(Query query, Class<T> clazz) {
return search(query, clazz, getIndexCoordinatesFor(clazz));
}
/*
* internal use only, not for public API
*/
abstract protected <T> ScrolledPage<SearchHit<T>> searchScrollStart(long scrollTimeInMillis, Query query,
Class<T> clazz, IndexCoordinates index);
/*
* internal use only, not for public API
*/
abstract protected <T> ScrolledPage<SearchHit<T>> searchScrollContinue(@Nullable String scrollId,
long scrollTimeInMillis, Class<T> clazz);
/*
* internal use only, not for public API
*/
abstract protected void searchScrollClear(String scrollId);
abstract protected MultiSearchResponse.Item[] getMultiSearchResult(MultiSearchRequest request); abstract protected MultiSearchResponse.Item[] getMultiSearchResult(MultiSearchRequest request);
// endregion // endregion
@ -247,9 +300,6 @@ public abstract class AbstractElasticsearchTemplate implements ElasticsearchOper
return values.toArray(valuesAsArray); return values.toArray(valuesAsArray);
} }
@Override
public abstract SearchResponse suggest(SuggestBuilder suggestion, IndexCoordinates index);
/** /**
* @param clazz the entity class * @param clazz the entity class
* @return the IndexCoordinates defined on the entity. * @return the IndexCoordinates defined on the entity.

View File

@ -41,8 +41,10 @@ import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.core.client.support.AliasData; import org.springframework.data.elasticsearch.core.client.support.AliasData;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; 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.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.AliasQuery; import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
@ -60,27 +62,35 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
private RestHighLevelClient client; private RestHighLevelClient client;
public DefaultIndexOperations(RestHighLevelClient client, ElasticsearchConverter elasticsearchConverter) { public DefaultIndexOperations(RestHighLevelClient client, ElasticsearchConverter elasticsearchConverter,
super(elasticsearchConverter); Class<?> boundClass) {
super(elasticsearchConverter, boundClass);
this.client = client;
}
public DefaultIndexOperations(RestHighLevelClient client, ElasticsearchConverter elasticsearchConverter,
IndexCoordinates boundIndex) {
super(elasticsearchConverter, boundIndex);
this.client = client; this.client = client;
} }
@Override @Override
public boolean createIndex(String indexName, Object settings) { protected boolean doCreate(String indexName, @Nullable Document settings) {
CreateIndexRequest request = requestFactory.createIndexRequest(indexName, settings); CreateIndexRequest request = requestFactory.createIndexRequest(indexName, settings);
try { try {
return client.indices().create(request, RequestOptions.DEFAULT).isAcknowledged(); return client.indices().create(request, RequestOptions.DEFAULT).isAcknowledged();
} catch (IOException e) { } 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 @Override
public boolean deleteIndex(String indexName) { protected boolean doDelete(String indexName) {
Assert.notNull(indexName, "No index defined for delete operation"); Assert.notNull(indexName, "No index defined for delete operation");
if (indexExists(indexName)) { if (doExists(indexName)) {
DeleteIndexRequest request = new DeleteIndexRequest(indexName); DeleteIndexRequest request = new DeleteIndexRequest(indexName);
try { try {
return client.indices().delete(request, RequestOptions.DEFAULT).isAcknowledged(); return client.indices().delete(request, RequestOptions.DEFAULT).isAcknowledged();
@ -92,7 +102,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
} }
@Override @Override
public boolean indexExists(String indexName) { protected boolean doExists(String indexName) {
GetIndexRequest request = new GetIndexRequest(indexName); GetIndexRequest request = new GetIndexRequest(indexName);
try { try {
return client.indices().exists(request, RequestOptions.DEFAULT); return client.indices().exists(request, RequestOptions.DEFAULT);
@ -102,7 +112,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
} }
@Override @Override
public boolean putMapping(IndexCoordinates index, Object mapping) { protected boolean doPutMapping(IndexCoordinates index, Document mapping) {
Assert.notNull(index, "No index defined for putMapping()"); Assert.notNull(index, "No index defined for putMapping()");
@ -115,7 +125,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
} }
@Override @Override
public Map<String, Object> getMapping(IndexCoordinates index) { protected Map<String, Object> doGetMapping(IndexCoordinates index) {
Assert.notNull(index, "No index defined for getMapping()"); Assert.notNull(index, "No index defined for getMapping()");
@ -130,7 +140,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
} }
@Override @Override
public boolean addAlias(AliasQuery query, IndexCoordinates index) { protected boolean doAddAlias(AliasQuery query, IndexCoordinates index) {
IndicesAliasesRequest request = requestFactory.indicesAddAliasesRequest(query, index); IndicesAliasesRequest request = requestFactory.indicesAddAliasesRequest(query, index);
try { try {
return client.indices().updateAliases(request, RequestOptions.DEFAULT).isAcknowledged(); return client.indices().updateAliases(request, RequestOptions.DEFAULT).isAcknowledged();
@ -140,7 +150,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
} }
@Override @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(index, "No index defined for Alias");
Assert.notNull(query.getAliasName(), "No alias defined"); Assert.notNull(query.getAliasName(), "No alias defined");
@ -155,7 +165,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
} }
@Override @Override
public List<AliasMetaData> queryForAlias(String indexName) { protected List<AliasMetaData> doQueryForAlias(String indexName) {
List<AliasMetaData> aliases = null; List<AliasMetaData> aliases = null;
RestClient restClient = client.getLowLevelClient(); RestClient restClient = client.getLowLevelClient();
Response response; Response response;
@ -172,12 +182,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
} }
@Override @Override
public Map<String, Object> getSettings(String indexName) { protected Map<String, Object> doGetSettings(String indexName, boolean includeDefaults) {
return getSettings(indexName, false);
}
@Override
public Map<String, Object> getSettings(String indexName, boolean includeDefaults) {
Assert.notNull(indexName, "No index defined for getSettings"); Assert.notNull(indexName, "No index defined for getSettings");
@ -196,7 +201,7 @@ class DefaultIndexOperations extends AbstractDefaultIndexOperations implements I
} }
@Override @Override
public void refresh(IndexCoordinates index) { protected void doRefresh(IndexCoordinates index) {
Assert.notNull(index, "No index defined for refresh()"); Assert.notNull(index, "No index defined for refresh()");

View File

@ -32,8 +32,10 @@ import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.AliasMetaData; import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; 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.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.AliasQuery; import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
@ -47,36 +49,43 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp
private final Client client; private final Client client;
public DefaultTransportIndexOperations(Client client, ElasticsearchConverter elasticsearchConverter) { public DefaultTransportIndexOperations(Client client, ElasticsearchConverter elasticsearchConverter,
super(elasticsearchConverter); Class<?> boundClass) {
super(elasticsearchConverter, boundClass);
this.client = client;
}
public DefaultTransportIndexOperations(Client client, ElasticsearchConverter elasticsearchConverter,
IndexCoordinates boundIndex) {
super(elasticsearchConverter, boundIndex);
this.client = client; this.client = client;
} }
@Override @Override
public boolean createIndex(String indexName, Object settings) { protected boolean doCreate(String indexName, @Nullable Document settings) {
CreateIndexRequestBuilder createIndexRequestBuilder = requestFactory.createIndexRequestBuilder(client, indexName, CreateIndexRequestBuilder createIndexRequestBuilder = requestFactory.createIndexRequestBuilder(client, indexName,
settings); settings);
return createIndexRequestBuilder.execute().actionGet().isAcknowledged(); return createIndexRequestBuilder.execute().actionGet().isAcknowledged();
} }
@Override @Override
public boolean deleteIndex(String indexName) { protected boolean doDelete(String indexName) {
Assert.notNull(indexName, "No index defined for delete operation"); 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 client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet().isAcknowledged();
} }
return false; return false;
} }
@Override @Override
public boolean indexExists(String indexName) { protected boolean doExists(String indexName) {
return client.admin().indices().exists(indicesExistsRequest(indexName)).actionGet().isExists(); return client.admin().indices().exists(indicesExistsRequest(indexName)).actionGet().isExists();
} }
@Override @Override
public boolean putMapping(IndexCoordinates index, Object mapping) { protected boolean doPutMapping(IndexCoordinates index, Document mapping) {
Assert.notNull(index, "No index defined for putMapping()"); Assert.notNull(index, "No index defined for putMapping()");
@ -85,7 +94,7 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp
} }
@Override @Override
public Map<String, Object> getMapping(IndexCoordinates index) { protected Map<String, Object> doGetMapping(IndexCoordinates index) {
Assert.notNull(index, "No index defined for getMapping()"); Assert.notNull(index, "No index defined for getMapping()");
@ -100,13 +109,13 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp
} }
@Override @Override
public boolean addAlias(AliasQuery query, IndexCoordinates index) { protected boolean doAddAlias(AliasQuery query, IndexCoordinates index) {
IndicesAliasesRequest.AliasActions aliasAction = requestFactory.aliasAction(query, index); IndicesAliasesRequest.AliasActions aliasAction = requestFactory.aliasAction(query, index);
return client.admin().indices().prepareAliases().addAliasAction(aliasAction).execute().actionGet().isAcknowledged(); return client.admin().indices().prepareAliases().addAliasAction(aliasAction).execute().actionGet().isAcknowledged();
} }
@Override @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(index, "No index defined for Alias");
Assert.notNull(query.getAliasName(), "No alias defined"); Assert.notNull(query.getAliasName(), "No alias defined");
@ -116,18 +125,13 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp
} }
@Override @Override
public List<AliasMetaData> queryForAlias(String indexName) { protected List<AliasMetaData> doQueryForAlias(String indexName) {
return client.admin().indices().getAliases(new GetAliasesRequest().indices(indexName)).actionGet().getAliases() return client.admin().indices().getAliases(new GetAliasesRequest().indices(indexName)).actionGet().getAliases()
.get(indexName); .get(indexName);
} }
@Override @Override
public Map<String, Object> getSettings(String indexName) { protected Map<String, Object> doGetSettings(String indexName, boolean includeDefaults) {
return getSettings(indexName, false);
}
@Override
public Map<String, Object> getSettings(String indexName, boolean includeDefaults) {
Assert.notNull(indexName, "No index defined for getSettings"); Assert.notNull(indexName, "No index defined for getSettings");
@ -144,7 +148,7 @@ class DefaultTransportIndexOperations extends AbstractDefaultIndexOperations imp
} }
@Override @Override
public void refresh(IndexCoordinates index) { protected void doRefresh(IndexCoordinates index) {
Assert.notNull(index, "No index defined for refresh()"); Assert.notNull(index, "No index defined for refresh()");

View File

@ -16,8 +16,8 @@
package org.springframework.data.elasticsearch.core; package org.springframework.data.elasticsearch.core;
import java.util.List; 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.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.BulkOptions; import org.springframework.data.elasticsearch.core.query.BulkOptions;
import org.springframework.data.elasticsearch.core.query.DeleteQuery; 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.IndexQuery;
import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.elasticsearch.core.query.UpdateQuery; import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateResponse;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
/** /**
@ -68,9 +69,9 @@ public interface DocumentOperations {
* saves the given entities to the given index * saves the given entities to the given index
* *
* @param entities must not be {@literal null} * @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 <T> the entity type * @param <T> the entity type
* @return the saved entites * @return the saved entities
*/ */
<T> Iterable<T> save(Iterable<T> entities, IndexCoordinates index); <T> Iterable<T> save(Iterable<T> entities, IndexCoordinates index);
@ -87,21 +88,32 @@ public interface DocumentOperations {
* Index an object. Will do save or update. * Index an object. Will do save or update.
* *
* @param query the query defining the object * @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 * @return returns the document id
*/ */
String index(IndexQuery query, IndexCoordinates index); 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 id the id of the object
* @param clazz the type of the object to be returned * @param clazz the entity class,
* @param index the index from which the object is read. * @param <T> the entity type
* @return the found object * @return the entity
*/ */
@Nullable @Nullable
<T> T get(GetQuery query, Class<T> clazz, IndexCoordinates index); <T> T get(String id, Class<T> 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> T get(String id, Class<T> clazz, IndexCoordinates index);
/** /**
* Execute a multiGet against elasticsearch for the given ids. * Execute a multiGet against elasticsearch for the given ids.
@ -113,6 +125,24 @@ public interface DocumentOperations {
*/ */
<T> List<T> multiGet(Query query, Class<T> clazz, IndexCoordinates index); <T> List<T> multiGet(Query query, Class<T> 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. * Bulk index all objects. Will do save or update.
* *
@ -158,6 +188,32 @@ public interface DocumentOperations {
*/ */
String delete(String id, IndexCoordinates index); 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. * Delete all records matching the query.
* *
@ -168,14 +224,6 @@ public interface DocumentOperations {
*/ */
void delete(Query query, Class<?> clazz, IndexCoordinates index); 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. * Partial update of the document.
* *
@ -184,4 +232,30 @@ public interface DocumentOperations {
* @return the update response * @return the update response
*/ */
UpdateResponse update(UpdateQuery updateQuery, IndexCoordinates index); 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> T get(GetQuery query, Class<T> clazz, IndexCoordinates index);
// endregion
} }

View File

@ -21,6 +21,7 @@ import java.util.Objects;
import org.elasticsearch.cluster.metadata.AliasMetaData; import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; 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.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.AliasQuery; import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
@ -40,7 +41,19 @@ import org.springframework.lang.Nullable;
*/ */
public interface ElasticsearchOperations extends DocumentOperations, SearchOperations { 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(); ElasticsearchConverter getElasticsearchConverter();
@ -52,11 +65,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* *
* @param indexName the name of the index * @param indexName the name of the index
* @return {@literal true} if the index was created * @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 @Deprecated
default boolean createIndex(String indexName) { 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 indexName the name of the index
* @param settings the index settings * @param settings the index settings
* @return {@literal true} if the index was created * @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 @Deprecated
default boolean createIndex(String indexName, Object settings) { 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 * @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document} * {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the index was created * @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 @Deprecated
default boolean createIndex(Class<?> clazz) { 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} * {@link org.springframework.data.elasticsearch.annotations.Document}
* @param settings the index settings * @param settings the index settings
* @return {@literal true} if the index was created * @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 @Deprecated
default boolean createIndex(Class<?> clazz, Object settings) { 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 * @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document} * {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the index was deleted * @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 @Deprecated
default boolean deleteIndex(Class<?> clazz) { 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 * @param indexName the name of the index to delete
* @return {@literal true} if the index was deleted * @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 @Deprecated
default boolean deleteIndex(String indexName) { 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 * @param indexName the name of the index
* @return {@literal true} if the index exists * @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 @Deprecated
default boolean indexExists(String indexName) { 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 * @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document} * {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the index exists * @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 @Deprecated
default boolean indexExists(Class<?> clazz) { 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 * @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document} * {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the mapping could be stored * @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 @Deprecated
default boolean putMapping(Class<?> clazz) { 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 * @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document} * {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the mapping could be stored * @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 @Deprecated
default boolean putMapping(IndexCoordinates index, Class<?> clazz) { 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 index the index to store the mapping to
* @param mappings can be a JSON String or a {@link Map} * @param mappings can be a JSON String or a {@link Map}
* @return {@literal true} if the mapping could be stored * @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 @Deprecated
default boolean putMapping(IndexCoordinates index, Object mappings) { 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} * {@link org.springframework.data.elasticsearch.annotations.Document}
* @param mappings can be a JSON String or a {@link Map} * @param mappings can be a JSON String or a {@link Map}
* @return {@literal true} if the mapping could be stored * @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 @Deprecated
default boolean putMapping(Class<?> clazz, Object mappings) { 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 * @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}. * {@link org.springframework.data.elasticsearch.annotations.Document}.
* @return the mapping * @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 @Deprecated
default Map<String, Object> getMapping(Class<?> clazz) { default Map<String, Object> 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 * @param index the index to read the mapping from
* @return the mapping * @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 @Deprecated
default Map<String, Object> getMapping(IndexCoordinates index) { default Map<String, Object> 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 query query defining the alias
* @param index the index for which to add an alias * @param index the index for which to add an alias
* @return true if the alias was created * @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 @Deprecated
default boolean addAlias(AliasQuery query, IndexCoordinates index) { 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 query query defining the alias
* @param index the index for which to remove an alias * @param index the index for which to remove an alias
* @return true if the alias was removed * @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 @Deprecated
default boolean removeAlias(AliasQuery query, IndexCoordinates index) { 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 * @param indexName the name of the index
* @return alias information * @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 @Deprecated
default List<AliasMetaData> queryForAlias(String indexName) { default List<AliasMetaData> 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 * @param indexName the name of the index
* @return the settings * @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 @Deprecated
default Map<String, Object> getSetting(String indexName) { default Map<String, Object> 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 * @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document} * {@link org.springframework.data.elasticsearch.annotations.Document}
* @return the settings * @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 @Deprecated
default Map<String, Object> getSetting(Class<?> clazz) { default Map<String, Object> 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<String, Object> 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<String, Object> getSettings(Class<?> clazz, boolean includeDefaults) {
return indexOps(clazz).getSettings(includeDefaults);
} }
/** /**
* Refresh the index(es). * Refresh the index(es).
* *
* @param index the index to refresh * @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 @Deprecated
default void refresh(IndexCoordinates index) { 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 * @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document} * {@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 @Deprecated
default void refresh(Class<?> clazz) { 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<String, Object>) object);
}
} catch (Exception e) {
throw new IllegalArgumentException("object cannot be converted to Document", e);
}
return document;
} // endregion
// region helper // region helper
/** /**

View File

@ -17,6 +17,7 @@ package org.springframework.data.elasticsearch.core;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest; 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.SearchResponse;
import org.elasticsearch.action.search.SearchScrollRequest; import org.elasticsearch.action.search.SearchScrollRequest;
import org.elasticsearch.action.update.UpdateRequest; import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue; 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.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.BulkOptions; import org.springframework.data.elasticsearch.core.query.BulkOptions;
import org.springframework.data.elasticsearch.core.query.DeleteQuery; 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.IndexQuery;
import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.elasticsearch.core.query.UpdateQuery; 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.data.elasticsearch.support.SearchHitsUtil;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -103,9 +103,29 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate {
} }
private void initialize(RestHighLevelClient client, ElasticsearchConverter elasticsearchConverter) { private void initialize(RestHighLevelClient client, ElasticsearchConverter elasticsearchConverter) {
Assert.notNull(client, "Client must not be null!"); Assert.notNull(client, "Client must not be null!");
this.client = client; 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 // endregion
@ -128,8 +148,8 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate {
@Override @Override
@Nullable @Nullable
public <T> T get(GetQuery query, Class<T> clazz, IndexCoordinates index) { public <T> T get(String id, Class<T> clazz, IndexCoordinates index) {
GetRequest request = requestFactory.getRequest(query, index); GetRequest request = requestFactory.getRequest(id, index);
try { try {
GetResponse response = client.get(request, RequestOptions.DEFAULT); GetResponse response = client.get(request, RequestOptions.DEFAULT);
return elasticsearchConverter.mapDocument(DocumentAdapters.from(response), clazz); 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 @Override
public List<String> bulkIndex(List<IndexQuery> queries, BulkOptions bulkOptions, IndexCoordinates index) { public List<String> bulkIndex(List<IndexQuery> queries, BulkOptions bulkOptions, IndexCoordinates index) {
@ -173,6 +203,10 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate {
@Override @Override
public String delete(String id, IndexCoordinates index) { 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)); DeleteRequest request = new DeleteRequest(index.getIndexName(), elasticsearchConverter.convertId(id));
try { try {
return client.delete(request, RequestOptions.DEFAULT).getId(); return client.delete(request, RequestOptions.DEFAULT).getId();
@ -182,6 +216,17 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate {
} }
@Override @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) { public void delete(DeleteQuery deleteQuery, IndexCoordinates index) {
DeleteByQueryRequest deleteByQueryRequest = requestFactory.deleteByQueryRequest(deleteQuery, index); DeleteByQueryRequest deleteByQueryRequest = requestFactory.deleteByQueryRequest(deleteQuery, index);
try { try {
@ -195,7 +240,9 @@ public class ElasticsearchRestTemplate extends AbstractElasticsearchTemplate {
public UpdateResponse update(UpdateQuery query, IndexCoordinates index) { public UpdateResponse update(UpdateQuery query, IndexCoordinates index) {
UpdateRequest request = requestFactory.updateRequest(query, index); UpdateRequest request = requestFactory.updateRequest(query, index);
try { 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) { } catch (IOException e) {
throw new ElasticsearchException("Error while update for request: " + request.toString(), e); throw new ElasticsearchException("Error while update for request: " + request.toString(), e);
} }

View File

@ -16,6 +16,7 @@
package org.springframework.data.elasticsearch.core; package org.springframework.data.elasticsearch.core;
import java.util.List; import java.util.List;
import java.util.Optional;
import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.bulk.BulkRequestBuilder; 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.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder; import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.search.suggest.SuggestBuilder; 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.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.BulkOptions; import org.springframework.data.elasticsearch.core.query.BulkOptions;
import org.springframework.data.elasticsearch.core.query.DeleteQuery; 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.IndexQuery;
import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.elasticsearch.core.query.UpdateQuery; 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.data.elasticsearch.support.SearchHitsUtil;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -97,9 +97,29 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
} }
private void initialize(Client client, ElasticsearchConverter elasticsearchConverter) { private void initialize(Client client, ElasticsearchConverter elasticsearchConverter) {
Assert.notNull(client, "Client must not be null!"); Assert.notNull(client, "Client must not be null!");
this.client = client; 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 // endregion
@ -128,8 +148,8 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
@Override @Override
@Nullable @Nullable
public <T> T get(GetQuery query, Class<T> clazz, IndexCoordinates index) { public <T> T get(String id, Class<T> clazz, IndexCoordinates index) {
GetRequestBuilder getRequestBuilder = requestFactory.getRequestBuilder(client, query, index); GetRequestBuilder getRequestBuilder = requestFactory.getRequestBuilder(client, id, index);
GetResponse response = getRequestBuilder.execute().actionGet(); GetResponse response = getRequestBuilder.execute().actionGet();
return elasticsearchConverter.mapDocument(DocumentAdapters.from(response), clazz); 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); 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 @Override
public List<String> bulkIndex(List<IndexQuery> queries, BulkOptions bulkOptions, IndexCoordinates index) { public List<String> bulkIndex(List<IndexQuery> queries, BulkOptions bulkOptions, IndexCoordinates index) {
@ -165,19 +191,36 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
@Override @Override
public String delete(String id, IndexCoordinates index) { 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)) return client.prepareDelete(index.getIndexName(), IndexCoordinates.TYPE, elasticsearchConverter.convertId(id))
.execute().actionGet().getId(); .execute().actionGet().getId();
} }
@Override @Override
@Deprecated
public void delete(DeleteQuery deleteQuery, IndexCoordinates index) { public void delete(DeleteQuery deleteQuery, IndexCoordinates index) {
requestFactory.deleteByQueryRequestBuilder(client, deleteQuery, index).get(); 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 @Override
public UpdateResponse update(UpdateQuery query, IndexCoordinates index) { public UpdateResponse update(UpdateQuery query, IndexCoordinates index) {
UpdateRequestBuilder updateRequestBuilder = requestFactory.updateRequestBuilderFor(client, query, 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<String> doBulkOperation(List<?> queries, BulkOptions bulkOptions, IndexCoordinates index) { private List<String> doBulkOperation(List<?> queries, BulkOptions bulkOptions, IndexCoordinates index) {

View File

@ -19,13 +19,17 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import org.elasticsearch.cluster.metadata.AliasMetaData; 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.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.AliasQuery; import org.springframework.data.elasticsearch.core.query.AliasQuery;
/** /**
* The operations for the * The operations for the
* <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices.html">Elasticsearch Index APIs</a>. * <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/indices.html">Elasticsearch Index APIs</a>.
* * <br/>
* 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 Peter-Josef Meisch
* @author Sascha Woo * @author Sascha Woo
* @since 4.0 * @since 4.0
@ -33,204 +37,104 @@ import org.springframework.data.elasticsearch.core.query.AliasQuery;
public interface IndexOperations { 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 * @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 * @param settings the index settings
* @return {@literal true} if the index was created * @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 * @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 * @return {@literal true} if the index exists
*/ */
boolean indexExists(String indexName); boolean exists();
/** /**
* check if index is exists. * Refresh the index(es) this 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 exists
*/ */
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 * @return mapping object
* {@link org.springframework.data.elasticsearch.annotations.Document} */
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 * @return {@literal true} if the mapping could be stored
*/ */
boolean putMapping(Class<?> clazz); boolean putMapping(Document mapping);
/**
* 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
*/
<T> boolean putMapping(Class<T> clazz, Object mappings);
/** /**
* Get mapping for an index defined by a class. * 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 * @return the mapping
*/ */
Map<String, Object> getMapping(Class<?> clazz); Map<String, Object> getMapping();
/**
* Get mapping for a given index.
*
* @param index the index to read the mapping from
* @return the mapping
*/
Map<String, Object> getMapping(IndexCoordinates index);
/** /**
* Add an alias. * Add an alias.
* *
* @param query query defining the alias * @param query query defining the alias
* @param index the index for which to add an alias
* @return true if the alias was created * @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<AliasMetaData> queryForAlias();
/** /**
* Remove an alias. * Remove an alias.
* *
* @param query query defining the alias * @param query query defining the alias
* @param index the index for which to remove an alias
* @return true if the alias was removed * @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 the settings
* @return alias information
*/ */
List<AliasMetaData> queryForAlias(String indexName); Map<String, Object> getSettings();
/** /**
* Get settings for a given indexName. * 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 * @return the settings
*/ */
Map<String, Object> getSettings(String indexName); Map<String, Object> getSettings(boolean includeDefaults);
/**
* 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<String, Object> 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<String, Object> 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<String, Object> 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);
} }

View File

@ -151,8 +151,37 @@ public interface ReactiveDocumentOperations {
* @param entityType the domain type used for mapping the document. * @param entityType the domain type used for mapping the document.
* @param <T> * @param <T>
* @return {@link Mono#empty()} if not found. * @return {@link Mono#empty()} if not found.
* @deprecated since 4.0 use {@link #get(String, Class)}
*/ */
<T> Mono<T> findById(String id, Class<T> entityType); @Deprecated
default <T> Mono<T> findById(String id, Class<T> 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 <T>
* @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 <T> Mono<T> findById(String id, Class<T> 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 <T>
* @return {@link Mono#empty()} if not found.
* @since 4.0
*/
<T> Mono<T> get(String id, Class<T> entityType);
/** /**
* Fetch the entity with given {@literal id}. * Fetch the entity with given {@literal id}.
@ -162,7 +191,7 @@ public interface ReactiveDocumentOperations {
* @param <T> * @param <T>
* @return the {@link Mono} emitting the entity or signalling completion if none found. * @return the {@link Mono} emitting the entity or signalling completion if none found.
*/ */
<T> Mono<T> findById(String id, Class<T> entityType, IndexCoordinates index); <T> Mono<T> get(String id, Class<T> entityType, IndexCoordinates index);
/** /**
* Check if an entity with given {@literal id} exists. * 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} * @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. * @return a {@link Mono} emitting {@literal true} if a matching document exists, {@literal false} otherwise.
*/ */
Mono<Boolean> 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<Boolean> exists(String id, Class<?> entityType, IndexCoordinates index); Mono<Boolean> exists(String id, Class<?> entityType, IndexCoordinates index);
/** /**
@ -188,7 +228,7 @@ public interface ReactiveDocumentOperations {
* @param entity must not be {@literal null}. * @param entity must not be {@literal null}.
* @return a {@link Mono} emitting the {@literal id} of the removed document. * @return a {@link Mono} emitting the {@literal id} of the removed document.
*/ */
Mono<String> delete(Object entity); Mono<String> delete(Object entity);
/** /**
* Delete the given entity extracting index and type from entity metadata. * 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} * @param index the target index, must not be {@literal null}
* @return a {@link Mono} emitting the {@literal id} of the removed document. * @return a {@link Mono} emitting the {@literal id} of the removed document.
*/ */
Mono<String> delete(Object entity, IndexCoordinates index); Mono<String> delete(Object entity, IndexCoordinates index);
/** /**
* Delete the entity with given {@literal id}. * Delete the entity with given {@literal id}.
@ -206,32 +246,32 @@ public interface ReactiveDocumentOperations {
* @param index the target index, 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. * @return a {@link Mono} emitting the {@literal id} of the removed document.
*/ */
default Mono<String> deleteById(String id, IndexCoordinates index) { Mono<String> 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<String> 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<String> 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<String> 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<String> deleteById(String id, Class<?> entityType, IndexCoordinates index);
/** /**
* Delete the documents matching the given {@link Query} extracting index and type from entity metadata. * 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}. * @param entityType must not be {@literal null}.
* @return a {@link Mono} emitting the number of the removed documents. * @return a {@link Mono} emitting the number of the removed documents.
*/ */
Mono<Long> deleteBy(Query query, Class<?> entityType); Mono<Long> delete(Query query, Class<?> entityType);
/** /**
* Delete the documents matching the given {@link Query} extracting index and type from entity metadata. * 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} * @param index the target index, must not be {@literal null}
* @return a {@link Mono} emitting the number of the removed documents. * @return a {@link Mono} emitting the number of the removed documents.
*/ */
Mono<Long> deleteBy(Query query, Class<?> entityType, IndexCoordinates index); Mono<Long> delete(Query query, Class<?> entityType, IndexCoordinates index);
} }

View File

@ -243,21 +243,31 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
} }
} }
/** @Override
* Customization hook on the actual execution result {@link Publisher}. <br /> public Mono<Boolean> exists(String id, Class<?> entityType) {
* return doExists(id, getIndexCoordinatesFor(entityType));
* @param request the already prepared {@link GetRequest} ready to be executed.
* @return a {@link Mono} emitting the result of the operation.
*/
protected Mono<GetResult> doFindById(GetRequest request) {
return Mono.from(execute(client -> client.get(request))) //
.onErrorResume(NoSuchIndexException.class, it -> Mono.empty());
} }
@Override @Override
public Mono<Boolean> exists(String id, Class<?> entityType) { public Mono<Boolean> exists(String id, IndexCoordinates index) {
return exists(id, entityType, getIndexCoordinatesFor(entityType)); return doExists(id, index);
}
/*
* (non-Javadoc)
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#exists(String, Class, IndexCoordinates)
*/
@Override
public Mono<Boolean> exists(String id, Class<?> entityType, IndexCoordinates index) {
Assert.notNull(id, "Id must not be null!");
return doExists(id, index);
}
private Mono<Boolean> 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 @Override
public <T> Mono<T> findById(String id, Class<T> entityType) { public <T> Mono<T> get(String id, Class<T> entityType) {
return findById(id, entityType, getIndexCoordinatesFor(entityType)); return get(id, entityType, getIndexCoordinatesFor(entityType));
} }
/*
* (non-Javadoc)
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#findById(String, Class, IndexCoordinates)
*/
@Override @Override
public <T> Mono<T> findById(String id, Class<T> entityType, IndexCoordinates index) { public <T> Mono<T> get(String id, Class<T> entityType, IndexCoordinates index) {
Assert.notNull(id, "Id must not be null!"); 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)); .map(it -> converter.mapDocument(DocumentAdapters.from(it), entityType));
} }
private Mono<GetResult> doFindById(String id, ElasticsearchPersistentEntity<?> entity, IndexCoordinates index) { private Mono<GetResult> doGet(String id, ElasticsearchPersistentEntity<?> entity, IndexCoordinates index) {
return Mono.defer(() -> { return Mono.defer(() -> {
return doGet(new GetRequest(index.getIndexName(), id));
return doFindById(new GetRequest(index.getIndexName(), id));
}); });
} }
/* /**
* (non-Javadoc) * Customization hook on the actual execution result {@link Publisher}. <br />
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#exists(String, Class, IndexCoordinates) *
* @param request the already prepared {@link GetRequest} ready to be executed.
* @return a {@link Mono} emitting the result of the operation.
*/ */
@Override protected Mono<GetResult> doGet(GetRequest request) {
public Mono<Boolean> exists(String id, Class<?> entityType, IndexCoordinates index) {
Assert.notNull(id, "Id must not be null!"); return Mono.from(execute(client -> client.get(request))) //
.onErrorResume(NoSuchIndexException.class, it -> Mono.empty());
return doExists(id, getPersistentEntityFor(entityType), index);
}
private Mono<Boolean> doExists(String id, ElasticsearchPersistentEntity<?> entity, @Nullable IndexCoordinates index) {
return Mono.defer(() -> doExists(new GetRequest(index.getIndexName(), id)));
} }
/* /*
@ -367,25 +366,11 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#delete(Object, String, String) * @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#delete(Object, String, String)
*/ */
@Override @Override
public Mono<String> delete(Object entity, IndexCoordinates index) { public Mono<String> delete(Object entity, IndexCoordinates index) {
Entity<?> elasticsearchEntity = operations.forEntity(entity); Entity<?> elasticsearchEntity = operations.forEntity(entity);
return Mono.defer(() -> doDeleteById(entity, converter.convertId(elasticsearchEntity.getId()), return Mono.defer(() -> doDeleteById(converter.convertId(elasticsearchEntity.getId()), index));
elasticsearchEntity.getPersistentEntity(), index));
}
/*
* (non-Javadoc)
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#delete(String, Class, IndexCoordinates)
*/
@Override
public Mono<String> deleteById(String id, Class<?> entityType, IndexCoordinates index) {
Assert.notNull(id, "Id must not be null!");
return doDeleteById(null, id, getPersistentEntityFor(entityType), index);
} }
@Override @Override
@ -394,25 +379,37 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
} }
@Override @Override
public Mono<String> deleteById(String id, Class<?> entityType) { public Mono<String> delete(String id, Class<?> entityType) {
return deleteById(id, entityType, getIndexCoordinatesFor(entityType));
Assert.notNull(id, "id must not be null");
Assert.notNull(entityType, "entityType must not be null");
return delete(id, getIndexCoordinatesFor(entityType));
} }
private Mono<String> doDeleteById(@Nullable Object source, String id, ElasticsearchPersistentEntity<?> entity, @Override
IndexCoordinates index) { public Mono<String> 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<String> doDeleteById(String id, IndexCoordinates index) {
return Mono.defer(() -> { return Mono.defer(() -> {
return doDelete(prepareDeleteRequest(source, new DeleteRequest(index.getIndexName(), id))); return doDelete(prepareDeleteRequest(new DeleteRequest(index.getIndexName(), id)));
}); });
} }
/* /*
* (non-Javadoc) * (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 @Override
public Mono<Long> deleteBy(Query query, Class<?> entityType, IndexCoordinates index) { public Mono<Long> delete(Query query, Class<?> entityType, IndexCoordinates index) {
Assert.notNull(query, "Query must not be null!"); Assert.notNull(query, "Query must not be null!");
@ -421,8 +418,8 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
} }
@Override @Override
public Mono<Long> deleteBy(Query query, Class<?> entityType) { public Mono<Long> delete(Query query, Class<?> entityType) {
return deleteBy(query, entityType, getIndexCoordinatesFor(entityType)); return delete(query, entityType, getIndexCoordinatesFor(entityType));
} }
private Flux<BulkByScrollResponse> doDeleteBy(Query query, ElasticsearchPersistentEntity<?> entity, private Flux<BulkByScrollResponse> 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 * Customization hook to modify a generated {@link DeleteRequest} prior to its execution. Eg. by setting the
* {@link WriteRequest#setRefreshPolicy(String) refresh policy} if applicable. * {@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}. * @param request the generated {@link DeleteRequest}.
* @return never {@literal null}. * @return never {@literal null}.
*/ */
protected DeleteRequest prepareDeleteRequest(@Nullable Object source, DeleteRequest request) { protected DeleteRequest prepareDeleteRequest(DeleteRequest request) {
return prepareWriteRequest(request); return prepareWriteRequest(request);
} }

View File

@ -19,6 +19,7 @@ import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.springframework.util.CollectionUtils.*; import static org.springframework.util.CollectionUtils.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -44,8 +45,6 @@ import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.unit.TimeValue; 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.VersionType;
import org.elasticsearch.index.query.MoreLikeThisQueryBuilder; import org.elasticsearch.index.query.MoreLikeThisQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder; 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.DeleteByQueryAction;
import org.elasticsearch.index.reindex.DeleteByQueryRequest; import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.index.reindex.DeleteByQueryRequestBuilder; 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.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder; 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.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.GeoDistanceSortBuilder; 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.domain.Sort;
import org.springframework.data.elasticsearch.ElasticsearchException; import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; 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.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
@ -180,31 +181,27 @@ class RequestFactory {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public CreateIndexRequest createIndexRequest(String indexName, Object settings) { public CreateIndexRequest createIndexRequest(String indexName, @Nullable Document settings) {
CreateIndexRequest request = new CreateIndexRequest(indexName); CreateIndexRequest request = new CreateIndexRequest(indexName);
if (settings instanceof String) {
request.settings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE); if (settings != null) {
} else if (settings instanceof Map) { request.settings(settings);
request.settings((Map<String, ?>) settings);
} else if (settings instanceof XContentBuilder) {
request.settings((XContentBuilder) settings);
} }
return request; return request;
} }
@SuppressWarnings("unchecked") @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); CreateIndexRequestBuilder createIndexRequestBuilder = client.admin().indices().prepareCreate(indexName);
if (settings instanceof String) {
createIndexRequestBuilder.setSettings(String.valueOf(settings), Requests.INDEX_CONTENT_TYPE); if (settings != null) {
} else if (settings instanceof Map) { createIndexRequestBuilder.setSettings(settings);
createIndexRequestBuilder.setSettings((Map<String, ?>) settings);
} else if (settings instanceof XContentBuilder) {
createIndexRequestBuilder.setSettings((XContentBuilder) settings);
} }
return createIndexRequestBuilder; return createIndexRequestBuilder;
} }
@Deprecated
public DeleteByQueryRequest deleteByQueryRequest(DeleteQuery deleteQuery, IndexCoordinates index) { public DeleteByQueryRequest deleteByQueryRequest(DeleteQuery deleteQuery, IndexCoordinates index) {
DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(index.getIndexNames()) // DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(index.getIndexNames()) //
.setQuery(deleteQuery.getQuery()) // .setQuery(deleteQuery.getQuery()) //
@ -220,6 +217,25 @@ class RequestFactory {
return deleteByQueryRequest; 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, public DeleteByQueryRequestBuilder deleteByQueryRequestBuilder(Client client, DeleteQuery deleteQuery,
IndexCoordinates index) { IndexCoordinates index) {
DeleteByQueryRequestBuilder requestBuilder = new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE) // DeleteByQueryRequestBuilder requestBuilder = new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE) //
@ -236,14 +252,37 @@ class RequestFactory {
return requestBuilder; return requestBuilder;
} }
public GetRequest getRequest(GetQuery query, IndexCoordinates index) { public DeleteByQueryRequestBuilder deleteByQueryRequestBuilder(Client client, Query query, Class<?> clazz,
return new GetRequest(index.getIndexName(), query.getId()); 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) { public GetRequest getRequest(String id, IndexCoordinates index) {
return client.prepareGet(index.getIndexName(), null, query.getId()); 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) { public HighlightBuilder highlightBuilder(Query query) {
HighlightBuilder highlightBuilder = query.getHighlightQuery().map(HighlightQuery::getHighlightBuilder).orElse(null); HighlightBuilder highlightBuilder = query.getHighlightQuery().map(HighlightQuery::getHighlightBuilder).orElse(null);
@ -420,39 +459,40 @@ class RequestFactory {
public UpdateRequest updateRequest(UpdateQuery query, IndexCoordinates index) { public UpdateRequest updateRequest(UpdateQuery query, IndexCoordinates index) {
Assert.notNull(query.getId(), "No Id define for Query"); UpdateRequest updateRequest = new UpdateRequest(index.getIndexName(), query.getId());
Assert.notNull(query.getUpdateRequest(), "No UpdateRequest define for Query");
UpdateRequest queryUpdateRequest = query.getUpdateRequest(); if (query.getScript() != null) {
Map<String, Object> params = query.getParams();
UpdateRequest updateRequest = new UpdateRequest(index.getIndexName(), query.getId()) // if (params == null) {
.routing(queryUpdateRequest.routing()) // params = new HashMap<>();
.retryOnConflict(queryUpdateRequest.retryOnConflict()) // }
.timeout(queryUpdateRequest.timeout()) // Script script = new Script(ScriptType.INLINE, query.getLang(), query.getScript(), params);
.waitForActiveShards(queryUpdateRequest.waitForActiveShards()) // updateRequest.script(script);
.setRefreshPolicy(queryUpdateRequest.getRefreshPolicy()) //
.waitForActiveShards(queryUpdateRequest.waitForActiveShards()) //
.scriptedUpsert(queryUpdateRequest.scriptedUpsert()) //
.docAsUpsert(queryUpdateRequest.docAsUpsert());
if (query.DoUpsert()) {
updateRequest.docAsUpsert(true);
} }
if (queryUpdateRequest.script() != null) { if (query.getDocument() != null) {
updateRequest.script(queryUpdateRequest.script()); updateRequest.doc(query.getDocument());
} }
if (queryUpdateRequest.doc() != null) { if (query.getUpsert() != null) {
updateRequest.doc(queryUpdateRequest.doc()); updateRequest.upsert(query.getUpsert());
} }
if (queryUpdateRequest.upsertRequest() != null) { if (query.getRouting() != null) {
updateRequest.upsert(queryUpdateRequest.upsertRequest()); updateRequest.routing(query.getRouting());
} }
if (queryUpdateRequest.fetchSource() != null) { if (query.getScriptedUpsert() != null) {
updateRequest.fetchSource(queryUpdateRequest.fetchSource()); updateRequest.scriptedUpsert(query.getScriptedUpsert());
}
if (query.getDocAsUpsert() != null) {
updateRequest.docAsUpsert(query.getDocAsUpsert());
}
if (query.getFetchSource() != null) {
updateRequest.fetchSource(query.getFetchSource());
} }
return updateRequest; return updateRequest;
@ -460,41 +500,41 @@ class RequestFactory {
public UpdateRequestBuilder updateRequestBuilderFor(Client client, UpdateQuery query, IndexCoordinates index) { public UpdateRequestBuilder updateRequestBuilderFor(Client client, UpdateQuery query, IndexCoordinates index) {
Assert.notNull(query.getId(), "No Id define for Query"); UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate(index.getIndexName(), IndexCoordinates.TYPE,
Assert.notNull(query.getUpdateRequest(), "No UpdateRequest define for Query"); query.getId());
UpdateRequest queryUpdateRequest = query.getUpdateRequest(); if (query.getScript() != null) {
Map<String, Object> params = query.getParams();
UpdateRequestBuilder updateRequestBuilder = client if (params == null) {
.prepareUpdate(index.getIndexName(), IndexCoordinates.TYPE, query.getId()) // params = new HashMap<>();
.setRouting(queryUpdateRequest.routing()) // }
.setRetryOnConflict(queryUpdateRequest.retryOnConflict()) // Script script = new Script(ScriptType.INLINE, query.getLang(), query.getScript(), params);
.setTimeout(queryUpdateRequest.timeout()) // updateRequestBuilder.setScript(script);
.setWaitForActiveShards(queryUpdateRequest.waitForActiveShards()) //
.setRefreshPolicy(queryUpdateRequest.getRefreshPolicy()) //
.setWaitForActiveShards(queryUpdateRequest.waitForActiveShards()) //
.setScriptedUpsert(queryUpdateRequest.scriptedUpsert()) //
.setDocAsUpsert(queryUpdateRequest.docAsUpsert());
if (query.DoUpsert()) {
updateRequestBuilder.setDocAsUpsert(true);
} }
if (queryUpdateRequest.script() != null) { if (query.getDocument() != null) {
updateRequestBuilder.setScript(queryUpdateRequest.script()); updateRequestBuilder.setDoc(query.getDocument());
} }
if (queryUpdateRequest.doc() != null) { if (query.getUpsert() != null) {
updateRequestBuilder.setDoc(queryUpdateRequest.doc()); updateRequestBuilder.setUpsert(query.getUpsert());
} }
if (queryUpdateRequest.upsertRequest() != null) { if (query.getRouting() != null) {
updateRequestBuilder.setUpsert(queryUpdateRequest.upsertRequest()); updateRequestBuilder.setRouting(query.getRouting());
} }
FetchSourceContext fetchSourceContext = queryUpdateRequest.fetchSource(); if (query.getScriptedUpsert() != null) {
if (fetchSourceContext != null) { updateRequestBuilder.setScriptedUpsert(query.getScriptedUpsert());
updateRequestBuilder.setFetchSource(fetchSourceContext.includes(), fetchSourceContext.excludes()); }
if (query.getDocAsUpsert() != null) {
updateRequestBuilder.setDocAsUpsert(query.getDocAsUpsert());
}
if (query.getFetchSource() != null) {
updateRequestBuilder.setFetchSource(query.getFetchSource());
} }
return updateRequestBuilder; return updateRequestBuilder;
@ -569,29 +609,17 @@ class RequestFactory {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public PutMappingRequest putMappingRequest(IndexCoordinates index, Object mapping) { public PutMappingRequest putMappingRequest(IndexCoordinates index, Document mapping) {
PutMappingRequest request = new PutMappingRequest(index.getIndexName()); PutMappingRequest request = new PutMappingRequest(index.getIndexName());
if (mapping instanceof String) { request.source(mapping);
request.source(String.valueOf(mapping), XContentType.JSON);
} else if (mapping instanceof Map) {
request.source((Map<String, ?>) mapping);
} else if (mapping instanceof XContentBuilder) {
request.source((XContentBuilder) mapping);
}
return request; return request;
} }
@SuppressWarnings("rawtypes") @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()) PutMappingRequestBuilder requestBuilder = client.admin().indices().preparePutMapping(index.getIndexName())
.setType(IndexCoordinates.TYPE); .setType(IndexCoordinates.TYPE);
if (mapping instanceof String) { requestBuilder.setSource(mapping);
requestBuilder.setSource(String.valueOf(mapping), XContentType.JSON);
} else if (mapping instanceof Map) {
requestBuilder.setSource((Map) mapping);
} else if (mapping instanceof XContentBuilder) {
requestBuilder.setSource((XContentBuilder) mapping);
}
return requestBuilder; return requestBuilder;
} }

View File

@ -50,6 +50,15 @@ public interface SearchOperations {
return count(query, null, index); 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 * return number of elements found by given query
* *
@ -211,50 +220,6 @@ public interface SearchOperations {
return search(query, clazz, index).map(SearchHit::getId).toList(); 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 <T> ScrolledPage<T> startScroll(long scrollTimeInMillis, Query query, Class<T> clazz,
IndexCoordinates index) {
return (ScrolledPage<T>) 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 <T> ScrolledPage<T> continueScroll(@Nullable String scrollId, long scrollTimeInMillis, Class<T> clazz) {
return (ScrolledPage<T>) 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. * more like this query to search for documents that are "like" a specific document.
* *
@ -271,8 +236,32 @@ public interface SearchOperations {
AggregatedPage<SearchHit<T>> aggregatedPage = SearchHitSupport.page(searchHits, query.getPageable()); AggregatedPage<SearchHit<T>> aggregatedPage = SearchHitSupport.page(searchHits, query.getPageable());
return (AggregatedPage<T>) SearchHitSupport.unwrapSearchHits(aggregatedPage); return (AggregatedPage<T>) SearchHitSupport.unwrapSearchHits(aggregatedPage);
} }
// endregion // 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 <T> SearchHit<T> searchOne(Query query, Class<T> clazz) {
List<SearchHit<T>> content = search(query, clazz).getSearchHits();
return content.isEmpty() ? null : content.get(0);
}
/** /**
* Execute the query against elasticsearch and return the first returned object. * Execute the query against elasticsearch and return the first returned object.
* *
@ -308,6 +297,16 @@ public interface SearchOperations {
*/ */
List<SearchHits<?>> multiSearch(List<? extends Query> queries, List<Class<?>> classes, IndexCoordinates index); List<SearchHits<?>> multiSearch(List<? extends Query> queries, List<Class<?>> classes, IndexCoordinates index);
/**
* Execute the criteria query against elasticsearch and return result as {@link SearchHits}
*
* @param <T> 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
*/
<T> SearchHits<T> search(Query query, Class<T> clazz);
/** /**
* Execute the criteria query against elasticsearch and return result as {@link SearchHits} * Execute the criteria query against elasticsearch and return result as {@link SearchHits}
* *
@ -319,6 +318,16 @@ public interface SearchOperations {
*/ */
<T> SearchHits<T> search(Query query, Class<T> clazz, IndexCoordinates index); <T> SearchHits<T> search(Query query, Class<T> clazz, IndexCoordinates index);
/**
* more like this query to search for documents that are "like" a specific document.
*
* @param <T> 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
*/
<T> SearchHits<T> search(MoreLikeThisQuery query, Class<T> clazz);
/** /**
* more like this query to search for documents that are "like" a specific document. * more like this query to search for documents that are "like" a specific document.
* *
@ -331,34 +340,16 @@ public interface SearchOperations {
<T> SearchHits<T> search(MoreLikeThisQuery query, Class<T> clazz, IndexCoordinates index); <T> SearchHits<T> search(MoreLikeThisQuery query, Class<T> clazz, IndexCoordinates index);
/** /**
* Returns scrolled page for given query * Executes the given {@link Query} against elasticsearch and return result as {@link CloseableIterator}.
* <p>
* *
* @param scrollTimeInMillis duration of the scroll time * @param <T> element return type
* @param query The search query. * @param query the query to execute
* @param clazz The class of entity to retrieve. * @param clazz the entity clazz used for property mapping and index name extraction
* @param index the index to run the query against * @return a {@link CloseableIterator} that wraps an Elasticsearch scroll context that needs to be closed in case of *
* @return scrolled page result * error.
*/ */
<T> ScrolledPage<SearchHit<T>> searchScrollStart(long scrollTimeInMillis, Query query, Class<T> clazz, <T> CloseableIterator<SearchHit<T>> searchForStream(Query query, Class<T> 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
*/
<T> ScrolledPage<SearchHit<T>> searchScrollContinue(@Nullable String scrollId, long scrollTimeInMillis,
Class<T> clazz);
/**
* Clears the search contexts associated with specified scroll ids.
*
* @param scrollId the scroll id
*/
void searchScrollClear(String scrollId);
/** /**
* Executes the given {@link Query} against elasticsearch and return result as {@link CloseableIterator}. * Executes the given {@link Query} against elasticsearch and return result as {@link CloseableIterator}.
@ -372,13 +363,4 @@ public interface SearchOperations {
* error. * error.
*/ */
<T> CloseableIterator<SearchHit<T>> searchForStream(Query query, Class<T> clazz, IndexCoordinates index); <T> CloseableIterator<SearchHit<T>> searchForStream(Query query, Class<T> 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);
} }

View File

@ -58,7 +58,7 @@ public interface Document extends Map<String, Object> {
* @param map source map containing key-value pairs and sub-documents. must not be {@literal null}. * @param map source map containing key-value pairs and sub-documents. must not be {@literal null}.
* @return a new {@link Document}. * @return a new {@link Document}.
*/ */
static Document from(Map<String, Object> map) { static Document from(Map<String, ? extends Object> map) {
Assert.notNull(map, "Map must not be null"); Assert.notNull(map, "Map must not be null");

View File

@ -46,7 +46,7 @@ class MapDocument implements Document {
this(new LinkedHashMap<>()); this(new LinkedHashMap<>());
} }
MapDocument(Map<String, Object> documentAsMap) { MapDocument(Map<String, ? extends Object> documentAsMap) {
this.documentAsMap = new LinkedHashMap<>(documentAsMap); this.documentAsMap = new LinkedHashMap<>(documentAsMap);
} }

View File

@ -17,6 +17,7 @@ package org.springframework.data.elasticsearch.core.query;
import static java.util.Collections.*; import static java.util.Collections.*;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@ -56,6 +57,7 @@ abstract class AbstractQuery implements Query {
@Nullable protected Integer maxResults; @Nullable protected Integer maxResults;
@Nullable protected HighlightQuery highlightQuery; @Nullable protected HighlightQuery highlightQuery;
private boolean trackTotalHits = false; private boolean trackTotalHits = false;
@Nullable private Duration scrollTime;
@Override @Override
@Nullable @Nullable
@ -226,4 +228,15 @@ abstract class AbstractQuery implements Query {
public boolean getTrackTotalHits() { public boolean getTrackTotalHits() {
return trackTotalHits; return trackTotalHits;
} }
@Nullable
@Override
public Duration getScrollTime() {
return scrollTime;
}
@Override
public void setScrollTime(@Nullable Duration scrollTime) {
this.scrollTime = scrollTime;
}
} }

View File

@ -16,7 +16,6 @@
package org.springframework.data.elasticsearch.core.query; package org.springframework.data.elasticsearch.core.query;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
@ -29,9 +28,7 @@ import org.springframework.util.Assert;
*/ */
public class CriteriaQuery extends AbstractQuery { public class CriteriaQuery extends AbstractQuery {
private @Nullable Criteria criteria; private Criteria criteria;
private CriteriaQuery() {}
public CriteriaQuery(Criteria criteria) { public CriteriaQuery(Criteria criteria) {
this(criteria, Pageable.unpaged()); this(criteria, Pageable.unpaged());
@ -48,7 +45,7 @@ public class CriteriaQuery extends AbstractQuery {
} }
public static Query fromQuery(CriteriaQuery source) { public static Query fromQuery(CriteriaQuery source) {
return fromQuery(source, new CriteriaQuery()); return fromQuery(source, new CriteriaQuery(source.criteria));
} }
public static <T extends CriteriaQuery> T fromQuery(CriteriaQuery source, T destination) { public static <T extends CriteriaQuery> 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(source, "source must not be null");
Assert.notNull(destination, "destination 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) { if (source.getSort() != null) {
destination.addSort(source.getSort()); destination.addSort(source.getSort());
@ -69,16 +64,13 @@ public class CriteriaQuery extends AbstractQuery {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public final <T extends CriteriaQuery> T addCriteria(Criteria criteria) { public final <T extends CriteriaQuery> T addCriteria(Criteria criteria) {
Assert.notNull(criteria, "Cannot add null criteria."); Assert.notNull(criteria, "Cannot add null criteria.");
if (this.criteria == null) {
this.criteria = criteria; this.criteria.and(criteria);
} else {
this.criteria.and(criteria);
}
return (T) this; return (T) this;
} }
@Nullable
public Criteria getCriteria() { public Criteria getCriteria() {
return this.criteria; return this.criteria;
} }

View File

@ -24,7 +24,9 @@ import org.springframework.lang.Nullable;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
* @author Peter-Josef Meisch * @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 { public class DeleteQuery {
@Nullable private QueryBuilder query; @Nullable private QueryBuilder query;

View File

@ -21,7 +21,9 @@ package org.springframework.data.elasticsearch.core.query;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
* @deprecated since 4.0
*/ */
@Deprecated
public class GetQuery { public class GetQuery {
public GetQuery(String id) { public GetQuery(String id) {

View File

@ -69,7 +69,12 @@ public class IndexQuery {
this.source = source; 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 @Nullable
@Deprecated
public String getParentId() { public String getParentId() {
return parentId; return parentId;
} }

View File

@ -94,6 +94,7 @@ public class NativeSearchQuery extends AbstractQuery {
return filter; return filter;
} }
@Nullable
public List<SortBuilder> getElasticsearchSorts() { public List<SortBuilder> getElasticsearchSorts() {
return sorts; return sorts;
} }
@ -103,6 +104,7 @@ public class NativeSearchQuery extends AbstractQuery {
return highlightBuilder; return highlightBuilder;
} }
@Nullable
public HighlightBuilder.Field[] getHighlightFields() { public HighlightBuilder.Field[] getHighlightFields() {
return highlightFields; return highlightFields;
} }

View File

@ -15,6 +15,7 @@
*/ */
package org.springframework.data.elasticsearch.core.query; package org.springframework.data.elasticsearch.core.query;
import java.time.Duration;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -45,7 +46,7 @@ public interface Query {
Pageable DEFAULT_PAGE = PageRequest.of(0, DEFAULT_PAGE_SIZE); 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}. * @return new instance of {@link Query}.
* @since 3.2 * @since 3.2
@ -229,4 +230,29 @@ public interface Query {
* @since 4.0 * @since 4.0
*/ */
boolean getTrackTotalHits(); 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;
}
} }

View File

@ -15,43 +15,168 @@
*/ */
package org.springframework.data.elasticsearch.core.query; 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; import org.springframework.lang.Nullable;
/** /**
* Defines an update request.
*
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
* @author Peter-Josef Meisch * @author Peter-Josef Meisch
* @see <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html>docs</a>
*/ */
public class UpdateQuery { public class UpdateQuery {
@Nullable private String id; private String id;
@Nullable private UpdateRequest updateRequest; @Nullable private String script;
private boolean doUpsert; @Nullable private Map<String, Object> params;
@Nullable private Document document;
@Nullable private Document upsert;
@Nullable private String lang;
@Nullable private String routing;
@Nullable private Boolean scriptedUpsert;
@Nullable private Boolean docAsUpsert;
@Nullable private Boolean fetchSource;
public static Builder builder(String id) {
return new Builder(id);
}
private UpdateQuery(String id, @Nullable String script, @Nullable Map<String, Object> params,
@Nullable Document document, @Nullable Document upsert, @Nullable String lang, @Nullable String routing,
@Nullable Boolean scriptedUpsert, @Nullable Boolean docAsUpsert, @Nullable Boolean fetchSource) {
this.id = id;
this.script = script;
this.params = params;
this.document = document;
this.upsert = upsert;
this.lang = lang;
this.routing = routing;
this.scriptedUpsert = scriptedUpsert;
this.docAsUpsert = docAsUpsert;
this.fetchSource = fetchSource;
}
@Nullable
public String getId() { public String getId() {
return id; return id;
} }
public void setId(String id) { @Nullable
this.id = id; public String getScript() {
return script;
} }
@Nullable @Nullable
public UpdateRequest getUpdateRequest() { public Map<String, Object> getParams() {
return updateRequest; return params;
} }
public void setUpdateRequest(UpdateRequest updateRequest) { @Nullable
this.updateRequest = updateRequest; public Document getDocument() {
return document;
} }
public boolean DoUpsert() { @Nullable
return doUpsert; public Document getUpsert() {
return upsert;
} }
public void setDoUpsert(boolean doUpsert) { @Nullable
this.doUpsert = doUpsert; public String getLang() {
return lang;
}
@Nullable
public String getRouting() {
return routing;
}
@Nullable
public Boolean getScriptedUpsert() {
return scriptedUpsert;
}
@Nullable
public Boolean getDocAsUpsert() {
return docAsUpsert;
}
@Nullable
public Boolean getFetchSource() {
return fetchSource;
}
public static final class Builder {
private String id;
@Nullable private String script = null;
@Nullable private Map<String, Object> params;
@Nullable private Document document = null;
@Nullable private Document upsert = null;
@Nullable private String lang = "painless";
@Nullable private String routing = null;
@Nullable private Boolean scriptedUpsert;
@Nullable private Boolean docAsUpsert;
@Nullable private Boolean fetchSource;
private Builder(String id) {
this.id = id;
}
public Builder withScript(String script) {
this.script = script;
return this;
}
public Builder withParams(Map<String, Object> 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);
}
} }
} }

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -116,7 +116,7 @@ abstract class AbstractReactiveElasticsearchRepositoryQuery implements Repositor
ReactiveElasticsearchOperations operations) { ReactiveElasticsearchOperations operations) {
if (isDeleteQuery()) { 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()) { } else if (isCountQuery()) {
return (query, type, targetType, indexCoordinates) -> operations.count(query, type, indexCoordinates); return (query, type, targetType, indexCoordinates) -> operations.count(query, type, indexCoordinates);
} else if (isExistsQuery()) { } else if (isExistsQuery()) {

View File

@ -82,7 +82,7 @@ public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery
if (tree.isDelete()) { if (tree.isDelete()) {
result = countOrGetDocumentsForDelete(query, accessor); result = countOrGetDocumentsForDelete(query, accessor);
elasticsearchOperations.delete(query, clazz, index); elasticsearchOperations.delete(query, clazz, index);
elasticsearchOperations.getIndexOperations().refresh(index); elasticsearchOperations.indexOps(index).refresh();
} else if (queryMethod.isPageQuery()) { } else if (queryMethod.isPageQuery()) {
query.setPageable(accessor.getPageable()); query.setPageable(accessor.getPageable());
SearchHits<?> searchHits = elasticsearchOperations.search(query, clazz, index); SearchHits<?> searchHits = elasticsearchOperations.search(query, clazz, index);

View File

@ -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.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.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.MoreLikeThisQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
@ -79,23 +76,18 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
protected ElasticsearchOperations operations; protected ElasticsearchOperations operations;
protected IndexOperations indexOperations; protected IndexOperations indexOperations;
protected @Nullable Class<T> entityClass; protected Class<T> entityClass;
protected @Nullable ElasticsearchEntityInformation<T, ID> entityInformation; protected @Nullable ElasticsearchEntityInformation<T, ID> entityInformation;
public AbstractElasticsearchRepository(ElasticsearchOperations operations) {
Assert.notNull(operations, "ElasticsearchOperations must not be null.");
this.operations = operations;
this.indexOperations = operations.getIndexOperations();
}
public AbstractElasticsearchRepository(ElasticsearchEntityInformation<T, ID> metadata, public AbstractElasticsearchRepository(ElasticsearchEntityInformation<T, ID> metadata,
ElasticsearchOperations operations) { ElasticsearchOperations operations) {
this(operations); this.operations = operations;
Assert.notNull(metadata, "ElasticsearchEntityInformation must not be null!"); Assert.notNull(metadata, "ElasticsearchEntityInformation must not be null!");
this.entityInformation = metadata; this.entityInformation = metadata;
setEntityClass(this.entityInformation.getJavaType()); this.entityClass = this.entityInformation.getJavaType();
this.indexOperations = operations.indexOps(this.entityClass);
try { try {
if (createIndexAndMapping()) { if (createIndexAndMapping()) {
createIndex(); createIndex();
@ -107,11 +99,11 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
} }
private void createIndex() { private void createIndex() {
indexOperations.createIndex(getEntityClass()); indexOperations.create();
} }
private void putMapping() { private void putMapping() {
indexOperations.putMapping(getEntityClass()); indexOperations.putMapping(indexOperations.createMapping(entityClass));
} }
private boolean createIndexAndMapping() { private boolean createIndexAndMapping() {
@ -123,8 +115,7 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
@Override @Override
public Optional<T> findById(ID id) { public Optional<T> findById(ID id) {
GetQuery query = new GetQuery(stringIdRepresentation(id)); return Optional.ofNullable(operations.get(stringIdRepresentation(id), getEntityClass(), getIndexCoordinates()));
return Optional.ofNullable(operations.get(query, getEntityClass(), getIndexCoordinates()));
} }
@Override @Override
@ -180,7 +171,7 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
Assert.notNull(entity, "Cannot save 'null' entity."); Assert.notNull(entity, "Cannot save 'null' entity.");
operations.save(entity, getIndexCoordinates()); operations.save(entity, getIndexCoordinates());
indexOperations.refresh(getIndexCoordinates()); operations.indexOps(entity.getClass()).refresh();
return entity; return entity;
} }
@ -203,15 +194,16 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
Assert.notNull(entities, "Cannot insert 'null' as a List."); Assert.notNull(entities, "Cannot insert 'null' as a List.");
operations.save(entities, getIndexCoordinates()); IndexCoordinates indexCoordinates = getIndexCoordinates();
indexOperations.refresh(getIndexCoordinates()); operations.save(entities, indexCoordinates);
operations.indexOps(indexCoordinates).refresh();
return entities; return entities;
} }
@Override @Override
public boolean existsById(ID id) { public boolean existsById(ID id) {
return findById(id).isPresent(); return operations.exists(stringIdRepresentation(id), getIndexCoordinates());
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -273,7 +265,7 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
IndexCoordinates indexCoordinates = getIndexCoordinates(); IndexCoordinates indexCoordinates = getIndexCoordinates();
doDelete(id, indexCoordinates); doDelete(id, indexCoordinates);
indexOperations.refresh(indexCoordinates); indexOperations.refresh();
} }
@Override @Override
@ -283,7 +275,7 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
IndexCoordinates indexCoordinates = getIndexCoordinates(); IndexCoordinates indexCoordinates = getIndexCoordinates();
doDelete(extractIdFromBean(entity), indexCoordinates); doDelete(extractIdFromBean(entity), indexCoordinates);
indexOperations.refresh(indexCoordinates); indexOperations.refresh();
} }
@Override @Override
@ -303,11 +295,11 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
if (idsQueryBuilder.ids().isEmpty()) { if (idsQueryBuilder.ids().isEmpty()) {
return; return;
} }
DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(idsQueryBuilder);
operations.delete(deleteQuery, indexCoordinates); Query query = new NativeSearchQueryBuilder().withQuery(idsQueryBuilder).build();
indexOperations.refresh(indexCoordinates);
operations.delete(query, getEntityClass(), indexCoordinates);
indexOperations.refresh();
} }
private void doDelete(@Nullable ID id, IndexCoordinates indexCoordinates) { private void doDelete(@Nullable ID id, IndexCoordinates indexCoordinates) {
@ -318,19 +310,18 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
@Override @Override
public void deleteAll() { public void deleteAll() {
DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(matchAllQuery());
IndexCoordinates indexCoordinates = getIndexCoordinates(); IndexCoordinates indexCoordinates = getIndexCoordinates();
operations.delete(deleteQuery, indexCoordinates); Query query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
indexOperations.refresh(indexCoordinates);
operations.delete(query, getEntityClass(), indexCoordinates);
indexOperations.refresh();
} }
@Override @Override
public void refresh() { public void refresh() {
indexOperations.refresh(getEntityClass()); indexOperations.refresh();
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Class<T> resolveReturnedClassFromGenericType() { private Class<T> resolveReturnedClassFromGenericType() {
ParameterizedType parameterizedType = resolveReturnedClassFromGenericType(getClass()); ParameterizedType parameterizedType = resolveReturnedClassFromGenericType(getClass());
@ -367,11 +358,6 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
return entityClass != null; return entityClass != null;
} }
public final void setEntityClass(Class<T> entityClass) {
Assert.notNull(entityClass, "EntityClass must not be null.");
this.entityClass = entityClass;
}
@Nullable @Nullable
protected ID extractIdFromBean(T entity) { protected ID extractIdFromBean(T entity) {
return entityInformation.getId(entity); return entityInformation.getId(entity);
@ -389,7 +375,6 @@ public abstract class AbstractElasticsearchRepository<T, ID> implements Elastics
protected abstract @Nullable String stringIdRepresentation(@Nullable ID id); protected abstract @Nullable String stringIdRepresentation(@Nullable ID id);
private IndexCoordinates getIndexCoordinates() { private IndexCoordinates getIndexCoordinates() {
return operations.getIndexCoordinatesFor(getEntityClass()); return operations.getIndexCoordinatesFor(getEntityClass());
} }

View File

@ -35,10 +35,6 @@ public class SimpleElasticsearchRepository<T, ID> extends AbstractElasticsearchR
super(metadata, elasticsearchOperations); super(metadata, elasticsearchOperations);
} }
public SimpleElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
super(elasticsearchOperations);
}
@Override @Override
protected @Nullable String stringIdRepresentation(@Nullable ID id) { protected @Nullable String stringIdRepresentation(@Nullable ID id) {
return operations.stringIdRepresentation(id); return operations.stringIdRepresentation(id);

View File

@ -79,7 +79,7 @@ public class SimpleReactiveElasticsearchRepository<T, ID> implements ReactiveEla
public Mono<T> findById(ID id) { public Mono<T> findById(ID id) {
Assert.notNull(id, "Id must not be null!"); Assert.notNull(id, "Id must not be null!");
return elasticsearchOperations.findById(convertId(id), entityInformation.getJavaType(), return elasticsearchOperations.get(convertId(id), entityInformation.getJavaType(),
entityInformation.getIndexCoordinates()); entityInformation.getIndexCoordinates());
} }
@ -154,7 +154,7 @@ public class SimpleReactiveElasticsearchRepository<T, ID> implements ReactiveEla
Assert.notNull(id, "Id must not be null!"); Assert.notNull(id, "Id must not be null!");
return elasticsearchOperations return elasticsearchOperations
.deleteById(convertId(id), entityInformation.getJavaType(), entityInformation.getIndexCoordinates()) // .delete(convertId(id), entityInformation.getIndexCoordinates()) //
.then(); .then();
} }
@ -200,7 +200,7 @@ public class SimpleReactiveElasticsearchRepository<T, ID> implements ReactiveEla
}) // }) //
.flatMap(query -> { .flatMap(query -> {
return elasticsearchOperations.deleteBy(query, entityInformation.getJavaType(), return elasticsearchOperations.delete(query, entityInformation.getJavaType(),
entityInformation.getIndexCoordinates()); entityInformation.getIndexCoordinates());
}) // }) //
.then(); .then();
@ -210,7 +210,7 @@ public class SimpleReactiveElasticsearchRepository<T, ID> implements ReactiveEla
public Mono<Void> deleteAll() { public Mono<Void> deleteAll() {
return elasticsearchOperations return elasticsearchOperations
.deleteBy(Query.findAll(), entityInformation.getJavaType(), entityInformation.getIndexCoordinates()) // .delete(Query.findAll(), entityInformation.getJavaType(), entityInformation.getIndexCoordinates()) //
.then(); .then();
} }

View File

@ -30,6 +30,7 @@ import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import org.apache.lucene.search.join.ScoreMode; import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder; 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.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
@ -68,13 +67,12 @@ import org.springframework.test.context.ContextConfiguration;
public class NestedObjectTests { public class NestedObjectTests {
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, Book.class); IndexInitializer.init(operations.indexOps(Book.class));
IndexInitializer.init(indexOperations, Person.class); IndexInitializer.init(operations.indexOps(Person.class));
IndexInitializer.init(indexOperations, PersonMultipleLevelNested.class); IndexInitializer.init(operations.indexOps(PersonMultipleLevelNested.class));
} }
@Test @Test
@ -126,7 +124,7 @@ public class NestedObjectTests {
IndexCoordinates index = IndexCoordinates.of("test-index-person").withTypes("user"); IndexCoordinates index = IndexCoordinates.of("test-index-person").withTypes("user");
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(Person.class); operations.indexOps(Person.class).refresh();
QueryBuilder builder = nestedQuery("car", QueryBuilder builder = nestedQuery("car",
boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None); boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None);
@ -146,11 +144,10 @@ public class NestedObjectTests {
// when // when
operations.bulkIndex(indexQueries, operations.bulkIndex(indexQueries,
IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user")); IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user"));
indexOperations.refresh(PersonMultipleLevelNested.class); operations.indexOps(PersonMultipleLevelNested.class).refresh();
// then // then
GetQuery getQuery = new GetQuery("1"); PersonMultipleLevelNested personIndexed = operations.get("1", PersonMultipleLevelNested.class,
PersonMultipleLevelNested personIndexed = operations.get(getQuery, PersonMultipleLevelNested.class,
IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user")); IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user"));
assertThat(personIndexed).isNotNull(); assertThat(personIndexed).isNotNull();
} }
@ -166,7 +163,7 @@ public class NestedObjectTests {
IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user")); IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user"));
// then // then
Map<String, Object> mapping = indexOperations.getMapping(PersonMultipleLevelNested.class); Map<String, Object> mapping = operations.indexOps(PersonMultipleLevelNested.class).getMapping();
assertThat(mapping).isNotNull(); assertThat(mapping).isNotNull();
Map<String, Object> propertyMap = (Map<String, Object>) mapping.get("properties"); Map<String, Object> propertyMap = (Map<String, Object>) mapping.get("properties");
@ -184,7 +181,7 @@ public class NestedObjectTests {
// when // when
IndexCoordinates index = IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user"); IndexCoordinates index = IndexCoordinates.of("test-index-person-multiple-level-nested").withTypes("user");
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(PersonMultipleLevelNested.class); operations.indexOps(PersonMultipleLevelNested.class).refresh();
// then // then
BoolQueryBuilder builder = boolQuery(); BoolQueryBuilder builder = boolQuery();
@ -324,7 +321,7 @@ public class NestedObjectTests {
IndexCoordinates index = IndexCoordinates.of("test-index-person").withTypes("user"); IndexCoordinates index = IndexCoordinates.of("test-index-person").withTypes("user");
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(Person.class); operations.indexOps(Person.class).refresh();
// when // when
QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")), ScoreMode.None); QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")), ScoreMode.None);
@ -373,7 +370,7 @@ public class NestedObjectTests {
// when // when
IndexCoordinates index = IndexCoordinates.of("test-index-book-nested-objects").withTypes("book"); IndexCoordinates index = IndexCoordinates.of("test-index-book-nested-objects").withTypes("book");
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(Book.class); operations.indexOps(Book.class).refresh();
// then // then
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()

View File

@ -39,6 +39,7 @@ import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.Score; import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField; import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration;
@ -74,17 +75,19 @@ public class EnableElasticsearchRepositoriesTests implements ApplicationContextA
@EnableElasticsearchRepositories @EnableElasticsearchRepositories
static class Config {} static class Config {}
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@Autowired private SampleElasticsearchRepository repository; @Autowired private SampleElasticsearchRepository repository;
@Autowired(required = false) private SampleRepository nestedRepository; @Autowired(required = false) private SampleRepository nestedRepository;
interface SampleRepository extends Repository<EnableElasticsearchRepositoriesTests.SampleEntity, Long> {} interface SampleRepository extends Repository<SampleEntity, Long> {}
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, SampleEntity.class); indexOperations = operations.indexOps(SampleEntity.class);
IndexInitializer.init(indexOperations);
} }
@Test @Test

View File

@ -23,14 +23,11 @@ import lombok.Builder;
import lombok.Data; import lombok.Data;
import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.query.UpdateQuery; 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.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
@ -57,16 +54,15 @@ public class ElasticsearchRestTemplateTests extends ElasticsearchTemplateTests {
public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() { public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() {
// when // when
IndexRequest indexRequest = new IndexRequest(); org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document
indexRequest.source("{}", XContentType.JSON); .create();
UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)).withIndexRequest(indexRequest).build(); UpdateQuery updateQuery = UpdateQuery.builder(randomNumeric(5)).withDocument(document).build();
assertThatThrownBy(() -> operations.update(updateQuery, index)).isInstanceOf(ElasticsearchStatusException.class); assertThatThrownBy(() -> operations.update(updateQuery, index)).isInstanceOf(ElasticsearchStatusException.class);
} }
@Data @Data
@Builder @Builder
@Document(indexName = "test-index-sample-core-rest-template", replicas = 0, @Document(indexName = "test-index-sample-core-rest-template", replicas = 0, refreshInterval = "-1")
refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {
@Id private String id; @Id private String id;

View File

@ -21,10 +21,8 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.Data; import lombok.Data;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.Client; import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.engine.DocumentMissingException; import org.elasticsearch.index.engine.DocumentMissingException;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -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.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.UpdateQuery; 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.ElasticsearchTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
@ -56,9 +53,9 @@ public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTe
@Test @Test
public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() { public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() {
// when // when
IndexRequest indexRequest = new IndexRequest(); org.springframework.data.elasticsearch.core.document.Document document = org.springframework.data.elasticsearch.core.document.Document
indexRequest.source("{}", XContentType.JSON); .create();
UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)).withIndexRequest(indexRequest).build(); UpdateQuery updateQuery = UpdateQuery.builder(randomNumeric(5)).withDocument(document).build();
assertThatThrownBy(() -> operations.update(updateQuery, index)).isInstanceOf(DocumentMissingException.class); assertThatThrownBy(() -> operations.update(updateQuery, index)).isInstanceOf(DocumentMissingException.class);
} }
@ -87,8 +84,7 @@ public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTe
} }
@Data @Data
@Document(indexName = "test-index-sample-core-transport-template", replicas = 0, @Document(indexName = "test-index-sample-core-transport-template", replicas = 0, refreshInterval = "-1")
refreshInterval = "-1")
static class SampleEntity { static class SampleEntity {
@Id private String id; @Id private String id;

View File

@ -62,11 +62,12 @@ public class LogEntityTests {
private final IndexCoordinates index = IndexCoordinates.of("test-index-log-core").withTypes("test-log-type"); private final IndexCoordinates index = IndexCoordinates.of("test-index-log-core").withTypes("test-log-type");
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations; private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() throws ParseException { 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"); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
IndexQuery indexQuery1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse("2013-10-18 18:01")) IndexQuery indexQuery1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse("2013-10-18 18:01"))
@ -82,12 +83,12 @@ public class LogEntityTests {
.code(2).ip("10.10.10.4").buildIndex(); .code(2).ip("10.10.10.4").buildIndex();
operations.bulkIndex(Arrays.asList(indexQuery1, indexQuery2, indexQuery3, indexQuery4), index); operations.bulkIndex(Arrays.asList(indexQuery1, indexQuery2, indexQuery3, indexQuery4), index);
indexOperations.refresh(LogEntity.class); indexOperations.refresh();
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(LogEntity.class); indexOperations.delete();
} }
@Test // DATAES-66 @Test // DATAES-66

View File

@ -40,7 +40,6 @@ import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach; 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.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.StringQuery; import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQuery; 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.junit4.ElasticsearchVersion;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@ -89,16 +87,18 @@ public class ReactiveElasticsearchTemplateTests {
private ElasticsearchRestTemplate restTemplate; private ElasticsearchRestTemplate restTemplate;
private ReactiveElasticsearchTemplate template; private ReactiveElasticsearchTemplate template;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void setUp() { public void setUp() {
restTemplate = new ElasticsearchRestTemplate(TestUtils.restHighLevelClient());
indexOperations = restTemplate.indexOps(SampleEntity.class);
deleteIndices(); deleteIndices();
restTemplate = new ElasticsearchRestTemplate(TestUtils.restHighLevelClient()); indexOperations.create();
restTemplate.createIndex(SampleEntity.class); indexOperations.putMapping(indexOperations.createMapping(SampleEntity.class));
restTemplate.putMapping(SampleEntity.class); indexOperations.refresh();
restTemplate.refresh(SampleEntity.class);
template = new ReactiveElasticsearchTemplate(TestUtils.reactiveClient(), restTemplate.getElasticsearchConverter()); template = new ReactiveElasticsearchTemplate(TestUtils.reactiveClient(), restTemplate.getElasticsearchConverter());
} }
@ -142,7 +142,7 @@ public class ReactiveElasticsearchTemplateTests {
.expectNextCount(1)// .expectNextCount(1)//
.verifyComplete(); .verifyComplete();
restTemplate.refresh(SampleEntity.class); indexOperations.refresh();
SearchHits<SampleEntity> result = restTemplate.search( SearchHits<SampleEntity> result = restTemplate.search(
new CriteriaQuery(Criteria.where("message").is(sampleEntity.getMessage())), SampleEntity.class, new CriteriaQuery(Criteria.where("message").is(sampleEntity.getMessage())), SampleEntity.class,
@ -161,7 +161,7 @@ public class ReactiveElasticsearchTemplateTests {
assertThat(it.getId()).isNotNull(); assertThat(it.getId()).isNotNull();
restTemplate.refresh(SampleEntity.class); indexOperations.refresh();
assertThat(TestUtils.documentWithId(it.getId()).existsIn(DEFAULT_INDEX)).isTrue(); assertThat(TestUtils.documentWithId(it.getId()).existsIn(DEFAULT_INDEX)).isTrue();
}) // }) //
.verifyComplete(); .verifyComplete();
@ -205,27 +205,27 @@ public class ReactiveElasticsearchTemplateTests {
} }
@Test // DATAES-519 @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) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
} }
@Test // DATAES-504 @Test // DATAES-504
public void findByIdShouldReturnEntity() { public void getByIdShouldReturnEntity() {
SampleEntity sampleEntity = randomEntity("some message"); SampleEntity sampleEntity = randomEntity("some message");
index(sampleEntity); index(sampleEntity);
template.findById(sampleEntity.getId(), SampleEntity.class) // template.get(sampleEntity.getId(), SampleEntity.class) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.expectNext(sampleEntity) // .expectNext(sampleEntity) //
.verifyComplete(); .verifyComplete();
} }
@Test // DATAES-504 @Test // DATAES-504
public void findByIdWhenIdIsAutogeneratedShouldHaveIdSetCorrectly() { public void getByIdWhenIdIsAutogeneratedShouldHaveIdSetCorrectly() {
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
@ -234,32 +234,32 @@ public class ReactiveElasticsearchTemplateTests {
assertThat(sampleEntity.getId()).isNotNull(); assertThat(sampleEntity.getId()).isNotNull();
template.findById(sampleEntity.getId(), SampleEntity.class) // template.get(sampleEntity.getId(), SampleEntity.class) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.consumeNextWith(it -> assertThat(it.getId()).isEqualTo(sampleEntity.getId())) // .consumeNextWith(it -> assertThat(it.getId()).isEqualTo(sampleEntity.getId())) //
.verifyComplete(); .verifyComplete();
} }
@Test // DATAES-504 @Test // DATAES-504
public void findByIdShouldCompleteWhenNotingFound() { public void getByIdShouldCompleteWhenNotingFound() {
SampleEntity sampleEntity = randomEntity("some message"); SampleEntity sampleEntity = randomEntity("some message");
index(sampleEntity); index(sampleEntity);
template.findById("foo", SampleEntity.class) // template.get("foo", SampleEntity.class) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
} }
@Test // DATAES-504 @Test // DATAES-504
public void findByIdShouldErrorForNullId() { public void getByIdShouldErrorForNullId() {
assertThatThrownBy(() -> { assertThatThrownBy(() -> {
template.findById(null, SampleEntity.class); template.get(null, SampleEntity.class);
}).isInstanceOf(IllegalArgumentException.class); }).isInstanceOf(IllegalArgumentException.class);
} }
@Test // DATAES-504 @Test // DATAES-504
public void findByIdWithExplicitIndexNameShouldOverwriteMetadata() { public void getByIdWithExplicitIndexNameShouldOverwriteMetadata() {
SampleEntity sampleEntity = randomEntity("some message"); SampleEntity sampleEntity = randomEntity("some message");
@ -269,16 +269,16 @@ public class ReactiveElasticsearchTemplateTests {
IndexCoordinates alternateIndex = IndexCoordinates.of(ALTERNATE_INDEX).withTypes("test-type"); IndexCoordinates alternateIndex = IndexCoordinates.of(ALTERNATE_INDEX).withTypes("test-type");
restTemplate.index(indexQuery, alternateIndex); restTemplate.index(indexQuery, alternateIndex);
restTemplate.refresh(SampleEntity.class); indexOperations.refresh();
restTemplate.refresh(defaultIndex); restTemplate.indexOps(defaultIndex).refresh();
restTemplate.refresh(alternateIndex); restTemplate.indexOps(alternateIndex).refresh();
template.findById(sampleEntity.getId(), SampleEntity.class, defaultIndex) // template.get(sampleEntity.getId(), SampleEntity.class, defaultIndex) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
template.findById(sampleEntity.getId(), SampleEntity.class, alternateIndex) // template.get(sampleEntity.getId(), SampleEntity.class, alternateIndex) //
.as(StepVerifier::create)// .as(StepVerifier::create)//
.expectNextCount(1) // .expectNextCount(1) //
.verifyComplete(); .verifyComplete();
@ -520,20 +520,20 @@ public class ReactiveElasticsearchTemplateTests {
} }
@Test // DATAES-519 @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)// .as(StepVerifier::create)//
.verifyComplete(); .verifyComplete();
} }
@Test // DATAES-504 @Test // DATAES-504
public void deleteByIdShouldRemoveExistingDocumentById() { public void deleteShouldRemoveExistingDocumentById() {
SampleEntity sampleEntity = randomEntity("test message"); SampleEntity sampleEntity = randomEntity("test message");
index(sampleEntity); index(sampleEntity);
template.deleteById(sampleEntity.getId(), SampleEntity.class) // template.delete(sampleEntity.getId(), SampleEntity.class) //
.as(StepVerifier::create)// .as(StepVerifier::create)//
.expectNext(sampleEntity.getId()) // .expectNext(sampleEntity.getId()) //
.verifyComplete(); .verifyComplete();
@ -545,7 +545,7 @@ public class ReactiveElasticsearchTemplateTests {
SampleEntity sampleEntity = randomEntity("test message"); SampleEntity sampleEntity = randomEntity("test message");
index(sampleEntity); 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)// .as(StepVerifier::create)//
.expectNext(sampleEntity.getId()) // .expectNext(sampleEntity.getId()) //
.verifyComplete(); .verifyComplete();
@ -564,7 +564,7 @@ public class ReactiveElasticsearchTemplateTests {
} }
@Test // DATAES-504 @Test // DATAES-504
public void deleteByIdShouldCompleteWhenNothingDeleted() { public void deleteShouldCompleteWhenNothingDeleted() {
SampleEntity sampleEntity = randomEntity("test message"); SampleEntity sampleEntity = randomEntity("test message");
@ -579,7 +579,7 @@ public class ReactiveElasticsearchTemplateTests {
CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("test")); CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("test"));
template.deleteBy(query, SampleEntity.class) // template.delete(query, SampleEntity.class) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.expectNext(0L) // .expectNext(0L) //
.verifyComplete(); .verifyComplete();
@ -606,7 +606,7 @@ public class ReactiveElasticsearchTemplateTests {
.withQuery(termQuery("message", "test")) // .withQuery(termQuery("message", "test")) //
.build(); .build();
template.deleteBy(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) // template.delete(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.expectNext(2L) // .expectNext(2L) //
.verifyComplete(); .verifyComplete();
@ -635,7 +635,7 @@ public class ReactiveElasticsearchTemplateTests {
.withQuery(termQuery("message", "negative")) // .withQuery(termQuery("message", "negative")) //
.build(); .build();
template.deleteBy(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) // template.delete(searchQuery, SampleEntity.class, IndexCoordinates.of(indexPrefix + '*')) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.expectNext(0L) // .expectNext(0L) //
.verifyComplete(); .verifyComplete();
@ -651,7 +651,7 @@ public class ReactiveElasticsearchTemplateTests {
CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("test")); CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("test"));
template.deleteBy(query, SampleEntity.class) // template.delete(query, SampleEntity.class) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.expectNext(2L) // .expectNext(2L) //
.verifyComplete(); .verifyComplete();
@ -665,7 +665,7 @@ public class ReactiveElasticsearchTemplateTests {
CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("luke")); CriteriaQuery query = new CriteriaQuery(new Criteria("message").contains("luke"));
template.deleteBy(query, SampleEntity.class) // template.delete(query, SampleEntity.class) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.expectNext(0L) // .expectNext(0L) //
.verifyComplete(); .verifyComplete();
@ -763,17 +763,19 @@ public class ReactiveElasticsearchTemplateTests {
entity2.rate = 2; entity2.rate = 2;
index(entity2); index(entity2);
IndexRequest indexRequest1 = new IndexRequest(); org.springframework.data.elasticsearch.core.document.Document document1 = org.springframework.data.elasticsearch.core.document.Document
indexRequest1.source("message", "updated 1"); .create();
UpdateQuery updateQuery1 = new UpdateQueryBuilder() // document1.put("message", "updated 1");
.withId(entity1.getId()) // UpdateQuery updateQuery1 = UpdateQuery.builder(entity1.getId()) //
.withIndexRequest(indexRequest1).build(); .withDocument(document1) //
.build();
IndexRequest indexRequest2 = new IndexRequest(); org.springframework.data.elasticsearch.core.document.Document document2 = org.springframework.data.elasticsearch.core.document.Document
indexRequest2.source("message", "updated 2"); .create();
UpdateQuery updateQuery2 = new UpdateQueryBuilder() // document2.put("message", "updated 2");
.withId(entity2.getId()) // UpdateQuery updateQuery2 = UpdateQuery.builder(entity2.getId()) //
.withIndexRequest(indexRequest2).build(); .withDocument(document2) //
.build();
List<UpdateQuery> queries = Arrays.asList(updateQuery1, updateQuery2); List<UpdateQuery> queries = Arrays.asList(updateQuery1, updateQuery2);
template.bulkUpdate(queries, IndexCoordinates.of(DEFAULT_INDEX)).block(); template.bulkUpdate(queries, IndexCoordinates.of(DEFAULT_INDEX)).block();
@ -858,7 +860,7 @@ public class ReactiveElasticsearchTemplateTests {
restTemplate.bulkIndex(getIndexQueries(entities), indexCoordinates); restTemplate.bulkIndex(getIndexQueries(entities), indexCoordinates);
} }
restTemplate.refresh(SampleEntity.class); indexOperations.refresh();
} }
@Data @Data

View File

@ -170,7 +170,7 @@ public class ReactiveElasticsearchTemplateUnitTests {
ArgumentCaptor<DeleteRequest> captor = ArgumentCaptor.forClass(DeleteRequest.class); ArgumentCaptor<DeleteRequest> captor = ArgumentCaptor.forClass(DeleteRequest.class);
when(client.delete(captor.capture())).thenReturn(Mono.empty()); when(client.delete(captor.capture())).thenReturn(Mono.empty());
template.deleteById("id", index) // template.delete("id", index) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
@ -185,7 +185,7 @@ public class ReactiveElasticsearchTemplateUnitTests {
template.setRefreshPolicy(RefreshPolicy.WAIT_UNTIL); template.setRefreshPolicy(RefreshPolicy.WAIT_UNTIL);
template.deleteById("id", index) // template.delete("id", index) //
.as(StepVerifier::create) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
@ -198,7 +198,7 @@ public class ReactiveElasticsearchTemplateUnitTests {
ArgumentCaptor<DeleteByQueryRequest> captor = ArgumentCaptor.forClass(DeleteByQueryRequest.class); ArgumentCaptor<DeleteByQueryRequest> captor = ArgumentCaptor.forClass(DeleteByQueryRequest.class);
when(client.deleteBy(captor.capture())).thenReturn(Mono.empty()); 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) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
@ -213,7 +213,7 @@ public class ReactiveElasticsearchTemplateUnitTests {
template.setRefreshPolicy(RefreshPolicy.NONE); 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) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
@ -226,7 +226,7 @@ public class ReactiveElasticsearchTemplateUnitTests {
ArgumentCaptor<DeleteByQueryRequest> captor = ArgumentCaptor.forClass(DeleteByQueryRequest.class); ArgumentCaptor<DeleteByQueryRequest> captor = ArgumentCaptor.forClass(DeleteByQueryRequest.class);
when(client.deleteBy(captor.capture())).thenReturn(Mono.empty()); 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) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();
@ -241,7 +241,7 @@ public class ReactiveElasticsearchTemplateUnitTests {
template.setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN); 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) // .as(StepVerifier::create) //
.verifyComplete(); .verifyComplete();

View File

@ -77,11 +77,12 @@ public class ElasticsearchTemplateAggregationTests {
static final String INDEX_NAME = "test-index-articles-core-aggregation"; static final String INDEX_NAME = "test-index-articles-core-aggregation";
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations; private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { 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") IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").subject("computing")
.addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10) .addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10)
@ -101,12 +102,12 @@ public class ElasticsearchTemplateAggregationTests {
operations.index(article2, index); operations.index(article2, index);
operations.index(article3, index); operations.index(article3, index);
operations.index(article4, index); operations.index(article4, index);
operations.refresh(ArticleEntity.class); indexOperations.refresh();
} }
@AfterEach @AfterEach
public void after() { public void after() {
indexOperations.deleteIndex(ArticleEntity.class); indexOperations.delete();
} }
@Test @Test

View File

@ -37,7 +37,6 @@ import org.springframework.data.elasticsearch.annotations.CompletionField;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.AbstractElasticsearchTemplate; import org.springframework.data.elasticsearch.core.AbstractElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
@ -63,18 +62,17 @@ public class ElasticsearchTemplateCompletionTests {
static class Config {} static class Config {}
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations;
@BeforeEach @BeforeEach
private void setup() { private void setup() {
IndexInitializer.init(indexOperations, CompletionEntity.class); IndexInitializer.init(operations.indexOps(CompletionEntity.class));
IndexInitializer.init(indexOperations, AnnotatedCompletionEntity.class); IndexInitializer.init(operations.indexOps(AnnotatedCompletionEntity.class));
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex("test-index-annotated-completion"); operations.indexOps(CompletionEntity.class).delete();
indexOperations.deleteIndex("test-index-core-completion"); operations.indexOps(AnnotatedCompletionEntity.class).delete();
} }
private void loadCompletionObjectEntities() { private void loadCompletionObjectEntities() {
@ -90,7 +88,7 @@ public class ElasticsearchTemplateCompletionTests {
.buildIndex()); .buildIndex());
operations.bulkIndex(indexQueries, IndexCoordinates.of("test-index-core-completion").withTypes("completion-type")); operations.bulkIndex(indexQueries, IndexCoordinates.of("test-index-core-completion").withTypes("completion-type"));
operations.refresh(CompletionEntity.class); operations.indexOps(CompletionEntity.class).refresh();
} }
private void loadAnnotatedCompletionObjectEntities() { private void loadAnnotatedCompletionObjectEntities() {
@ -111,7 +109,7 @@ public class ElasticsearchTemplateCompletionTests {
operations.bulkIndex(indexQueries, operations.bulkIndex(indexQueries,
IndexCoordinates.of("test-index-annotated-completion").withTypes("annotated-completion-type")); IndexCoordinates.of("test-index-annotated-completion").withTypes("annotated-completion-type"));
operations.refresh(AnnotatedCompletionEntity.class); operations.indexOps(AnnotatedCompletionEntity.class).refresh();
} }
private void loadAnnotatedCompletionObjectEntitiesWithWeights() { private void loadAnnotatedCompletionObjectEntitiesWithWeights() {
@ -128,7 +126,7 @@ public class ElasticsearchTemplateCompletionTests {
operations.bulkIndex(indexQueries, operations.bulkIndex(indexQueries,
IndexCoordinates.of("test-index-annotated-completion").withTypes("annotated-completion-type")); IndexCoordinates.of("test-index-annotated-completion").withTypes("annotated-completion-type"));
operations.refresh(AnnotatedCompletionEntity.class); operations.indexOps(AnnotatedCompletionEntity.class).refresh();
} }
@Test @Test

View File

@ -67,21 +67,22 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
static class Config {} static class Config {}
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations; private IndexOperations indexOperations;
@BeforeEach @BeforeEach
void setup() { void setup() {
indexOperations.deleteIndex(ContextCompletionEntity.class); indexOperations = operations.indexOps(ContextCompletionEntity.class);
indexOperations.delete();
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(ContextCompletionEntity.class); indexOperations.delete();
} }
private void loadContextCompletionObjectEntities() { private void loadContextCompletionObjectEntities() {
IndexInitializer.init(indexOperations, ContextCompletionEntity.class); IndexInitializer.init(indexOperations);
NonDocumentEntity nonDocumentEntity = new NonDocumentEntity(); NonDocumentEntity nonDocumentEntity = new NonDocumentEntity();
nonDocumentEntity.setSomeField1("foo"); nonDocumentEntity.setSomeField1("foo");
@ -111,7 +112,7 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
operations.bulkIndex(indexQueries, operations.bulkIndex(indexQueries,
IndexCoordinates.of("test-index-context-completion").withTypes("context-completion-type")); IndexCoordinates.of("test-index-context-completion").withTypes("context-completion-type"));
operations.refresh(ContextCompletionEntity.class); operations.indexOps(ContextCompletionEntity.class).refresh();
} }
@Test // DATAES-536 @Test // DATAES-536

View File

@ -39,7 +39,6 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField; import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit; import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates; import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
@ -78,18 +77,17 @@ public class ElasticsearchTemplateGeoTests {
.withTypes("geo-class-point-type"); .withTypes("geo-class-point-type");
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, AuthorMarkerEntity.class); IndexInitializer.init(operations.indexOps(AuthorMarkerEntity.class));
IndexInitializer.init(indexOperations, LocationMarkerEntity.class); IndexInitializer.init(operations.indexOps(LocationMarkerEntity.class));
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(AuthorMarkerEntity.class); operations.indexOps(AuthorMarkerEntity.class).delete();
indexOperations.deleteIndex(LocationMarkerEntity.class); operations.indexOps(LocationMarkerEntity.class).delete();
} }
private void loadClassBaseEntities() { 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("2").name("Mohsin Husen").location(51.5171d, 0.1062d).buildIndex());
indexQueries.add(new AuthorMarkerEntityBuilder("3").name("Rizwan Idrees").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.bulkIndex(indexQueries, authorMarkerIndex);
operations.refresh(AuthorMarkerEntity.class); operations.indexOps(AuthorMarkerEntity.class).refresh();
} }
private void loadAnnotationBaseEntities() { private void loadAnnotationBaseEntities() {
@ -132,7 +130,7 @@ public class ElasticsearchTemplateGeoTests {
indexQueries.add(buildIndex(location3)); indexQueries.add(buildIndex(location3));
operations.bulkIndex(indexQueries, locationMarkerIndex); operations.bulkIndex(indexQueries, locationMarkerIndex);
operations.refresh(LocationMarkerEntity.class); operations.indexOps(LocationMarkerEntity.class).refresh();
} }
@Test @Test

View File

@ -84,28 +84,27 @@ import org.springframework.test.context.ContextConfiguration;
public class MappingBuilderTests extends MappingContextBaseTests { public class MappingBuilderTests extends MappingContextBaseTests {
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations; private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
indexOperations = operations.indexOps(SimpleRecursiveEntity.class);
indexOperations.deleteIndex(StockPrice.class); indexOperations.delete();
indexOperations.deleteIndex(SimpleRecursiveEntity.class); operations.indexOps(StockPrice.class).delete();
indexOperations.deleteIndex(StockPrice.class); operations.indexOps(SampleInheritedEntity.class).delete();
indexOperations.deleteIndex(SampleInheritedEntity.class); operations.indexOps(User.class).delete();
indexOperations.deleteIndex(User.class); operations.indexOps(Group.class).delete();
indexOperations.deleteIndex(Group.class); operations.indexOps(Book.class).delete();
indexOperations.deleteIndex(Book.class); operations.indexOps(NormalizerEntity.class).delete();
indexOperations.deleteIndex(NormalizerEntity.class); operations.indexOps(CopyToEntity.class).delete();
indexOperations.deleteIndex(CopyToEntity.class);
} }
@Test @Test
public void shouldNotFailOnCircularReference() { public void shouldNotFailOnCircularReference() {
indexOperations.createIndex(SimpleRecursiveEntity.class); operations.indexOps(SimpleRecursiveEntity.class).create();
indexOperations.putMapping(SimpleRecursiveEntity.class); indexOperations.putMapping(indexOperations.createMapping(SimpleRecursiveEntity.class));
indexOperations.refresh(SimpleRecursiveEntity.class); indexOperations.refresh();
} }
@Test // DATAES-568 @Test // DATAES-568
@ -136,10 +135,11 @@ public class MappingBuilderTests extends MappingContextBaseTests {
public void shouldAddStockPriceDocumentToIndex() { public void shouldAddStockPriceDocumentToIndex() {
// Given // Given
IndexOperations indexOps = operations.indexOps(StockPrice.class);
// When // When
indexOperations.createIndex(StockPrice.class); indexOps.create();
indexOperations.putMapping(StockPrice.class); indexOps.putMapping(indexOps.createMapping(StockPrice.class));
String symbol = "AU"; String symbol = "AU";
double price = 2.34; double price = 2.34;
String id = "abc"; String id = "abc";
@ -150,7 +150,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
.symbol(symbol) // .symbol(symbol) //
.price(BigDecimal.valueOf(price)) // .price(BigDecimal.valueOf(price)) //
.build()), index); .build()), index);
indexOperations.refresh(StockPrice.class); operations.indexOps(StockPrice.class).refresh();
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
SearchHits<StockPrice> result = operations.search(searchQuery, StockPrice.class, index); SearchHits<StockPrice> result = operations.search(searchQuery, StockPrice.class, index);
@ -186,19 +186,19 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@Test // DATAES-76 @Test // DATAES-76
public void shouldAddSampleInheritedEntityDocumentToIndex() { public void shouldAddSampleInheritedEntityDocumentToIndex() {
// given // given
IndexCoordinates index = IndexCoordinates.of("test-index-sample-inherited-mapping-builder").withTypes("mapping");
IndexOperations indexOps = operations.indexOps(index);
// when // when
indexOperations.createIndex(SampleInheritedEntity.class); indexOps.create();
indexOperations.putMapping(SampleInheritedEntity.class); indexOps.putMapping(indexOps.createMapping(SampleInheritedEntity.class));
Date createdDate = new Date(); Date createdDate = new Date();
String message = "msg"; String message = "msg";
String id = "abc"; 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(), operations.index(new SampleInheritedEntityBuilder(id).createdDate(createdDate).message(message).buildIndex(),
index); index);
operations.refresh(SampleInheritedEntity.class); operations.indexOps(SampleInheritedEntity.class).refresh();
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
SearchHits<SampleInheritedEntity> result = operations.search(searchQuery, SampleInheritedEntity.class, index); SearchHits<SampleInheritedEntity> result = operations.search(searchQuery, SampleInheritedEntity.class, index);
@ -231,10 +231,13 @@ public class MappingBuilderTests extends MappingContextBaseTests {
public void shouldHandleReverseRelationship() { public void shouldHandleReverseRelationship() {
// given // given
indexOperations.createIndex(User.class); IndexOperations indexOpsUser = operations.indexOps(User.class);
indexOperations.putMapping(User.class); indexOpsUser.create();
indexOperations.createIndex(Group.class); indexOpsUser.putMapping(indexOpsUser.createMapping(User.class));
indexOperations.putMapping(Group.class);
IndexOperations indexOpsGroup = operations.indexOps(Group.class);
indexOpsGroup.create();
indexOpsGroup.putMapping(indexOpsGroup.createMapping(Group.class));
// when // when
@ -245,8 +248,9 @@ public class MappingBuilderTests extends MappingContextBaseTests {
public void shouldMapBooks() { public void shouldMapBooks() {
// given // given
indexOperations.createIndex(Book.class); IndexOperations indexOps = operations.indexOps(Book.class);
indexOperations.putMapping(Book.class); indexOps.create();
indexOps.putMapping(indexOps.createMapping(Book.class));
// when // when
@ -257,11 +261,12 @@ public class MappingBuilderTests extends MappingContextBaseTests {
public void shouldUseBothAnalyzer() { public void shouldUseBothAnalyzer() {
// given // given
indexOperations.createIndex(Book.class); IndexOperations indexOps = this.operations.indexOps(Book.class);
indexOperations.putMapping(Book.class); indexOps.create();
indexOps.putMapping(indexOps.createMapping(Book.class));
// when // when
Map mapping = operations.getMapping(Book.class); Map mapping = indexOps.getMapping();
Map descriptionMapping = (Map) ((Map) mapping.get("properties")).get("description"); Map descriptionMapping = (Map) ((Map) mapping.get("properties")).get("description");
Map prefixDescription = (Map) ((Map) descriptionMapping.get("fields")).get("prefix"); Map prefixDescription = (Map) ((Map) descriptionMapping.get("fields")).get("prefix");
@ -298,11 +303,12 @@ public class MappingBuilderTests extends MappingContextBaseTests {
public void shouldUseCopyTo() { public void shouldUseCopyTo() {
// given // given
indexOperations.createIndex(CopyToEntity.class); IndexOperations indexOps = operations.indexOps(CopyToEntity.class);
indexOperations.putMapping(CopyToEntity.class); indexOps.create();
indexOps.putMapping(indexOps.createMapping(CopyToEntity.class));
// when // when
Map mapping = operations.getMapping(CopyToEntity.class); Map mapping = indexOps.getMapping();
Map properties = (Map) mapping.get("properties"); Map properties = (Map) mapping.get("properties");
Map fieldFirstName = (Map) properties.get("firstName"); Map fieldFirstName = (Map) properties.get("firstName");
Map fieldLastName = (Map) properties.get("lastName"); Map fieldLastName = (Map) properties.get("lastName");

View File

@ -67,19 +67,20 @@ public class CriteriaQueryTests {
private final IndexCoordinates index = IndexCoordinates.of("test-index-sample-core-query").withTypes("test-type"); private final IndexCoordinates index = IndexCoordinates.of("test-index-sample-core-query").withTypes("test-type");
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations; private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
indexOperations.deleteIndex(SampleEntity.class); indexOperations = operations.indexOps(SampleEntity.class);
indexOperations.createIndex(SampleEntity.class); indexOperations.delete();
indexOperations.putMapping(SampleEntity.class); indexOperations.create();
indexOperations.refresh(SampleEntity.class); indexOperations.putMapping(indexOperations.createMapping(SampleEntity.class));
indexOperations.refresh();
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(SampleEntity.class); indexOperations.delete();
} }
@Test @Test
@ -96,7 +97,7 @@ public class CriteriaQueryTests {
indexQuery.setId(documentId); indexQuery.setId(documentId);
indexQuery.setObject(sampleEntity); indexQuery.setObject(sampleEntity);
operations.index(indexQuery, index); operations.index(indexQuery, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery( CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("test").and("message").contains("some")); new Criteria("message").contains("test").and("message").contains("some"));
@ -139,7 +140,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery( CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("some").or("message").contains("test")); new Criteria("message").contains("some").or("message").contains("test"));
@ -170,7 +171,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery); indexQueries.add(indexQuery);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().and(new Criteria("message").contains("some"))); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().and(new Criteria("message").contains("some")));
// when // when
@ -201,7 +202,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery); indexQueries.add(indexQuery);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().or(new Criteria("message").contains("some"))); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().or(new Criteria("message").contains("some")));
// when // when
@ -230,7 +231,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery); indexQueries.add(indexQuery);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message"));
// when // when
@ -272,7 +273,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message"));
// when // when
@ -314,7 +315,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
Criteria criteria = new Criteria("message").endsWith("end"); Criteria criteria = new Criteria("message").endsWith("end");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria); CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
@ -356,7 +357,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
Criteria criteria = new Criteria("message").startsWith("start"); Criteria criteria = new Criteria("message").startsWith("start");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria); CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
@ -398,7 +399,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("contains")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("contains"));
// when // when
@ -439,7 +440,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").expression("+elasticsearch || test")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").expression("+elasticsearch || test"));
// when // when
@ -480,7 +481,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery( CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").startsWith("some").endsWith("search").contains("message").is("some message search")); new Criteria("message").startsWith("some").endsWith("search").contains("message").is("some message search"));
@ -522,7 +523,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("foo").not()); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("foo").not());
// when // when
@ -566,7 +567,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100, 150)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100, 150));
// when // when
@ -608,7 +609,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(350, null)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(350, null));
// when // when
@ -651,7 +652,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(null, 550)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(null, 550));
// when // when
@ -694,7 +695,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").lessThanEqual(750)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").lessThanEqual(750));
// when // when
@ -737,7 +738,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").greaterThanEqual(950)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").greaterThanEqual(950));
// when // when
@ -780,7 +781,7 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1));
// when // when
@ -801,7 +802,7 @@ public class CriteriaQueryTests {
indexQueries.add(buildIndex(SampleEntity.builder().id("3").message("ac").build())); indexQueries.add(buildIndex(SampleEntity.builder().id("3").message("ac").build()));
operations.bulkIndex(indexQueries, index); operations.bulkIndex(indexQueries, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
// when // when
CriteriaQuery criteriaQuery = new CriteriaQuery( CriteriaQuery criteriaQuery = new CriteriaQuery(
@ -828,7 +829,7 @@ public class CriteriaQueryTests {
indexQuery.setId(documentId); indexQuery.setId(documentId);
indexQuery.setObject(sampleEntity); indexQuery.setObject(sampleEntity);
operations.index(indexQuery, index); operations.index(indexQuery, index);
indexOperations.refresh(SampleEntity.class); indexOperations.refresh();
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("Hello World!")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("Hello World!"));

View File

@ -29,6 +29,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
@ -57,10 +58,10 @@ public class ImmutableElasticsearchRepositoryTests {
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexOperations indexOperations = operations.indexOps(ImmutableEntity.class);
operations.deleteIndex(ImmutableEntity.class); indexOperations.delete();
operations.createIndex(ImmutableEntity.class); indexOperations.create();
operations.refresh(ImmutableEntity.class); indexOperations.refresh();
} }
@Test // DATAES-281 @Test // DATAES-281

View File

@ -19,9 +19,7 @@ import org.elasticsearch.client.Client;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.ElasticsearchConfigurationSupport; 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.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
/** /**
@ -43,9 +41,4 @@ public class ElasticsearchTemplateConfiguration extends ElasticsearchConfigurati
ElasticsearchConverter elasticsearchConverter) { ElasticsearchConverter elasticsearchConverter) {
return new ElasticsearchTemplate(elasticsearchClient, elasticsearchConverter); return new ElasticsearchTemplate(elasticsearchClient, elasticsearchConverter);
} }
@Bean
IndexOperations indexOperations(ElasticsearchOperations elasticsearchOperations) {
return elasticsearchOperations.getIndexOperations();
}
} }

View File

@ -29,6 +29,7 @@ import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
@ -52,16 +53,19 @@ public class ComplexCustomMethodRepositoryTests {
@Autowired private ComplexElasticsearchRepository complexRepository; @Autowired private ComplexElasticsearchRepository complexRepository;
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, SampleEntity.class); indexOperations = operations.indexOps(SampleEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(SampleEntity.class); indexOperations.delete();
} }
@Test @Test

View File

@ -29,6 +29,7 @@ import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
@ -51,16 +52,18 @@ public class ComplexCustomMethodRepositoryManualWiringTests {
@Autowired private ComplexElasticsearchRepositoryManualWiring complexRepository; @Autowired private ComplexElasticsearchRepositoryManualWiring complexRepository;
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, SampleEntity.class); indexOperations = operations.indexOps(SampleEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(SampleEntity.class); indexOperations.delete();
} }
@Test @Test

View File

@ -49,6 +49,7 @@ import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Highlight; import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.data.elasticsearch.annotations.HighlightField; import org.springframework.data.elasticsearch.annotations.HighlightField;
import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit; import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits; import org.springframework.data.elasticsearch.core.SearchHits;
@ -80,16 +81,18 @@ public abstract class CustomMethodRepositoryBaseTests {
@Autowired private SampleStreamingCustomMethodRepository streamingRepository; @Autowired private SampleStreamingCustomMethodRepository streamingRepository;
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, SampleEntity.class); indexOperations = operations.indexOps(SampleEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(SampleEntity.class); indexOperations.delete();
} }
@Test @Test

View File

@ -30,6 +30,7 @@ import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version; import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
@ -56,16 +57,18 @@ public class DoubleIDRepositoryTests {
@Autowired private DoubleIDRepository repository; @Autowired private DoubleIDRepository repository;
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, DoubleIDEntity.class); indexOperations = operations.indexOps(DoubleIDEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
public void after() { public void after() {
indexOperations.deleteIndex(DoubleIDEntity.class); indexOperations.delete();
} }
@Test @Test

View File

@ -26,7 +26,9 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
@ -56,15 +58,17 @@ public class DynamicIndexEntityTests {
@Autowired private DynamicIndexRepository repository; @Autowired private DynamicIndexRepository repository;
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@Autowired private IndexNameProvider indexNameProvider; @Autowired private IndexNameProvider indexNameProvider;
@BeforeEach @BeforeEach
public void init() { public void init() {
indexOperations = operations.indexOps(IndexCoordinates.of("index1"));
deleteIndexes(); deleteIndexes();
indexOperations.createIndex("index1"); operations.indexOps(IndexCoordinates.of("index1")).create();
indexOperations.createIndex("index2"); operations.indexOps(IndexCoordinates.of("index2")).create();
} }
@AfterEach @AfterEach
@ -74,8 +78,8 @@ public class DynamicIndexEntityTests {
private void deleteIndexes() { private void deleteIndexes() {
indexOperations.deleteIndex("index1"); indexOperations.delete();
indexOperations.deleteIndex("index2"); operations.indexOps(IndexCoordinates.of("index2")).delete();
} }
@Test // DATAES-456 @Test // DATAES-456

View File

@ -35,6 +35,7 @@ import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField; 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.IndexOperations;
import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
@ -62,18 +63,20 @@ public class SpringDataGeoRepositoryTests {
@EnableElasticsearchRepositories(considerNestedRepositories = true) @EnableElasticsearchRepositories(considerNestedRepositories = true)
static class Config {} static class Config {}
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@Autowired SpringDataGeoRepository repository; @Autowired SpringDataGeoRepository repository;
@BeforeEach @BeforeEach
public void init() { public void init() {
IndexInitializer.init(indexOperations, GeoEntity.class); indexOperations = operations.indexOps(GeoEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(GeoEntity.class); indexOperations.delete();
} }
@Test @Test

View File

@ -30,6 +30,7 @@ import org.springframework.context.annotation.Import;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version; import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
@ -56,16 +57,19 @@ public class IntegerIDRepositoryTests {
@Autowired private IntegerIDRepository repository; @Autowired private IntegerIDRepository repository;
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, IntegerIDEntity.class); indexOperations = operations.indexOps(IntegerIDEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(IntegerIDEntity.class); indexOperations.delete();
} }
@Test @Test

View File

@ -41,6 +41,7 @@ import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.InnerField; import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.IndexOperations; import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
@ -65,16 +66,19 @@ public class InnerObjectTests {
@Autowired private SampleElasticSearchBookRepository bookRepository; @Autowired private SampleElasticSearchBookRepository bookRepository;
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, Book.class); indexOperations = operations.indexOps(Book.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(Book.class); indexOperations.delete();
} }
@Test @Test

View File

@ -16,6 +16,7 @@
package org.springframework.data.elasticsearch.repositories.setting.dynamic; package org.springframework.data.elasticsearch.repositories.setting.dynamic;
import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.core.document.Document.*;
import java.util.Map; import java.util.Map;
@ -61,18 +62,19 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
static class Config {} static class Config {}
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations; private IndexOperations indexOperations;
@Autowired private DynamicSettingAndMappingEntityRepository repository; @Autowired private DynamicSettingAndMappingEntityRepository repository;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, DynamicSettingAndMappingEntity.class); indexOperations = operations.indexOps(DynamicSettingAndMappingEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(DynamicSettingAndMappingEntity.class); indexOperations.delete();
} }
@Test // DATAES-64 @Test // DATAES-64
@ -82,8 +84,8 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
// delete , create and apply mapping in before method // delete , create and apply mapping in before method
// then // then
assertThat(indexOperations.indexExists(DynamicSettingAndMappingEntity.class)).isTrue(); assertThat(indexOperations.exists()).isTrue();
Map<String, Object> map = indexOperations.getSettings(DynamicSettingAndMappingEntity.class); Map<String, Object> map = indexOperations.getSettings();
assertThat(map.containsKey("index.number_of_replicas")).isTrue(); assertThat(map.containsKey("index.number_of_replicas")).isTrue();
assertThat(map.containsKey("index.number_of_shards")).isTrue(); assertThat(map.containsKey("index.number_of_shards")).isTrue();
assertThat(map.containsKey("index.analysis.analyzer.emailAnalyzer.tokenizer")).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 // delete , create and apply mapping in before method
// when // when
Map<String, Object> mapping = indexOperations.getMapping(DynamicSettingAndMappingEntity.class); Map<String, Object> mapping = indexOperations.getMapping();
// then // then
Map<String, Object> properties = (Map<String, Object>) mapping.get("properties"); Map<String, Object> properties = (Map<String, Object>) mapping.get("properties");
@ -149,9 +151,9 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
public void shouldCreateMappingWithSpecifiedMappings() { public void shouldCreateMappingWithSpecifiedMappings() {
// given // given
indexOperations.deleteIndex(DynamicSettingAndMappingEntity.class); indexOperations.delete();
indexOperations.createIndex(DynamicSettingAndMappingEntity.class); indexOperations.create();
indexOperations.refresh(DynamicSettingAndMappingEntity.class); indexOperations.refresh();
// when // when
String mappings = "{\n" + // String mappings = "{\n" + //
@ -159,11 +161,11 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
" \"email\" : {\"type\" : \"text\", \"analyzer\" : \"emailAnalyzer\" }\n" + // " \"email\" : {\"type\" : \"text\", \"analyzer\" : \"emailAnalyzer\" }\n" + //
" }\n" + // " }\n" + //
'}'; '}';
indexOperations.putMapping(DynamicSettingAndMappingEntity.class, mappings); indexOperations.putMapping(parse(mappings));
indexOperations.refresh(DynamicSettingAndMappingEntity.class); indexOperations.refresh();
// then // then
Map<String, Object> mapping = indexOperations.getMapping(DynamicSettingAndMappingEntity.class); Map<String, Object> mapping = indexOperations.getMapping();
Map<String, Object> properties = (Map<String, Object>) mapping.get("properties"); Map<String, Object> properties = (Map<String, Object>) mapping.get("properties");
assertThat(mapping).isNotNull(); assertThat(mapping).isNotNull();
assertThat(properties).isNotNull(); assertThat(properties).isNotNull();
@ -178,7 +180,7 @@ public class DynamicSettingAndMappingEntityRepositoryTests {
// given // given
// then // then
Map<String, Object> mapping = indexOperations.getMapping(DynamicSettingAndMappingEntity.class); Map<String, Object> mapping = indexOperations.getMapping();
Map<String, Object> properties = (Map<String, Object>) mapping.get("properties"); Map<String, Object> properties = (Map<String, Object>) mapping.get("properties");
assertThat(mapping).isNotNull(); assertThat(mapping).isNotNull();
assertThat(properties).isNotNull(); assertThat(properties).isNotNull();

View File

@ -53,16 +53,17 @@ public class FieldDynamicMappingEntityRepositoryTests {
static class Config {} static class Config {}
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations; private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, FieldDynamicMappingEntity.class); indexOperations = operations.indexOps(FieldDynamicMappingEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(FieldDynamicMappingEntity.class); indexOperations.delete();
} }
@Test // DATAES-209 @Test // DATAES-209

View File

@ -55,16 +55,17 @@ public class SpELEntityTests {
@Autowired private SpELRepository repository; @Autowired private SpELRepository repository;
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations; private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, SpELEntity.class); indexOperations = operations.indexOps(SpELEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex("test-index-abz-*"); operations.indexOps(IndexCoordinates.of("test-index-abz-*")).delete();
} }
@Test @Test

View File

@ -60,16 +60,17 @@ public class SynonymRepositoryTests {
@Autowired private SynonymRepository repository; @Autowired private SynonymRepository repository;
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations; private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, SynonymEntity.class); indexOperations = operations.indexOps(SynonymEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(SynonymEntity.class); indexOperations.delete();
} }
@Test @Test

View File

@ -45,6 +45,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.ScriptedField; 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.IndexOperations;
import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
@ -76,16 +77,18 @@ public class UUIDElasticsearchRepositoryTests {
@Autowired private SampleUUIDKeyedElasticsearchRepository repository; @Autowired private SampleUUIDKeyedElasticsearchRepository repository;
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, SampleEntityUUIDKeyed.class); indexOperations = operations.indexOps(SampleEntityUUIDKeyed.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(SampleEntityUUIDKeyed.class); indexOperations.delete();
} }
@Test @Test

View File

@ -37,6 +37,7 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType; 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.core.IndexOperations;
import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration; import org.springframework.data.elasticsearch.junit.jupiter.ElasticsearchRestTemplateConfiguration;
import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest; import org.springframework.data.elasticsearch.junit.jupiter.SpringIntegrationTest;
@ -65,11 +66,13 @@ class QueryKeywordsTests {
@Autowired private ProductRepository repository; @Autowired private ProductRepository repository;
@Autowired private IndexOperations indexOperations; @Autowired ElasticsearchOperations operations;
private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { 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) Product product1 = Product.builder().id("1").name("Sugar").text("Cane sugar").price(1.0f).available(false)
.sortName("sort5").build(); .sortName("sort5").build();
@ -89,7 +92,7 @@ class QueryKeywordsTests {
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(Product.class); indexOperations.delete();
} }
@Test @Test

View File

@ -81,16 +81,17 @@ public class SimpleElasticsearchRepositoryTests {
@Autowired private SampleElasticsearchRepository repository; @Autowired private SampleElasticsearchRepository repository;
@Autowired private ElasticsearchOperations operations; @Autowired private ElasticsearchOperations operations;
@Autowired private IndexOperations indexOperations; private IndexOperations indexOperations;
@BeforeEach @BeforeEach
public void before() { public void before() {
IndexInitializer.init(indexOperations, SampleEntity.class); indexOperations = operations.indexOps(SampleEntity.class);
IndexInitializer.init(indexOperations);
} }
@AfterEach @AfterEach
void after() { void after() {
indexOperations.deleteIndex(SampleEntity.class); indexOperations.delete();
} }
@Test @Test

View File

@ -32,27 +32,22 @@ public class IndexInitializer {
* *
* @param operations * @param operations
* @param clazz * @param clazz
* @deprecated since 4.0, use {@link IndexInitializer#init(IndexOperations, Class)} * @deprecated since 4.0, use {@link IndexInitializer#init(IndexOperations)}
*/ */
@Deprecated @Deprecated
public static void init(ElasticsearchOperations operations, Class<?> clazz) { public static void init(ElasticsearchOperations operations, Class<?> clazz) {
IndexOperations indexOperations = operations.getIndexOperations(); init(operations.indexOps(clazz));
indexOperations.deleteIndex(clazz);
indexOperations.createIndex(clazz);
indexOperations.putMapping(clazz);
indexOperations.refresh(clazz);
} }
/** /**
* Initialize a fresh index with mappings for {@link Class}. Drops the index if it exists before creation. * Initialize a fresh index with mappings for {@link Class}. Drops the index if it exists before creation.
* *
* @param operations * @param indexOperations
* @param clazz
*/ */
public static void init(IndexOperations operations, Class<?> clazz) { public static void init(IndexOperations indexOperations) {
operations.deleteIndex(clazz); indexOperations.delete();
operations.createIndex(clazz); indexOperations.create();
operations.putMapping(clazz); indexOperations.putMapping(indexOperations.createMapping());
operations.refresh(clazz); indexOperations.refresh();
} }
} }