Created
August 18, 2015 16:20
-
-
Save devnoo/ea35419966891d44b923 to your computer and use it in GitHub Desktop.
Spring test execution listener to clean elasticsearch when using spring data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; | |
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; | |
import org.springframework.data.elasticsearch.core.query.DeleteQuery; | |
import org.springframework.test.context.TestContext; | |
import org.springframework.test.context.support.AbstractTestExecutionListener; | |
import java.util.Collection; | |
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; | |
/** | |
* execution listener that can clear and recreate an index. | |
*/ | |
public class ElasticsearchTestExecutionListener extends AbstractTestExecutionListener { | |
@Override | |
public void beforeTestMethod(TestContext testContext) throws Exception { | |
ElasticsearchOperations elasticSearchTemplate = testContext.getApplicationContext().getBean(ElasticsearchOperations.class); | |
Collection<? extends ElasticsearchPersistentEntity<?>> persistentEntities = elasticSearchTemplate.getElasticsearchConverter().getMappingContext().getPersistentEntities(); | |
persistentEntities.stream().filter(e -> e.getParentType() == null).map(entity -> entity.getType()).forEach(entityType -> { | |
if (elasticSearchTemplate.indexExists(entityType)) { | |
DeleteQuery deleteQuery = new DeleteQuery(); | |
deleteQuery.setQuery(matchAllQuery()); | |
elasticSearchTemplate.delete(deleteQuery, entityType); | |
}else{ | |
elasticSearchTemplate.createIndex(entityType); | |
elasticSearchTemplate.putMapping(entityType); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment