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.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
/**
@ -48,9 +47,4 @@ public abstract class AbstractElasticsearchConfiguration extends ElasticsearchCo
public ElasticsearchOperations elasticsearchOperations(ElasticsearchConverter elasticsearchConverter) {
return new ElasticsearchRestTemplate(elasticsearchClient(), elasticsearchConverter);
}
@Bean
public IndexOperations indexOperations(ElasticsearchOperations elasticsearchOperations) {
return elasticsearchOperations.getIndexOperations();
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -16,8 +16,8 @@
package org.springframework.data.elasticsearch.core;
import java.util.List;
import java.util.Optional;
import org.elasticsearch.action.update.UpdateResponse;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.BulkOptions;
import org.springframework.data.elasticsearch.core.query.DeleteQuery;
@ -25,6 +25,7 @@ import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateResponse;
import org.springframework.lang.Nullable;
/**
@ -68,9 +69,9 @@ public interface DocumentOperations {
* saves the given entities to the given index
*
* @param entities must not be {@literal null}
* @param index the idnex to save the entities in, must not be {@literal null}
* @param index the index to save the entities in, must not be {@literal null}
* @param <T> the entity type
* @return the saved entites
* @return the saved entities
*/
<T> Iterable<T> save(Iterable<T> entities, IndexCoordinates index);
@ -87,21 +88,32 @@ public interface DocumentOperations {
* Index an object. Will do save or update.
*
* @param query the query defining the object
* @param index the index from which the object is read.
* @param index the index where the object is stored.
* @return returns the document id
*/
String index(IndexQuery query, IndexCoordinates index);
/**
* Retrieves an object from an index.
* Retrieves an object from the index specified in the entity's Document annotation.
*
* @param query the query defining the id of the object to get
* @param clazz the type of the object to be returned
* @param index the index from which the object is read.
* @return the found object
* @param id the id of the object
* @param clazz the entity class,
* @param <T> the entity type
* @return the entity
*/
@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.
@ -113,6 +125,24 @@ public interface DocumentOperations {
*/
<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.
*
@ -158,6 +188,32 @@ public interface DocumentOperations {
*/
String delete(String id, IndexCoordinates index);
/**
* Delete the one object with provided id.
*
* @param id the document ot delete
* @param entityType must not be {@literal null}.
* @return documentId of the document deleted
*/
String delete(String id, Class<?> entityType);
/**
* Deletes the given entity
*
* @param entity the entity to delete
* @return documentId of the document deleted
*/
String delete(Object entity);
/**
* Deletes the given entity
*
* @param entity the entity to delete
* @param index the index from which to delete
* @return documentId of the document deleted
*/
String delete(Object entity, IndexCoordinates index);
/**
* Delete all records matching the query.
*
@ -168,14 +224,6 @@ public interface DocumentOperations {
*/
void delete(Query query, Class<?> clazz, IndexCoordinates index);
/**
* Delete all records matching the query.
*
* @param query query defining the objects
* @param index the index where to delete the records
*/
void delete(DeleteQuery query, IndexCoordinates index);
/**
* Partial update of the document.
*
@ -184,4 +232,30 @@ public interface DocumentOperations {
* @return the update response
*/
UpdateResponse update(UpdateQuery updateQuery, IndexCoordinates index);
// region deprecated
/**
* Delete all records matching the query.
*
* @param query query defining the objects
* @param index the index where to delete the records
* @deprecated since 4.0, use {@link #delete(Query, Class, IndexCoordinates)}
*/
@Deprecated
void delete(DeleteQuery query, IndexCoordinates index);
/**
* Retrieves an object from an index.
*
* @param query the query defining the id of the object to get
* @param clazz the type of the object to be returned
* @param index the index from which the object is read.
* @return the found object
* @deprecated since 4.0, use {@link #getById(String, Class, IndexCoordinates)}
*/
@Deprecated
@Nullable
<T> 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.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.lang.Nullable;
@ -40,7 +41,19 @@ import org.springframework.lang.Nullable;
*/
public interface ElasticsearchOperations extends DocumentOperations, SearchOperations {
IndexOperations getIndexOperations();
/**
* get an {@link IndexOperations} that is bound to the given class
*
* @return IndexOperations
*/
IndexOperations indexOps(Class<?> clazz);
/**
* get an {@link IndexOperations} that is bound to the given class
*
* @return IndexOperations
*/
IndexOperations indexOps(IndexCoordinates index);
ElasticsearchConverter getElasticsearchConverter();
@ -52,11 +65,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
*
* @param indexName the name of the index
* @return {@literal true} if the index was created
* @deprecated since 4.0, use {@link IndexOperations#createIndex(String) instead}
* @deprecated since 4.0, use {@link IndexOperations#create()}
*/
@Deprecated
default boolean createIndex(String indexName) {
return getIndexOperations().createIndex(indexName);
return indexOps(IndexCoordinates.of(indexName)).create();
}
/**
@ -65,11 +78,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* @param indexName the name of the index
* @param settings the index settings
* @return {@literal true} if the index was created
* @deprecated since 4.0, use {@link IndexOperations#createIndex(String, Object)} instead}
* @deprecated since 4.0, use {@link IndexOperations#create(Document)}
*/
@Deprecated
default boolean createIndex(String indexName, Object settings) {
return getIndexOperations().createIndex(indexName, settings);
return indexOps(IndexCoordinates.of(indexName)).create(getDocument(settings));
}
/**
@ -78,11 +91,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the index was created
* @deprecated since 4.0, use {@link IndexOperations#createIndex(Class)} instead}
* @deprecated since 4.0, use {@link IndexOperations#create()}
*/
@Deprecated
default boolean createIndex(Class<?> clazz) {
return getIndexOperations().createIndex(clazz);
return indexOps(clazz).create();
}
/**
@ -92,11 +105,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @param settings the index settings
* @return {@literal true} if the index was created
* @deprecated since 4.0, use {@link IndexOperations#createIndex(Class, Object)} instead}
* @deprecated since 4.0, use {@link IndexOperations#create(Document)}
*/
@Deprecated
default boolean createIndex(Class<?> clazz, Object settings) {
return getIndexOperations().createIndex(clazz, settings);
return indexOps(clazz).create(getDocument(settings));
}
/**
@ -105,11 +118,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the index was deleted
* @deprecated since 4.0, use {@link IndexOperations#deleteIndex(Class)} instead}
* @deprecated since 4.0, use {@link IndexOperations#delete()}
*/
@Deprecated
default boolean deleteIndex(Class<?> clazz) {
return getIndexOperations().deleteIndex(clazz);
return indexOps(clazz).delete();
}
/**
@ -117,11 +130,23 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
*
* @param indexName the name of the index to delete
* @return {@literal true} if the index was deleted
* @deprecated since 4.0, use {@link IndexOperations#deleteIndex(String)} instead}
* @deprecated since 4.0, use {@link IndexOperations#delete()}
*/
@Deprecated
default boolean deleteIndex(String indexName) {
return getIndexOperations().deleteIndex(indexName);
return indexOps(IndexCoordinates.of(indexName)).delete();
}
/**
* Deletes an index for an IndexCoordinate
*
* @param index the index to delete
* @return {@literal true} if the index was deleted
* @deprecated since 4.0 use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#delete()}
*/
@Deprecated
default boolean deleteIndex(IndexCoordinates index) {
return indexOps(index).delete();
}
/**
@ -129,11 +154,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
*
* @param indexName the name of the index
* @return {@literal true} if the index exists
* @deprecated since 4.0, use {@link IndexOperations#indexExists(String)} instead}
* @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#exists()}
*/
@Deprecated
default boolean indexExists(String indexName) {
return getIndexOperations().indexExists(indexName);
return indexOps(IndexCoordinates.of(indexName)).exists();
}
/**
@ -142,11 +167,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the index exists
* @deprecated since 4.0, use {@link IndexOperations#indexExists(Class)} instead}
* @deprecated since 4.0, use {@link #indexOps(Class)} and {@link IndexOperations#exists()}
*/
@Deprecated
default boolean indexExists(Class<?> clazz) {
return getIndexOperations().indexExists(clazz);
return indexOps(clazz).exists();
}
/**
@ -155,11 +180,13 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the mapping could be stored
* @deprecated since 4.0, use {@link IndexOperations#putMapping(Class)} instead}
* @deprecated since 4.0, use {@link #indexOps(Class)}, {@link IndexOperations#createMapping(Class)} and
* {@link IndexOperations#putMapping(Document)}
*/
@Deprecated
default boolean putMapping(Class<?> clazz) {
return getIndexOperations().putMapping(clazz);
IndexOperations indexOps = indexOps(clazz);
return indexOps.putMapping(indexOps.createMapping(clazz));
}
/**
@ -169,11 +196,13 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the mapping could be stored
* @deprecated since 4.0, use {@link IndexOperations#putMapping(IndexCoordinates, Class)} instead}
* @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)}, {@link IndexOperations#createMapping(Class)} and
* {@link IndexOperations#putMapping(Document)}
*/
@Deprecated
default boolean putMapping(IndexCoordinates index, Class<?> clazz) {
return getIndexOperations().putMapping(index, clazz);
IndexOperations indexOps = indexOps(index);
return indexOps.putMapping(indexOps.createMapping(clazz));
}
/**
@ -182,11 +211,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* @param index the index to store the mapping to
* @param mappings can be a JSON String or a {@link Map}
* @return {@literal true} if the mapping could be stored
* @deprecated since 4.0, use {@link IndexOperations#putMapping(IndexCoordinates, Object)} instead}
* @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#putMapping(Document)}
*/
@Deprecated
default boolean putMapping(IndexCoordinates index, Object mappings) {
return getIndexOperations().putMapping(index, mappings);
return indexOps(index).putMapping(getDocument(mappings));
}
/**
@ -196,11 +225,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @param mappings can be a JSON String or a {@link Map}
* @return {@literal true} if the mapping could be stored
* @deprecated since 4.0, use {@link IndexOperations#putMapping(Class, Object)} instead}
* @deprecated since 4.0, use {@link #indexOps(Class)} and {@link IndexOperations#putMapping(Document)}
*/
@Deprecated
default boolean putMapping(Class<?> clazz, Object mappings) {
return getIndexOperations().putMapping(clazz, mappings);
return indexOps(clazz).putMapping(getDocument(mappings));
}
/**
@ -209,11 +238,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}.
* @return the mapping
* @deprecated since 4.0, use {@link IndexOperations#getMapping(Class)} instead}
* @deprecated since 4.0, use {@link #indexOps(Class)} and {@link IndexOperations#getMapping()}
*/
@Deprecated
default Map<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
* @return the mapping
* @deprecated since 4.0, use {@link IndexOperations#getMapping(IndexCoordinates)} instead}
* @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#getMapping()}
*/
@Deprecated
default Map<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 index the index for which to add an alias
* @return true if the alias was created
* @deprecated since 4.0, use {@link IndexOperations#addAlias(AliasQuery, IndexCoordinates)} instead}
* @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#addAlias(AliasQuery)}
*/
@Deprecated
default boolean addAlias(AliasQuery query, IndexCoordinates index) {
return getIndexOperations().addAlias(query, index);
return indexOps(index).addAlias(query);
}
/**
@ -247,11 +276,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
* @param query query defining the alias
* @param index the index for which to remove an alias
* @return true if the alias was removed
* @deprecated since 4.0, use {@link IndexOperations#removeAlias(AliasQuery, IndexCoordinates)} instead}
* @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} {@link IndexOperations#removeAlias(AliasQuery)}
*/
@Deprecated
default boolean removeAlias(AliasQuery query, IndexCoordinates index) {
return getIndexOperations().removeAlias(query, index);
return indexOps(index).removeAlias(query);
}
/**
@ -259,11 +288,11 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
*
* @param indexName the name of the index
* @return alias information
* @deprecated since 4.0, use {@link IndexOperations#queryForAlias(String)} instead}
* @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#queryForAlias()}
*/
@Deprecated
default List<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
* @return the settings
* @deprecated since 4.0, use {@link IndexOperations#getSettings(String)} )} instead}
* @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#getSettings()} )}
*/
@Deprecated
default Map<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
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return the settings
* @deprecated since 4.0, use {@link IndexOperations#getSettings(Class)} instead}
* @deprecated since 4.0, use {@link #indexOps(Class)} and {@link IndexOperations#getSettings()}
*/
@Deprecated
default Map<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).
*
* @param index the index to refresh
* @deprecated since 4.0, use {@link IndexOperations#refresh(IndexCoordinates)} instead}
* @deprecated since 4.0, use {@link #indexOps(IndexCoordinates)} and {@link IndexOperations#refresh()} instead}
*/
@Deprecated
default void refresh(IndexCoordinates index) {
getIndexOperations().refresh(index);
indexOps(index).refresh();
}
/**
@ -307,13 +362,36 @@ public interface ElasticsearchOperations extends DocumentOperations, SearchOpera
*
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @deprecated since 4.0, use {@link IndexOperations#refresh(Class)} instead}
* @deprecated since 4.0, use {@link #indexOps(Class)} and {@link IndexOperations#refresh()} instead}
*/
@Deprecated
default void refresh(Class<?> clazz) {
getIndexOperations().refresh(clazz);
indexOps(clazz).refresh();
}
// endregion
/**
* converts an object to a Document
*
* @param object
* @return
* @deprecated since 4.0, helper method for deprecated functions
*/
@Deprecated
@Nullable
default Document getDocument(Object object) {
Document document = null;
try {
if (object instanceof String) {
document = Document.parse((String) object);
} else if (object instanceof Map) {
document = Document.from((Map<String, Object>) object);
}
} catch (Exception e) {
throw new IllegalArgumentException("object cannot be converted to Document", e);
}
return document;
} // endregion
// region helper
/**

View File

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

View File

@ -16,6 +16,7 @@
package org.springframework.data.elasticsearch.core;
import java.util.List;
import java.util.Optional;
import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
@ -28,7 +29,6 @@ import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.search.suggest.SuggestBuilder;
@ -41,10 +41,10 @@ import org.springframework.data.elasticsearch.core.document.SearchDocumentRespon
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.BulkOptions;
import org.springframework.data.elasticsearch.core.query.DeleteQuery;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateResponse;
import org.springframework.data.elasticsearch.support.SearchHitsUtil;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
@ -97,9 +97,29 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
}
private void initialize(Client client, ElasticsearchConverter elasticsearchConverter) {
Assert.notNull(client, "Client must not be null!");
this.client = client;
initialize(elasticsearchConverter, new DefaultTransportIndexOperations(client, elasticsearchConverter));
initialize(elasticsearchConverter);
}
// endregion
// region IndexOperations
@Override
public IndexOperations indexOps(Class<?> clazz) {
Assert.notNull(clazz, "clazz must not be null");
return new DefaultTransportIndexOperations(client, elasticsearchConverter, clazz);
}
@Override
public IndexOperations indexOps(IndexCoordinates index) {
Assert.notNull(index, "index must not be null");
return new DefaultTransportIndexOperations(client, elasticsearchConverter, index);
}
// endregion
@ -128,8 +148,8 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
@Override
@Nullable
public <T> T get(GetQuery query, Class<T> clazz, IndexCoordinates index) {
GetRequestBuilder getRequestBuilder = requestFactory.getRequestBuilder(client, query, index);
public <T> T get(String id, Class<T> clazz, IndexCoordinates index) {
GetRequestBuilder getRequestBuilder = requestFactory.getRequestBuilder(client, id, index);
GetResponse response = getRequestBuilder.execute().actionGet();
return elasticsearchConverter.mapDocument(DocumentAdapters.from(response), clazz);
}
@ -145,6 +165,12 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
return elasticsearchConverter.mapDocuments(DocumentAdapters.from(builder.execute().actionGet()), clazz);
}
@Override
protected boolean doExists(String id, IndexCoordinates index) {
GetRequestBuilder getRequestBuilder = requestFactory.getRequestBuilder(client, id, index);
return getRequestBuilder.execute().actionGet().isExists();
}
@Override
public List<String> bulkIndex(List<IndexQuery> queries, BulkOptions bulkOptions, IndexCoordinates index) {
@ -165,19 +191,36 @@ public class ElasticsearchTemplate extends AbstractElasticsearchTemplate {
@Override
public String delete(String id, IndexCoordinates index) {
Assert.notNull(id, "id must not be null");
Assert.notNull(index, "index must not be null");
return client.prepareDelete(index.getIndexName(), IndexCoordinates.TYPE, elasticsearchConverter.convertId(id))
.execute().actionGet().getId();
}
@Override
@Deprecated
public void delete(DeleteQuery deleteQuery, IndexCoordinates index) {
requestFactory.deleteByQueryRequestBuilder(client, deleteQuery, index).get();
}
@Override
public void delete(Query query, Class<?> clazz, IndexCoordinates index) {
requestFactory.deleteByQueryRequestBuilder(client, query, clazz, index).get();
}
@Override
public String delete(Object entity, IndexCoordinates index) {
return super.delete(entity, index);
}
@Override
public UpdateResponse update(UpdateQuery query, IndexCoordinates index) {
UpdateRequestBuilder updateRequestBuilder = requestFactory.updateRequestBuilderFor(client, query, index);
return updateRequestBuilder.execute().actionGet();
org.elasticsearch.action.update.UpdateResponse updateResponse = updateRequestBuilder.execute().actionGet();
UpdateResponse.Result result = UpdateResponse.Result.valueOf(updateResponse.getResult().name());
return new UpdateResponse(result);
}
private List<String> doBulkOperation(List<?> queries, BulkOptions bulkOptions, IndexCoordinates index) {

View File

@ -19,13 +19,17 @@ import java.util.List;
import java.util.Map;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
/**
* The operations for the
* <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 Sascha Woo
* @since 4.0
@ -33,204 +37,104 @@ import org.springframework.data.elasticsearch.core.query.AliasQuery;
public interface IndexOperations {
/**
* Create an index for given indexName.
* Create an index.
*
* @param indexName the name of the index
* @return {@literal true} if the index was created
*/
boolean createIndex(String indexName);
boolean create();
/**
* Create an index for given indexName and Settings.
* Create an index for given Settings.
*
* @param indexName the name of the index
* @param settings the index settings
* @return {@literal true} if the index was created
*/
boolean createIndex(String indexName, Object settings);
boolean create(Document settings);
/**
* Create an index for a class.
* Deletes the index this {@link IndexOperations} is bound to
*
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the index was created
*/
boolean createIndex(Class<?> clazz);
/**
* Create an index for given class and Settings.
*
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @param settings the index settings
* @return {@literal true} if the index was created
*/
boolean createIndex(Class<?> clazz, Object settings);
/**
* Deletes an index for given entity.
*
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the index was deleted
*/
boolean deleteIndex(Class<?> clazz);
boolean delete();
/**
* Deletes an index.
* Checks if the index this IndexOperations is bound to exists
*
* @param indexName the name of the index to delete
* @return {@literal true} if the index was deleted
*/
boolean deleteIndex(String indexName);
/**
* check if index exists.
*
* @param indexName the name of the index
* @return {@literal true} if the index exists
*/
boolean indexExists(String indexName);
boolean exists();
/**
* check if index is exists.
*
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the index exists
* Refresh the index(es) this IndexOperations is bound to
*/
boolean indexExists(Class<?> clazz);
void refresh();
/**
* Create mapping for a class and store it to the index.
* Creates the index mapping for the entity this IndexOperations is bound to.
*
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return mapping object
*/
Document createMapping();
/**
* Creates the index mapping for the given class
*
* @param clazz the clazz to create a mapping for
* @return mapping object
*/
Document createMapping(Class<?> clazz);
/**
* writes a mapping to the index
*
* @param mapping the Document with the mapping definitions
* @return {@literal true} if the mapping could be stored
*/
boolean putMapping(Class<?> clazz);
/**
* Create mapping for the given class and put the mapping to the given index.
*
* @param index the index to store the mapping to
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @return {@literal true} if the mapping could be stored
*/
boolean putMapping(IndexCoordinates index, Class<?> clazz);
/**
* Stores a mapping to an index.
*
* @param index the index to store the mapping to
* @param mappings can be a JSON String or a {@link Map}
* @return {@literal true} if the mapping could be stored
*/
boolean putMapping(IndexCoordinates index, Object mappings);
/**
* Create mapping for a class Stores a mapping to an index.
*
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}
* @param mappings can be a JSON String or a {@link Map}
* @return {@literal true} if the mapping could be stored
*/
<T> boolean putMapping(Class<T> clazz, Object mappings);
boolean putMapping(Document mapping);
/**
* Get mapping for an index defined by a class.
*
* @param clazz The entity class, must be annotated with
* {@link org.springframework.data.elasticsearch.annotations.Document}.
* @return the mapping
*/
Map<String, Object> getMapping(Class<?> clazz);
/**
* Get mapping for a given index.
*
* @param index the index to read the mapping from
* @return the mapping
*/
Map<String, Object> getMapping(IndexCoordinates index);
Map<String, Object> getMapping();
/**
* Add an alias.
*
* @param query query defining the alias
* @param index the index for which to add an alias
* @return true if the alias was created
*/
boolean addAlias(AliasQuery query, IndexCoordinates index);
boolean addAlias(AliasQuery query);
/**
* Get the alias informations for a specified index.
*
* @return alias information
*/
List<AliasMetaData> queryForAlias();
/**
* Remove an alias.
*
* @param query query defining the alias
* @param index the index for which to remove an alias
* @return true if the alias was removed
*/
boolean removeAlias(AliasQuery query, IndexCoordinates index);
boolean removeAlias(AliasQuery query);
/**
* Get the alias informations for a specified index.
* Get the index settings.
*
* @param indexName the name of the index
* @return alias information
* @return the settings
*/
List<AliasMetaData> queryForAlias(String indexName);
Map<String, Object> getSettings();
/**
* Get settings for a given indexName.
*
* @param indexName the name of the index
* @param includeDefaults wehther or not to include all the default settings
* @return the settings
*/
Map<String, Object> getSettings(String indexName);
/**
* Get settings for a given indexName.
*
* @param indexName the name of the index
* @param includeDefaults whether or not to include all the default settings
* @return the settings
*/
Map<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);
Map<String, Object> getSettings(boolean includeDefaults);
}

View File

@ -151,8 +151,37 @@ public interface ReactiveDocumentOperations {
* @param entityType the domain type used for mapping the document.
* @param <T>
* @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}.
@ -162,7 +191,7 @@ public interface ReactiveDocumentOperations {
* @param <T>
* @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.
@ -180,6 +209,17 @@ public interface ReactiveDocumentOperations {
* @param index the target index, must not be {@literal null}
* @return a {@link Mono} emitting {@literal true} if a matching document exists, {@literal false} otherwise.
*/
Mono<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);
/**
@ -188,7 +228,7 @@ public interface ReactiveDocumentOperations {
* @param entity must not be {@literal null}.
* @return a {@link Mono} emitting the {@literal id} of the removed document.
*/
Mono<String> delete(Object entity);
Mono<String> delete(Object entity);
/**
* Delete the given entity extracting index and type from entity metadata.
@ -197,7 +237,7 @@ public interface ReactiveDocumentOperations {
* @param index the target index, must not be {@literal null}
* @return a {@link Mono} emitting the {@literal id} of the removed document.
*/
Mono<String> delete(Object entity, IndexCoordinates index);
Mono<String> delete(Object entity, IndexCoordinates index);
/**
* Delete the entity with given {@literal id}.
@ -206,32 +246,32 @@ public interface ReactiveDocumentOperations {
* @param index the target index, must not be {@literal null}
* @return a {@link Mono} emitting the {@literal id} of the removed document.
*/
default Mono<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.
*
@ -239,7 +279,7 @@ public interface ReactiveDocumentOperations {
* @param entityType must not be {@literal null}.
* @return a {@link Mono} emitting the number of the removed documents.
*/
Mono<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.
@ -249,5 +289,5 @@ public interface ReactiveDocumentOperations {
* @param index the target index, must not be {@literal null}
* @return a {@link Mono} emitting the number of the removed documents.
*/
Mono<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
}
}
/**
* Customization hook on the actual execution result {@link Publisher}. <br />
*
* @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
public Mono<Boolean> exists(String id, Class<?> entityType) {
return doExists(id, getIndexCoordinatesFor(entityType));
}
@Override
public Mono<Boolean> exists(String id, Class<?> entityType) {
return exists(id, entityType, getIndexCoordinatesFor(entityType));
public Mono<Boolean> exists(String id, IndexCoordinates index) {
return doExists(id, index);
}
/*
* (non-Javadoc)
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#exists(String, Class, IndexCoordinates)
*/
@Override
public Mono<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
public <T> Mono<T> findById(String id, Class<T> entityType) {
return findById(id, entityType, getIndexCoordinatesFor(entityType));
public <T> Mono<T> get(String id, Class<T> entityType) {
return get(id, entityType, getIndexCoordinatesFor(entityType));
}
/*
* (non-Javadoc)
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#findById(String, Class, IndexCoordinates)
*/
@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!");
return doFindById(id, getPersistentEntityFor(entityType), index)
return doGet(id, getPersistentEntityFor(entityType), index)
.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 doFindById(new GetRequest(index.getIndexName(), id));
return doGet(new GetRequest(index.getIndexName(), id));
});
}
/*
* (non-Javadoc)
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#exists(String, Class, IndexCoordinates)
/**
* Customization hook on the actual execution result {@link Publisher}. <br />
*
* @param request the already prepared {@link GetRequest} ready to be executed.
* @return a {@link Mono} emitting the result of the operation.
*/
@Override
public Mono<Boolean> exists(String id, Class<?> entityType, IndexCoordinates index) {
protected Mono<GetResult> doGet(GetRequest request) {
Assert.notNull(id, "Id must not be null!");
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)));
return Mono.from(execute(client -> client.get(request))) //
.onErrorResume(NoSuchIndexException.class, it -> Mono.empty());
}
/*
@ -367,25 +366,11 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#delete(Object, String, String)
*/
@Override
public Mono<String> delete(Object entity, IndexCoordinates index) {
public Mono<String> delete(Object entity, IndexCoordinates index) {
Entity<?> elasticsearchEntity = operations.forEntity(entity);
return Mono.defer(() -> doDeleteById(entity, converter.convertId(elasticsearchEntity.getId()),
elasticsearchEntity.getPersistentEntity(), index));
}
/*
* (non-Javadoc)
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#delete(String, Class, IndexCoordinates)
*/
@Override
public Mono<String> deleteById(String id, Class<?> entityType, IndexCoordinates index) {
Assert.notNull(id, "Id must not be null!");
return doDeleteById(null, id, getPersistentEntityFor(entityType), index);
return Mono.defer(() -> doDeleteById(converter.convertId(elasticsearchEntity.getId()), index));
}
@Override
@ -394,25 +379,37 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
}
@Override
public Mono<String> deleteById(String id, Class<?> entityType) {
return deleteById(id, entityType, getIndexCoordinatesFor(entityType));
public Mono<String> delete(String id, Class<?> entityType) {
Assert.notNull(id, "id must not be null");
Assert.notNull(entityType, "entityType must not be null");
return delete(id, getIndexCoordinatesFor(entityType));
}
private Mono<String> doDeleteById(@Nullable Object source, String id, ElasticsearchPersistentEntity<?> entity,
IndexCoordinates index) {
@Override
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 doDelete(prepareDeleteRequest(source, new DeleteRequest(index.getIndexName(), id)));
return doDelete(prepareDeleteRequest(new DeleteRequest(index.getIndexName(), id)));
});
}
/*
* (non-Javadoc)
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#deleteBy(Query, Class, IndexCoordinates)
* @see org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations#delete(Query, Class, IndexCoordinates)
*/
@Override
public Mono<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!");
@ -421,8 +418,8 @@ public class ReactiveElasticsearchTemplate implements ReactiveElasticsearchOpera
}
@Override
public Mono<Long> deleteBy(Query query, Class<?> entityType) {
return deleteBy(query, entityType, getIndexCoordinatesFor(entityType));
public Mono<Long> delete(Query query, Class<?> entityType) {
return delete(query, entityType, getIndexCoordinatesFor(entityType));
}
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
* {@link WriteRequest#setRefreshPolicy(String) refresh policy} if applicable.
*
* @param source the source object the {@link DeleteRequest} was derived from. My be {@literal null} if using the
* {@literal id} directly.
* @param request the generated {@link DeleteRequest}.
* @return never {@literal null}.
*/
protected DeleteRequest prepareDeleteRequest(@Nullable Object source, DeleteRequest request) {
protected DeleteRequest prepareDeleteRequest(DeleteRequest request) {
return prepareWriteRequest(request);
}

View File

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

View File

@ -50,6 +50,15 @@ public interface SearchOperations {
return count(query, null, index);
}
/**
* return number of elements found by given query
*
* @param query the query to execute
* @param clazz the entity clazz used for property mapping and index name extraction
* @return count
*/
long count(Query query, Class<?> clazz);
/**
* return number of elements found by given query
*
@ -211,50 +220,6 @@ public interface SearchOperations {
return search(query, clazz, index).map(SearchHit::getId).toList();
}
/**
* Returns scrolled page for given query
*
* @param scrollTimeInMillis duration of the scroll time
* @param query The search query.
* @param clazz The class of entity to retrieve.
* @param index the index to run the query against
* @return scrolled page result
* @deprecated since 4.0, use {@link #searchScrollStart(long, Query, Class, IndexCoordinates)}.
*/
@Deprecated
default <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.
*
@ -271,8 +236,32 @@ public interface SearchOperations {
AggregatedPage<SearchHit<T>> aggregatedPage = SearchHitSupport.page(searchHits, query.getPageable());
return (AggregatedPage<T>) SearchHitSupport.unwrapSearchHits(aggregatedPage);
}
// endregion
/**
* Does a suggest query
*
* @param suggestion the query
* @param index the index to run the query against
* @return the suggest response
*/
SearchResponse suggest(SuggestBuilder suggestion, IndexCoordinates index);
/**
* Execute the query against elasticsearch and return the first returned object.
*
* @param query the query to execute
* @param clazz the entity clazz used for property mapping and indexname extraction
* @return the first found object
*/
@Nullable
default <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.
*
@ -308,6 +297,16 @@ public interface SearchOperations {
*/
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}
*
@ -319,6 +318,16 @@ public interface SearchOperations {
*/
<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.
*
@ -331,34 +340,16 @@ public interface SearchOperations {
<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 query The search query.
* @param clazz The class of entity to retrieve.
* @param index the index to run the query against
* @return scrolled page result
* @param <T> element return type
* @param query the query to execute
* @param clazz the entity clazz used for property mapping and index name extraction
* @return a {@link CloseableIterator} that wraps an Elasticsearch scroll context that needs to be closed in case of *
* error.
*/
<T> ScrolledPage<SearchHit<T>> searchScrollStart(long scrollTimeInMillis, 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);
<T> CloseableIterator<SearchHit<T>> searchForStream(Query query, Class<T> clazz);
/**
* Executes the given {@link Query} against elasticsearch and return result as {@link CloseableIterator}.
@ -372,13 +363,4 @@ public interface SearchOperations {
* error.
*/
<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}.
* @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");

View File

@ -46,7 +46,7 @@ class MapDocument implements Document {
this(new LinkedHashMap<>());
}
MapDocument(Map<String, Object> documentAsMap) {
MapDocument(Map<String, ? extends Object> 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 java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@ -56,6 +57,7 @@ abstract class AbstractQuery implements Query {
@Nullable protected Integer maxResults;
@Nullable protected HighlightQuery highlightQuery;
private boolean trackTotalHits = false;
@Nullable private Duration scrollTime;
@Override
@Nullable
@ -226,4 +228,15 @@ abstract class AbstractQuery implements Query {
public boolean getTrackTotalHits() {
return trackTotalHits;
}
@Nullable
@Override
public Duration getScrollTime() {
return scrollTime;
}
@Override
public void setScrollTime(@Nullable Duration scrollTime) {
this.scrollTime = scrollTime;
}
}

View File

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

View File

@ -24,7 +24,9 @@ import org.springframework.lang.Nullable;
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Peter-Josef Meisch
* @deprecated since 4.0, use {@link Query} implementations and set {@link Query#setScrollTimeInMillis(Long)} and {@link Query#getMaxResults()}
*/
@Deprecated
public class DeleteQuery {
@Nullable private QueryBuilder query;

View File

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

View File

@ -69,7 +69,12 @@ public class IndexQuery {
this.source = source;
}
/**
* @deprecated from 4.0. Elasticsearch 7 does not support the parent id in an index request. parent/child relations
* must be modeled using the join datatype. Setting it here will have no effect.
*/
@Nullable
@Deprecated
public String getParentId() {
return parentId;
}

View File

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

View File

@ -15,6 +15,7 @@
*/
package org.springframework.data.elasticsearch.core.query;
import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
@ -45,7 +46,7 @@ public interface Query {
Pageable DEFAULT_PAGE = PageRequest.of(0, DEFAULT_PAGE_SIZE);
/**
* Get get a {@link Query} that matches all documents in the index.
* Get a {@link Query} that matches all documents in the index.
*
* @return new instance of {@link Query}.
* @since 3.2
@ -229,4 +230,29 @@ public interface Query {
* @since 4.0
*/
boolean getTrackTotalHits();
/**
* For queries that are used in delete request, these are internally handled by Elasticsearch as scroll/bulk delete queries.
*
* @return the scrolltime settings
* @since 4.0
*/
@Nullable
Duration getScrollTime();
/**
* For queries that are used in delete request, these are internally handled by Elasticsearch as scroll/bulk delete queries.
*
* @param scrollTime the scrolltime settings
* @since 4.0
*/
void setScrollTime(@Nullable Duration scrollTime);
/**
* @return {@literal true} if scrollTimeMillis is set.
* @since 4.0
*/
default boolean hasScrollTime() {
return getScrollTime() != null;
}
}

View File

@ -15,43 +15,168 @@
*/
package org.springframework.data.elasticsearch.core.query;
import org.elasticsearch.action.update.UpdateRequest;
import java.util.Map;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.lang.Nullable;
/**
* Defines an update request.
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Peter-Josef Meisch
* @see <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html>docs</a>
*/
public class UpdateQuery {
@Nullable private String id;
@Nullable private UpdateRequest updateRequest;
private boolean doUpsert;
private String id;
@Nullable private String script;
@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() {
return id;
}
public void setId(String id) {
this.id = id;
@Nullable
public String getScript() {
return script;
}
@Nullable
public UpdateRequest getUpdateRequest() {
return updateRequest;
public Map<String, Object> getParams() {
return params;
}
public void setUpdateRequest(UpdateRequest updateRequest) {
this.updateRequest = updateRequest;
@Nullable
public Document getDocument() {
return document;
}
public boolean DoUpsert() {
return doUpsert;
@Nullable
public Document getUpsert() {
return upsert;
}
public void setDoUpsert(boolean doUpsert) {
this.doUpsert = doUpsert;
@Nullable
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) {
if (isDeleteQuery()) {
return (query, type, targetType, indexCoordinates) -> operations.deleteBy(query, type, indexCoordinates);
return (query, type, targetType, indexCoordinates) -> operations.delete(query, type, indexCoordinates);
} else if (isCountQuery()) {
return (query, type, targetType, indexCoordinates) -> operations.count(query, type, indexCoordinates);
} else if (isExistsQuery()) {

View File

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

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

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

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

View File

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

View File

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