From 4c206f7de5d5afb199499184df32eebe8ae887f2 Mon Sep 17 00:00:00 2001 From: "P.J.Meisch" Date: Thu, 9 May 2019 23:30:30 +0200 Subject: [PATCH] DATAES-579 - Test code cleanup. Original pull request: #283. --- .../core/ElasticsearchOperations.java | 9 +- .../core/ElasticsearchTemplate.java | 15 +- .../data/elasticsearch/InnerObjectTests.java | 73 - .../data/elasticsearch/NestedObjectTests.java | 345 +++-- .../builder/SampleInheritedEntityBuilder.java | 55 - .../client/ClusterNodesUnitTests.java | 5 +- .../MultiNodeHostProviderUnitTests.java | 5 +- .../ReactiveElasticsearchClientTests.java | 1 - .../ReactiveElasticsearchClientUnitTests.java | 2 +- ...icsearchConfigurationSupportUnitTests.java | 1 - .../EnableElasticsearchRepositoriesTests.java | 101 -- .../ElasticsearchConfigurationTests.java | 26 +- .../ElasticsearchNamespaceHandlerTests.java | 40 +- ...eNestedElasticsearchRepositoriesTests.java | 63 +- .../EnableElasticsearchRepositoriesTests.java | 186 +++ .../SampleElasticsearchRepository.java | 10 +- ...ampleUUIDKeyedElasticsearchRepository.java | 12 +- .../data/elasticsearch/core/AliasTests.java | 186 +-- .../core/DefaultEntityMapperTests.java | 122 +- .../core/DefaultResultMapperTests.java | 209 ++- .../ElasticsearchEntityMapperUnitTests.java | 75 +- .../core/ElasticsearchRestTemplateTests.java | 92 +- ...lasticsearchTemplateCustomMapperTests.java | 26 +- ...ElasticsearchTemplateParentChildTests.java | 121 +- .../core/ElasticsearchTemplateTests.java | 1182 ++++++++++++----- .../ElasticsearchTransportTemplateTests.java | 68 +- .../elasticsearch/core/LogEntityTests.java | 207 ++- .../core/MappingBuilderTests.java | 409 +++++- .../core/MappingContextBaseTests.java | 12 +- .../ReactiveElasticsearchTemplateTests.java | 88 +- ...eactiveElasticsearchTemplateUnitTests.java | 96 +- .../SimpleDynamicTemplatesMappingTests.java | 37 +- .../SimpleElasticsearchDateMappingTests.java | 68 +- ...ElasticsearchTemplateAggregationTests.java | 207 ++- .../completion/AnnotatedCompletionEntity.java | 50 - .../AnnotatedCompletionEntityBuilder.java | 59 - .../completion/CompletionAnnotatedEntity.java | 52 - .../core/completion/CompletionEntity.java | 50 - .../CompletionEntityAnnotatedBuilder.java | 61 - .../completion/CompletionEntityBuilder.java | 58 - .../completion/ContextCompletionEntity.java | 57 - .../ContextCompletionEntityBuilder.java | 57 - .../ElasticsearchTemplateCompletionTests.java | 361 +++-- ...chTemplateCompletionWithContextsTests.java | 228 +++- .../MappingElasticsearchConverterTests.java | 19 +- .../core/facet/ArticleEntity.java | 111 -- .../core/facet/ArticleEntityBuilder.java | 69 - .../ElasticsearchTemplateFacetTests.java | 647 +++++---- .../elasticsearch/core/facet/LogEntity.java | 102 -- .../core/facet/LogEntityBuilder.java | 67 - .../core/geo/AuthorMarkerEntity.java | 64 - .../core/geo/AuthorMarkerEntityBuilder.java | 53 - .../geo/ElasticsearchTemplateGeoTests.java | 437 ++++-- .../core/geo/LocationMarkerEntity.java | 51 - .../core/query/CriteriaQueryTests.java | 200 ++- .../entities/AbstractInheritedEntity.java | 50 - .../data/elasticsearch/entities/Author.java | 42 - .../data/elasticsearch/entities/Book.java | 62 - .../data/elasticsearch/entities/Car.java | 54 - .../elasticsearch/entities/CopyToEntity.java | 47 - .../entities/DoubleIDEntity.java | 70 - .../DynamicSettingAndMappingEntity.java | 61 - .../entities/FieldDynamicMappingEntity.java | 51 - .../entities/GTEVersionEntity.java | 49 - .../elasticsearch/entities/GeoEntity.java | 48 - .../elasticsearch/entities/GirlFriend.java | 59 - .../data/elasticsearch/entities/Group.java | 37 - .../elasticsearch/entities/HetroEntity1.java | 83 -- .../elasticsearch/entities/HetroEntity2.java | 83 -- .../entities/IntegerIDEntity.java | 70 - .../elasticsearch/entities/MinimalEntity.java | 31 - .../entities/NonDocumentEntity.java | 46 - .../entities/NormalizerEntity.java | 52 - .../elasticsearch/entities/ParentEntity.java | 101 -- .../data/elasticsearch/entities/Person.java | 77 -- .../entities/PersonMultipleLevelNested.java | 88 -- .../data/elasticsearch/entities/Product.java | 97 -- .../entities/SampleDateMappingEntity.java | 73 - .../SampleDynamicTemplatesEntity.java | 25 - .../SampleDynamicTemplatesEntityTwo.java | 25 - .../elasticsearch/entities/SampleEntity.java | 99 -- .../entities/SampleEntityUUIDKeyed.java | 96 -- .../entities/SampleInheritedEntity.java | 39 - .../entities/SampleMappingEntity.java | 68 - .../entities/SampleTransientEntity.java | 79 -- .../entities/SimpleRecursiveEntity.java | 34 - .../elasticsearch/entities/SpELEntity.java | 39 - .../elasticsearch/entities/StockPrice.java | 50 - .../elasticsearch/entities/SynonymEntity.java | 52 - .../UseServerConfigurationEntity.java | 28 - .../data/elasticsearch/entities/User.java | 36 - ...ImmutableElasticsearchRepositoryTests.java | 49 +- .../SampleElasticSearchBookRepository.java | 27 - .../cdi/CdiProductRepository.java | 5 +- .../repositories/cdi/CdiRepositoryTests.java | 266 +++- .../cdi/QualifiedProductRepository.java | 3 +- .../cdi/SamplePersonRepository.java | 3 +- .../ComplexCustomMethodRepositoryTests.java | 105 ++ .../ComplexElasticsearchRepository.java | 5 +- .../ComplexElasticsearchRepositoryCustom.java | 2 +- .../ComplexElasticsearchRepositoryImpl.java | 2 +- ...stomMethodRepositoryManualWiringTests.java | 104 ++ .../ComplexElasticsearchRepositoryCustom.java | 10 + ...exElasticsearchRepositoryManualWiring.java | 6 +- ...asticsearchRepositoryManualWiringImpl.java | 3 +- .../custom/SampleCustomMethodRepository.java | 132 -- .../CustomMethodRepositoryBaseTests.java | 504 ++++--- .../CustomMethodRepositoryRestTests.java | 25 +- .../CustomMethodRepositoryTests.java | 25 +- .../doubleid/DoubleIDRepository.java | 28 - .../doubleid}/DoubleIDRepositoryTests.java | 88 +- .../index/CreateIndexFalseEntity.java | 17 - .../index/CreateIndexFalseRepository.java | 10 - .../CreateIndexFalseRepositoryTests.java | 34 - .../geo/SpringDataGeoRepository.java | 11 - .../geo/SpringDataGeoRepositoryTests.java | 76 +- .../integer/IntegerIDRepository.java | 28 - .../integer}/IntegerIDRepositoryTests.java | 84 +- .../nestedobject/InnerObjectTests.java | 137 ++ .../NonDocumentEntityRepository.java | 30 - .../nondocument}/NonDocumentEntityTests.java | 43 +- .../repositories/query/ProductRepository.java | 43 - ...amicSettingAndMappingEntityRepository.java | 28 - ...ettingAndMappingEntityRepositoryTests.java | 168 --- .../FieldDynamicMappingEntityRepository.java | 28 - ...ldDynamicMappingEntityRepositoryTests.java | 86 -- ...ettingAndMappingEntityRepositoryTests.java | 216 +++ ...ldDynamicMappingEntityRepositoryTests.java | 119 ++ .../spel}/SpELEntityTests.java | 69 +- .../repositories/spel/SpELRepository.java | 29 - .../synonym/SynonymRepository.java | 28 - .../synonym/SynonymRepositoryTests.java | 74 +- .../UUIDElasticsearchRepositoryTests.java | 243 +++- ...stomMethodRepositoryManualWiringTests.java | 60 - .../ComplexCustomMethodRepositoryTests.java | 60 - ...asticsearchRepositoriesRegistrarTests.java | 47 +- .../ElasticsearchStringQueryUnitTests.java | 149 ++- ...tiveElasticsearchQueryMethodUnitTests.java | 150 ++- ...tiveElasticsearchStringQueryUnitTests.java | 151 ++- .../query/keywords/QueryKeywordsTests.java | 232 ++++ .../ElasticsearchRepositoryFactoryTests.java | 5 +- .../support/QueryKeywordsTests.java | 145 -- ...eReactiveElasticsearchRepositoryTests.java | 53 +- .../SimpleElasticsearchRepositoryTests.java | 257 +++- .../elasticsearch/utils/IndexInitializer.java | 21 + ...m-method-repository-manual-wiring-test.xml | 4 +- .../complex-custom-method-repository-test.xml | 2 +- .../custom-method-repository-rest-test.xml | 5 +- .../custom-method-repository-test.xml | 5 +- .../resources/double-id-repository-test.xml | 21 +- src/test/resources/dynamic-settings-test.xml | 3 +- .../existing-index-repository-test.xml | 3 +- ...rt.xml => field-dynamic-settings-test.xml} | 5 +- .../resources/immutable-repository-test.xml | 3 +- .../resources/integer-id-repository-test.xml | 3 +- .../config/{ => namespace}/namespace.xml | 3 +- .../repository-non-document-entity.xml | 4 +- .../resources/repository-query-keywords.xml | 20 + .../repository-spring-data-geo-support.xml | 19 +- .../repository-test-nested-object-books.xml | 19 +- src/test/resources/simple-repository-test.xml | 3 +- src/test/resources/spel-repository-test.xml | 3 +- src/test/resources/synonym-test.xml | 21 +- .../resources/uuidkeyed-repository-test.xml | 20 + 164 files changed, 7454 insertions(+), 6143 deletions(-) delete mode 100644 src/test/java/org/springframework/data/elasticsearch/InnerObjectTests.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/builder/SampleInheritedEntityBuilder.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/config/EnableElasticsearchRepositoriesTests.java rename src/test/java/org/springframework/data/elasticsearch/config/{ => abstractelasticsearchconfiguration}/ElasticsearchConfigurationTests.java (67%) rename src/test/java/org/springframework/data/elasticsearch/config/{ => namespace}/ElasticsearchNamespaceHandlerTests.java (54%) rename src/test/java/org/springframework/data/elasticsearch/config/{ => nested}/EnableNestedElasticsearchRepositoriesTests.java (52%) create mode 100644 src/test/java/org/springframework/data/elasticsearch/config/notnested/EnableElasticsearchRepositoriesTests.java rename src/test/java/org/springframework/data/elasticsearch/{repositories/sample => config/notnested}/SampleElasticsearchRepository.java (69%) rename src/test/java/org/springframework/data/elasticsearch/{repositories/sample => config/notnested}/SampleUUIDKeyedElasticsearchRepository.java (64%) delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/completion/AnnotatedCompletionEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/completion/AnnotatedCompletionEntityBuilder.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionAnnotatedEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntityAnnotatedBuilder.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntityBuilder.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/completion/ContextCompletionEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/completion/ContextCompletionEntityBuilder.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntityBuilder.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntityBuilder.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntityBuilder.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/core/geo/LocationMarkerEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/AbstractInheritedEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/Author.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/Book.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/Car.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/CopyToEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/DoubleIDEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/DynamicSettingAndMappingEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/FieldDynamicMappingEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/GTEVersionEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/GeoEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/GirlFriend.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/Group.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/HetroEntity1.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/HetroEntity2.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/IntegerIDEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/MinimalEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/NonDocumentEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/NormalizerEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/ParentEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/Person.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/PersonMultipleLevelNested.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/Product.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SampleDateMappingEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SampleDynamicTemplatesEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SampleDynamicTemplatesEntityTwo.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SampleEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SampleEntityUUIDKeyed.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SampleInheritedEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SampleMappingEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SampleTransientEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SimpleRecursiveEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SpELEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/StockPrice.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/SynonymEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/UseServerConfigurationEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/entities/User.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/book/SampleElasticSearchBookRepository.java create mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexCustomMethodRepositoryTests.java rename src/test/java/org/springframework/data/elasticsearch/{repository/complex => repositories/complex/custommethod/autowiring}/ComplexElasticsearchRepository.java (79%) rename src/test/java/org/springframework/data/elasticsearch/{repository/complex => repositories/complex/custommethod/autowiring}/ComplexElasticsearchRepositoryCustom.java (89%) rename src/test/java/org/springframework/data/elasticsearch/{repository/complex => repositories/complex/custommethod/autowiring}/ComplexElasticsearchRepositoryImpl.java (82%) create mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexCustomMethodRepositoryManualWiringTests.java create mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexElasticsearchRepositoryCustom.java rename src/test/java/org/springframework/data/elasticsearch/{repository/complex => repositories/complex/custommethod/manualwiring}/ComplexElasticsearchRepositoryManualWiring.java (69%) rename src/test/java/org/springframework/data/elasticsearch/{repository/complex => repositories/complex/custommethod/manualwiring}/ComplexElasticsearchRepositoryManualWiringImpl.java (83%) delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/custom/SampleCustomMethodRepository.java rename src/test/java/org/springframework/data/elasticsearch/repositories/{ => custommethod}/CustomMethodRepositoryBaseTests.java (77%) rename src/test/java/org/springframework/data/elasticsearch/repositories/{ => custommethod}/CustomMethodRepositoryRestTests.java (57%) rename src/test/java/org/springframework/data/elasticsearch/repositories/{ => custommethod}/CustomMethodRepositoryTests.java (58%) delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepository.java rename src/test/java/org/springframework/data/elasticsearch/{repository/support => repositories/doubleid}/DoubleIDRepositoryTests.java (61%) delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseEntity.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseRepository.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseRepositoryTests.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepository.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepository.java rename src/test/java/org/springframework/data/elasticsearch/{repository/support => repositories/integer}/IntegerIDRepositoryTests.java (62%) create mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/nestedobject/InnerObjectTests.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/nondocument/NonDocumentEntityRepository.java rename src/test/java/org/springframework/data/elasticsearch/{ => repositories/nondocument}/NonDocumentEntityTests.java (54%) delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/query/ProductRepository.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/setting/DynamicSettingAndMappingEntityRepository.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/setting/DynamicSettingAndMappingEntityRepositoryTests.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/setting/FieldDynamicMappingEntityRepository.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/setting/FieldDynamicMappingEntityRepositoryTests.java create mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/setting/dynamic/DynamicSettingAndMappingEntityRepositoryTests.java create mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/setting/fielddynamic/FieldDynamicMappingEntityRepositoryTests.java rename src/test/java/org/springframework/data/elasticsearch/{ => repositories/spel}/SpELEntityTests.java (62%) delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELRepository.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepository.java rename src/test/java/org/springframework/data/elasticsearch/{repository/support => repositories/uuidkeyed}/UUIDElasticsearchRepositoryTests.java (77%) delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryManualWiringTests.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryTests.java create mode 100644 src/test/java/org/springframework/data/elasticsearch/repository/query/keywords/QueryKeywordsTests.java delete mode 100644 src/test/java/org/springframework/data/elasticsearch/repository/support/QueryKeywordsTests.java rename src/test/java/org/springframework/data/elasticsearch/repository/support/{ => simple}/SimpleElasticsearchRepositoryTests.java (75%) create mode 100644 src/test/java/org/springframework/data/elasticsearch/utils/IndexInitializer.java rename src/test/resources/{repository-query-support.xml => field-dynamic-settings-test.xml} (80%) rename src/test/resources/org/springframework/data/elasticsearch/config/{ => namespace}/namespace.xml (94%) create mode 100644 src/test/resources/repository-query-keywords.xml create mode 100644 src/test/resources/uuidkeyed-repository-test.xml diff --git a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java index 0f1b6108f..904a51828 100755 --- a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java @@ -37,6 +37,7 @@ import java.util.stream.Collectors; * @author Kevin Leturc * @author Zetang Zeng * @author Dmitriy Yakovlev + * @author Peter-Josef Meisch */ public interface ElasticsearchOperations { @@ -108,7 +109,7 @@ public interface ElasticsearchOperations { * @param clazz * @param */ - Map getMapping(Class clazz); + Map getMapping(Class clazz); /** * Get mapping for a given indexName and type @@ -116,21 +117,21 @@ public interface ElasticsearchOperations { * @param indexName * @param type */ - Map getMapping(String indexName, String type); + Map getMapping(String indexName, String type); /** * Get settings for a given indexName * * @param indexName */ - Map getSetting(String indexName); + Map getSetting(String indexName); /** * Get settings for a given class * * @param clazz */ - Map getSetting(Class clazz); + Map getSetting(Class clazz); /** diff --git a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java index d6bc220ec..ffc20a141 100755 --- a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java @@ -124,6 +124,7 @@ import org.springframework.util.StringUtils; * @author Ivan Greene * @author Christoph Strobl * @author Dmitriy Yakovlev + * @author Peter-Josef Meisch */ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient, ApplicationContextAware { @@ -234,10 +235,10 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient< } @Override - public Map getMapping(String indexName, String type) { + public Map getMapping(String indexName, String type) { Assert.notNull(indexName, "No index defined for putMapping()"); Assert.notNull(type, "No type defined for putMapping()"); - Map mappings = null; + Map mappings = null; try { mappings = client.admin().indices().getMappings(new GetMappingsRequest().indices(indexName).types(type)) .actionGet().getMappings().get(indexName).get(type).getSourceAsMap(); @@ -249,7 +250,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient< } @Override - public Map getMapping(Class clazz) { + public Map getMapping(Class clazz) { return getMapping(getPersistentEntityFor(clazz).getIndexName(), getPersistentEntityFor(clazz).getIndexType()); } @@ -1034,10 +1035,10 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient< return createIndex(getPersistentEntityFor(clazz).getIndexName(), settings); } - private Map getDefaultSettings(ElasticsearchPersistentEntity persistentEntity) { + private Map getDefaultSettings(ElasticsearchPersistentEntity persistentEntity) { if (persistentEntity.isUseServerConfiguration()) - return new HashMap(); + return new HashMap<>(); return new MapBuilder().put("index.number_of_shards", String.valueOf(persistentEntity.getShards())) .put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas())) @@ -1046,12 +1047,12 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient< } @Override - public Map getSetting(Class clazz) { + public Map getSetting(Class clazz) { return getSetting(getPersistentEntityFor(clazz).getIndexName()); } @Override - public Map getSetting(String indexName) { + public Map getSetting(String indexName) { Assert.notNull(indexName, "No index defined for getSettings"); Settings settings = client.admin().indices().getSettings(new GetSettingsRequest()).actionGet().getIndexToSettings() .get(indexName); diff --git a/src/test/java/org/springframework/data/elasticsearch/InnerObjectTests.java b/src/test/java/org/springframework/data/elasticsearch/InnerObjectTests.java deleted file mode 100644 index bb43384e1..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/InnerObjectTests.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2014-2019 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; - -import static org.apache.commons.lang.RandomStringUtils.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.Author; -import org.springframework.data.elasticsearch.entities.Book; -import org.springframework.data.elasticsearch.repositories.book.SampleElasticSearchBookRepository; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author Mohsin Husen - * @author Christoph Strobl - */ - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:/repository-test-nested-object-books.xml") -public class InnerObjectTests { - - @Autowired private SampleElasticSearchBookRepository bookRepository; - - @Autowired private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before() { - elasticsearchTemplate.deleteIndex(Book.class); - elasticsearchTemplate.createIndex(Book.class); - elasticsearchTemplate.putMapping(Book.class); - elasticsearchTemplate.refresh(Book.class); - } - - @Test - public void shouldIndexInnerObject() { - // given - String id = randomAlphanumeric(5); - Book book = new Book(); - book.setId(id); - book.setName("xyz"); - Author author = new Author(); - author.setId("1"); - author.setName("ABC"); - book.setAuthor(author); - // when - bookRepository.save(book); - // then - assertThat(bookRepository.findById(id), is(notNullValue())); - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java b/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java index 91ef0abf0..724e9820f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java @@ -16,14 +16,16 @@ package org.springframework.data.elasticsearch; import static org.apache.commons.lang.RandomStringUtils.*; +import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.*; + +import lombok.Getter; +import lombok.Setter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -35,18 +37,19 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; import org.springframework.data.domain.Page; +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.InnerField; +import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.GetQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; -import org.springframework.data.elasticsearch.entities.Author; -import org.springframework.data.elasticsearch.entities.Book; -import org.springframework.data.elasticsearch.entities.Car; -import org.springframework.data.elasticsearch.entities.GirlFriend; -import org.springframework.data.elasticsearch.entities.Person; -import org.springframework.data.elasticsearch.entities.PersonMultipleLevelNested; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -54,29 +57,20 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:/repository-test-nested-object.xml") +@ContextConfiguration("classpath:/elasticsearch-template-test.xml") public class NestedObjectTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - + @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { - elasticsearchTemplate.deleteIndex(Book.class); - elasticsearchTemplate.createIndex(Book.class); - elasticsearchTemplate.putMapping(Book.class); - elasticsearchTemplate.refresh(Book.class); - elasticsearchTemplate.deleteIndex(Person.class); - elasticsearchTemplate.createIndex(Person.class); - elasticsearchTemplate.putMapping(Person.class); - elasticsearchTemplate.refresh(Person.class); - elasticsearchTemplate.deleteIndex(PersonMultipleLevelNested.class); - elasticsearchTemplate.createIndex(PersonMultipleLevelNested.class); - elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); - elasticsearchTemplate.refresh(PersonMultipleLevelNested.class); + + IndexInitializer.init(elasticsearchTemplate, Book.class); + IndexInitializer.init(elasticsearchTemplate, Person.class); + IndexInitializer.init(elasticsearchTemplate, PersonMultipleLevelNested.class); } @Test @@ -126,81 +120,79 @@ public class NestedObjectTests { indexQueries.add(indexQuery1); indexQueries.add(indexQuery2); - elasticsearchTemplate.putMapping(Person.class); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(Person.class); - final QueryBuilder builder = nestedQuery("car", boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None); + final QueryBuilder builder = nestedQuery("car", + boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None); final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); final List persons = elasticsearchTemplate.queryForList(searchQuery, Person.class); - assertThat(persons.size(), is(1)); + assertThat(persons).hasSize(1); } @Test public void shouldIndexMultipleLevelNestedObject() { - //given + + // given final List indexQueries = createPerson(); - //when - elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); + // when elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(PersonMultipleLevelNested.class); - //then + // then final GetQuery getQuery = new GetQuery(); getQuery.setId("1"); - final PersonMultipleLevelNested personIndexed = elasticsearchTemplate.queryForObject(getQuery, PersonMultipleLevelNested.class); - assertThat(personIndexed, is(notNullValue())); + final PersonMultipleLevelNested personIndexed = elasticsearchTemplate.queryForObject(getQuery, + PersonMultipleLevelNested.class); + assertThat(personIndexed).isNotNull(); } @Test public void shouldIndexMultipleLevelNestedObjectWithIncludeInParent() { - //given + + // given final List indexQueries = createPerson(); - //when - elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); + // when elasticsearchTemplate.bulkIndex(indexQueries); + // then + final Map mapping = elasticsearchTemplate.getMapping(PersonMultipleLevelNested.class); - final Map mapping = elasticsearchTemplate.getMapping(PersonMultipleLevelNested.class); - - assertThat(mapping, is(notNullValue())); - final Map propertyMap = (Map) mapping.get("properties"); - assertThat(propertyMap, is(notNullValue())); + assertThat(mapping).isNotNull(); + final Map propertyMap = (Map) mapping.get("properties"); + assertThat(propertyMap).isNotNull(); final Map bestCarsAttributes = (Map) propertyMap.get("bestCars"); - assertThat(bestCarsAttributes.get("include_in_parent"), is(notNullValue())); + assertThat(bestCarsAttributes.get("include_in_parent")).isNotNull(); } - @Test public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject() { - //given + + // given final List indexQueries = createPerson(); - //when - elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); + // when elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(PersonMultipleLevelNested.class); - //then + // then final BoolQueryBuilder builder = boolQuery(); - builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"),ScoreMode.None)) - .must(nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()),ScoreMode.None)); + builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"), ScoreMode.None)).must( + nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()), ScoreMode.None)); - final SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(builder) - .build(); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); - final Page personIndexed = elasticsearchTemplate.queryForPage(searchQuery, PersonMultipleLevelNested.class); - assertThat(personIndexed, is(notNullValue())); - assertThat(personIndexed.getTotalElements(), is(1L)); - assertThat(personIndexed.getContent().get(0).getId(), is("1")); + final Page personIndexed = elasticsearchTemplate.queryForPage(searchQuery, + PersonMultipleLevelNested.class); + assertThat(personIndexed).isNotNull(); + assertThat(personIndexed.getTotalElements()).isEqualTo(1); + assertThat(personIndexed.getContent().get(0).getId()).isEqualTo("1"); } - private List createPerson() { final PersonMultipleLevelNested person1 = new PersonMultipleLevelNested(); @@ -245,7 +237,7 @@ public class NestedObjectTests { person2.setId("2"); person2.setName("name"); - person2.setGirlFriends(Arrays.asList(permanent)); + person2.setGirlFriends(Collections.singletonList(permanent)); final IndexQuery indexQuery2 = new IndexQuery(); indexQuery2.setId(person2.getId()); @@ -261,6 +253,7 @@ public class NestedObjectTests { @Test public void shouldSearchBooksForPersonInitialLevelNestedType() { + // given final List cars = new ArrayList<>(); final Car saturn = new Car(); @@ -322,24 +315,24 @@ public class NestedObjectTests { indexQueries.add(indexQuery1); indexQueries.add(indexQuery2); - elasticsearchTemplate.putMapping(Person.class); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(Person.class); - final QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")), ScoreMode.None); + // when + final QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")), + ScoreMode.None); final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); final List persons = elasticsearchTemplate.queryForList(searchQuery, Person.class); - assertThat(persons.size(), is(1)); + // then + assertThat(persons).hasSize(1); } - /* - DATAES-73 - */ - @Test + @Test // DATAES-73 public void shouldIndexAndSearchMapAsNestedType() { - //given + + // given final Book book1 = new Book(); final Book book2 = new Book(); @@ -369,17 +362,221 @@ public class NestedObjectTests { indexQueries.add(indexQuery1); indexQueries.add(indexQuery2); - //when + + // when elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(Book.class); - //then + + // then final SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"),ScoreMode.None)) - .build(); + .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.None)).build(); final Page books = elasticsearchTemplate.queryForPage(searchQuery, Book.class); - assertThat(books.getContent().size(), is(1)); - assertThat(books.getContent().get(0).getId(), is(book2.getId())); + assertThat(books.getContent()).hasSize(1); + assertThat(books.getContent().get(0).getId()).isEqualTo(book2.getId()); } -} + @Setter + @Getter + @Document(indexName = "test-index-book-nested-objects", type = "book", shards = 1, replicas = 0, refreshInterval = "-1") + static class Book { + + @Id private String id; + private String name; + @Field(type = FieldType.Object) private Author author; + @Field(type = FieldType.Nested) private Map> buckets = new HashMap<>(); + @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"), + otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop", + searchAnalyzer = "standard") }) private String description; + } + + @Document(indexName = "test-index-person", type = "user", shards = 1, replicas = 0, refreshInterval = "-1") + static class Person { + + @Id private String id; + + private String name; + + @Field(type = FieldType.Nested) private List car; + + @Field(type = FieldType.Nested, includeInParent = true) private List books; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCar() { + return car; + } + + public void setCar(List car) { + this.car = car; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + } + + static class Car { + + private String name; + private String model; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + @Document(indexName = "test-index-person-multiple-level-nested", type = "user", shards = 1, replicas = 0, + refreshInterval = "-1") + static class PersonMultipleLevelNested { + + @Id private String id; + + private String name; + + @Field(type = FieldType.Nested) private List girlFriends; + + @Field(type = FieldType.Nested) private List cars; + + @Field(type = FieldType.Nested, includeInParent = true) private List bestCars; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getGirlFriends() { + return girlFriends; + } + + public void setGirlFriends(List girlFriends) { + this.girlFriends = girlFriends; + } + + public List getCars() { + return cars; + } + + public void setCars(List cars) { + this.cars = cars; + } + + public List getBestCars() { + return bestCars; + } + + public void setBestCars(List bestCars) { + this.bestCars = bestCars; + } + } + + /** + * @author Mohsin Husen + */ + + static class GirlFriend { + + private String name; + + private String type; + + @Field(type = FieldType.Nested) private List cars; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public List getCars() { + return cars; + } + + public void setCars(List cars) { + this.cars = cars; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class Author { + + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + +} diff --git a/src/test/java/org/springframework/data/elasticsearch/builder/SampleInheritedEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/builder/SampleInheritedEntityBuilder.java deleted file mode 100644 index 82c4bcff5..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/builder/SampleInheritedEntityBuilder.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2014-2019 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.builder; - -import java.util.Date; - -import org.springframework.data.elasticsearch.core.query.IndexQuery; -import org.springframework.data.elasticsearch.entities.SampleInheritedEntity; - -/** - * @author Kevin Leturc - */ -public class SampleInheritedEntityBuilder { - - private SampleInheritedEntity result; - - public SampleInheritedEntityBuilder(String id) { - result = new SampleInheritedEntity(); - result.setId(id); - } - - public SampleInheritedEntityBuilder createdDate(Date createdDate) { - result.setCreatedDate(createdDate); - return this; - } - - public SampleInheritedEntityBuilder message(String message) { - result.setMessage(message); - return this; - } - - public SampleInheritedEntity build() { - return result; - } - - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/client/ClusterNodesUnitTests.java b/src/test/java/org/springframework/data/elasticsearch/client/ClusterNodesUnitTests.java index a5422b803..794faf3c8 100644 --- a/src/test/java/org/springframework/data/elasticsearch/client/ClusterNodesUnitTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/client/ClusterNodesUnitTests.java @@ -17,9 +17,6 @@ package org.springframework.data.elasticsearch.client; import static org.assertj.core.api.Assertions.*; -import java.util.List; - -import org.elasticsearch.common.transport.TransportAddress; import org.junit.Test; /** @@ -85,6 +82,6 @@ public class ClusterNodesUnitTests { public void rejectsUnresolvableHost() { assertThatExceptionOfType(IllegalArgumentException.class) // - .isThrownBy(() -> ClusterNodes.of("mylocalhost:80")); + .isThrownBy(() -> ClusterNodes.of("mylocalhost.invalid.:80")); } } diff --git a/src/test/java/org/springframework/data/elasticsearch/client/reactive/MultiNodeHostProviderUnitTests.java b/src/test/java/org/springframework/data/elasticsearch/client/reactive/MultiNodeHostProviderUnitTests.java index e90e791c0..e2c781a1b 100644 --- a/src/test/java/org/springframework/data/elasticsearch/client/reactive/MultiNodeHostProviderUnitTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/client/reactive/MultiNodeHostProviderUnitTests.java @@ -18,7 +18,6 @@ package org.springframework.data.elasticsearch.client.reactive; import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; -import org.springframework.data.elasticsearch.client.reactive.HostProvider.Verification; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -26,6 +25,7 @@ import org.junit.Before; import org.junit.Test; import org.springframework.data.elasticsearch.client.ElasticsearchHost; import org.springframework.data.elasticsearch.client.ElasticsearchHost.State; +import org.springframework.data.elasticsearch.client.reactive.HostProvider.Verification; import org.springframework.data.elasticsearch.client.reactive.ReactiveMockClientTestsUtils.MockDelegatingElasticsearchHostProvider; import org.springframework.data.elasticsearch.client.reactive.ReactiveMockClientTestsUtils.MockWebClientProvider.Receive; import org.springframework.web.reactive.function.client.ClientResponse; @@ -106,8 +106,7 @@ public class MultiNodeHostProviderUnitTests { provider.clusterInfo().as(StepVerifier::create).expectNextCount(1).verifyComplete(); - provider.getActive(Verification.ACTIVE).as(StepVerifier::create).expectNext(mock.client(HOST_2)) - .verifyComplete(); + provider.getActive(Verification.ACTIVE).as(StepVerifier::create).expectNext(mock.client(HOST_2)).verifyComplete(); verify(mock.client(HOST_2), times(2)).head(); } diff --git a/src/test/java/org/springframework/data/elasticsearch/client/reactive/ReactiveElasticsearchClientTests.java b/src/test/java/org/springframework/data/elasticsearch/client/reactive/ReactiveElasticsearchClientTests.java index 45b2d019c..406957220 100644 --- a/src/test/java/org/springframework/data/elasticsearch/client/reactive/ReactiveElasticsearchClientTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/client/reactive/ReactiveElasticsearchClientTests.java @@ -53,7 +53,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; - import org.springframework.data.elasticsearch.ElasticsearchVersion; import org.springframework.data.elasticsearch.ElasticsearchVersionRule; import org.springframework.data.elasticsearch.TestUtils; diff --git a/src/test/java/org/springframework/data/elasticsearch/client/reactive/ReactiveElasticsearchClientUnitTests.java b/src/test/java/org/springframework/data/elasticsearch/client/reactive/ReactiveElasticsearchClientUnitTests.java index 9c49af24e..dab800a52 100644 --- a/src/test/java/org/springframework/data/elasticsearch/client/reactive/ReactiveElasticsearchClientUnitTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/client/reactive/ReactiveElasticsearchClientUnitTests.java @@ -16,7 +16,7 @@ package org.springframework.data.elasticsearch.client.reactive; import static org.assertj.core.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import static org.springframework.data.elasticsearch.client.reactive.ReactiveMockClientTestsUtils.MockWebClientProvider.Receive.*; diff --git a/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchConfigurationSupportUnitTests.java b/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchConfigurationSupportUnitTests.java index 1eafe5c53..d7b13a059 100644 --- a/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchConfigurationSupportUnitTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchConfigurationSupportUnitTests.java @@ -24,7 +24,6 @@ import java.util.Collections; import org.apache.commons.lang.ClassUtils; import org.elasticsearch.client.RestHighLevelClient; import org.junit.Test; - import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/src/test/java/org/springframework/data/elasticsearch/config/EnableElasticsearchRepositoriesTests.java b/src/test/java/org/springframework/data/elasticsearch/config/EnableElasticsearchRepositoriesTests.java deleted file mode 100644 index beee82ab8..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/config/EnableElasticsearchRepositoriesTests.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2013-15 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.config; - -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; - -import java.util.Arrays; - -import org.elasticsearch.node.NodeValidationException; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.elasticsearch.Utils; -import org.springframework.data.elasticsearch.core.ElasticsearchOperations; -import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.SampleEntity; -import org.springframework.data.elasticsearch.repositories.sample.SampleElasticsearchRepository; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; -import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; -import org.springframework.data.repository.Repository; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - * @author Kevin Leturc - * @author Gad Akuka - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration -public class EnableElasticsearchRepositoriesTests implements ApplicationContextAware { - - ApplicationContext context; - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.context = applicationContext; - } - - @Configuration - @EnableElasticsearchRepositories(basePackages = {"org.springframework.data.elasticsearch.repositories.sample", - "org.springframework.data.elasticsearch.config"}) - static class Config { - - @Bean - public ElasticsearchOperations elasticsearchTemplate() throws NodeValidationException { - return new ElasticsearchTemplate(Utils.getNodeClient()); - } - } - - @Autowired - private SampleElasticsearchRepository repository; - - @Autowired(required = false) - private SampleRepository nestedRepository; - - interface SampleRepository extends Repository {}; - - @Test - public void bootstrapsRepository() { - assertThat(repository, is(notNullValue())); - } - - @Test - public void shouldScanSelectedPackage() { - //given - - //when - String[] beanNamesForType = context.getBeanNamesForType(ElasticsearchRepository.class); - - //then - assertThat(beanNamesForType.length, is(2)); - assertTrue(Arrays.asList(beanNamesForType).contains("sampleElasticsearchRepository")); - assertTrue(Arrays.asList(beanNamesForType).contains("sampleUUIDKeyedElasticsearchRepository")); - } - - @Test - public void hasNotNestedRepository() { - assertNull(nestedRepository); - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchConfigurationTests.java b/src/test/java/org/springframework/data/elasticsearch/config/abstractelasticsearchconfiguration/ElasticsearchConfigurationTests.java similarity index 67% rename from src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchConfigurationTests.java rename to src/test/java/org/springframework/data/elasticsearch/config/abstractelasticsearchconfiguration/ElasticsearchConfigurationTests.java index 2a44f47ef..a8feb7572 100644 --- a/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchConfigurationTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/abstractelasticsearchconfiguration/ElasticsearchConfigurationTests.java @@ -13,19 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.config; +package org.springframework.data.elasticsearch.config.abstractelasticsearchconfiguration; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; import org.elasticsearch.client.RestHighLevelClient; import org.junit.Test; import org.junit.runner.RunWith; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; -import org.springframework.data.elasticsearch.repositories.existing.index.CreateIndexFalseRepository; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -47,8 +48,8 @@ public class ElasticsearchConfigurationTests { @Configuration @EnableElasticsearchRepositories( - basePackages = { "org.springframework.data.elasticsearch.repositories.existing.index", - "org.springframework.data.elasticsearch.config" }) + basePackages = { "org.springframework.data.elasticsearch.config.abstractelasticsearchconfiguration" }, + considerNestedRepositories = true) static class Config extends AbstractElasticsearchConfiguration { @Override @@ -60,6 +61,15 @@ public class ElasticsearchConfigurationTests { @Test // DATAES-563 public void bootstrapsRepository() { - assertThat(repository, is(notNullValue())); + + assertThat(repository).isNotNull(); } + + @Document(indexName = "test-index-config-abstractelasticsearchconfiguraiton", type = "test-type", createIndex = false) + static class CreateIndexFalseEntity { + + @Id private String id; + } + + interface CreateIndexFalseRepository extends ElasticsearchRepository {} } diff --git a/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java b/src/test/java/org/springframework/data/elasticsearch/config/namespace/ElasticsearchNamespaceHandlerTests.java similarity index 54% rename from src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java rename to src/test/java/org/springframework/data/elasticsearch/config/namespace/ElasticsearchNamespaceHandlerTests.java index 6281a6d49..76e254f61 100644 --- a/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/namespace/ElasticsearchNamespaceHandlerTests.java @@ -13,19 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.config; +package org.springframework.data.elasticsearch.config.namespace; -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.client.RestClientFactoryBean; import org.springframework.data.elasticsearch.client.TransportClientFactoryBean; -import org.springframework.data.elasticsearch.repositories.sample.SampleElasticsearchRepository; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -33,31 +33,41 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Rizwan Idrees * @author Mohsin Husen * @author Don Wellington + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("namespace.xml") public class ElasticsearchNamespaceHandlerTests { - @Autowired - private ApplicationContext context; + @Autowired private ApplicationContext context; @Test public void shouldCreateTransportClient() { - assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue())); - assertThat(context.getBean(TransportClientFactoryBean.class), is(instanceOf(TransportClientFactoryBean.class))); + + assertThat(context.getBean(TransportClientFactoryBean.class)).isNotNull(); + assertThat(context.getBean(TransportClientFactoryBean.class)).isInstanceOf(TransportClientFactoryBean.class); } @Test public void shouldCreateRepository() { - assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue())); - assertThat(context.getBean(SampleElasticsearchRepository.class), - is(instanceOf(SampleElasticsearchRepository.class))); + + assertThat(context.getBean(TransportClientFactoryBean.class)).isNotNull(); + assertThat(context.getBean(CreateIndexFalseRepository.class)).isInstanceOf(CreateIndexFalseRepository.class); } - + @Test public void shouldCreateRestClient() { - assertThat(context.getBean(RestClientFactoryBean.class), is(notNullValue())); - assertThat(context.getBean(RestClientFactoryBean.class), is(instanceOf(RestClientFactoryBean.class))); + + assertThat(context.getBean(RestClientFactoryBean.class)).isNotNull(); + assertThat(context.getBean(RestClientFactoryBean.class)).isInstanceOf(RestClientFactoryBean.class); } + + @Document(indexName = "test-index-config-namespace", type = "test-type", createIndex = false) + static class CreateIndexFalseEntity { + + @Id private String id; + } + + interface CreateIndexFalseRepository extends ElasticsearchRepository {} } diff --git a/src/test/java/org/springframework/data/elasticsearch/config/EnableNestedElasticsearchRepositoriesTests.java b/src/test/java/org/springframework/data/elasticsearch/config/nested/EnableNestedElasticsearchRepositoriesTests.java similarity index 52% rename from src/test/java/org/springframework/data/elasticsearch/config/EnableNestedElasticsearchRepositoriesTests.java rename to src/test/java/org/springframework/data/elasticsearch/config/nested/EnableNestedElasticsearchRepositoriesTests.java index 7b66c6d97..7f895fdf7 100644 --- a/src/test/java/org/springframework/data/elasticsearch/config/EnableNestedElasticsearchRepositoriesTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/nested/EnableNestedElasticsearchRepositoriesTests.java @@ -13,9 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.config; +package org.springframework.data.elasticsearch.config.nested; import static org.junit.Assert.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.lang.Double; +import java.lang.Long; import org.elasticsearch.node.NodeValidationException; import org.junit.Test; @@ -23,10 +34,16 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; import org.springframework.data.elasticsearch.Utils; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +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.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.SampleEntity; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; import org.springframework.data.repository.Repository; import org.springframework.test.context.ContextConfiguration; @@ -34,29 +51,59 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Kevin Leturc + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class EnableNestedElasticsearchRepositoriesTests { @Configuration - @EnableElasticsearchRepositories(basePackages = {"org.springframework.data.elasticsearch.repositories.sample", - "org.springframework.data.elasticsearch.config"}, considerNestedRepositories = true) + @EnableElasticsearchRepositories(basePackages = { "org.springframework.data.elasticsearch.config.nested" }, + considerNestedRepositories = true) static class Config { @Bean public ElasticsearchOperations elasticsearchTemplate() throws NodeValidationException { return new ElasticsearchTemplate(Utils.getNodeClient()); } + } - @Autowired(required = false) - private SampleRepository nestedRepository; - - interface SampleRepository extends Repository {}; + @Autowired(required = false) private SampleRepository nestedRepository; + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ @Test public void hasNestedRepository() { assertNotNull(nestedRepository); } + + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-config-nested", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + + @Score private float score; + + } + + interface SampleRepository extends Repository {} } diff --git a/src/test/java/org/springframework/data/elasticsearch/config/notnested/EnableElasticsearchRepositoriesTests.java b/src/test/java/org/springframework/data/elasticsearch/config/notnested/EnableElasticsearchRepositoriesTests.java new file mode 100644 index 000000000..dc9c13c83 --- /dev/null +++ b/src/test/java/org/springframework/data/elasticsearch/config/notnested/EnableElasticsearchRepositoriesTests.java @@ -0,0 +1,186 @@ +/* + * Copyright 2013-15 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.config.notnested; + +import static org.assertj.core.api.Assertions.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.lang.Double; +import java.lang.Long; +import java.util.UUID; + +import org.elasticsearch.node.NodeValidationException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; +import org.springframework.data.elasticsearch.Utils; +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.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; +import org.springframework.data.elasticsearch.utils.IndexInitializer; +import org.springframework.data.repository.Repository; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Kevin Leturc + * @author Gad Akuka + * @author Peter-Josef Meisch + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +public class EnableElasticsearchRepositoriesTests implements ApplicationContextAware { + + ApplicationContext context; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + + this.context = applicationContext; + } + + @Configuration + @EnableElasticsearchRepositories(basePackages = { "org.springframework.data.elasticsearch.config.notnested" }) + static class Config { + + @Bean + public ElasticsearchOperations elasticsearchTemplate() throws NodeValidationException { + + return new ElasticsearchTemplate(Utils.getNodeClient()); + } + } + + @Autowired ElasticsearchTemplate elasticsearchTemplate; + + @Autowired private SampleElasticsearchRepository repository; + + @Autowired(required = false) private SampleRepository nestedRepository; + + interface SampleRepository extends Repository {} + + @Before + public void before() { + + IndexInitializer.init(elasticsearchTemplate, SampleEntity.class); + } + + @Test + public void bootstrapsRepository() { + + assertThat(repository).isNotNull(); + } + + @Test + public void shouldScanSelectedPackage() { + + // given + + // when + String[] beanNamesForType = context.getBeanNamesForType(ElasticsearchRepository.class); + + // then + assertThat(beanNamesForType).containsExactlyInAnyOrder("sampleElasticsearchRepository", + "sampleUUIDKeyedElasticsearchRepository"); + } + + @Test + public void hasNotNestedRepository() { + + assertThat(nestedRepository).isNull(); + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-config-not-nested", type = "test-type", shards = 1, replicas = 0, + refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + + } + + /** + * @author Gad Akuka + * @author Rizwan Idrees + * @author Mohsin Husen + */ + + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-uuid-keyed-config-not-nested", type = "test-type-uuid-keyed", shards = 1, + replicas = 0, refreshInterval = "-1") + static class SampleEntityUUIDKeyed { + + @Id private UUID id; + private String type; + @Field(type = FieldType.Text, fielddata = true) private String message; + private int rate; + @ScriptedField private Long scriptedRate; + private boolean available; + private String highlightedMessage; + + private GeoPoint location; + + @Version private Long version; + + } +} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/sample/SampleElasticsearchRepository.java b/src/test/java/org/springframework/data/elasticsearch/config/notnested/SampleElasticsearchRepository.java similarity index 69% rename from src/test/java/org/springframework/data/elasticsearch/repositories/sample/SampleElasticsearchRepository.java rename to src/test/java/org/springframework/data/elasticsearch/config/notnested/SampleElasticsearchRepository.java index a2d74c3b0..a6c6b9e4a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/sample/SampleElasticsearchRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/notnested/SampleElasticsearchRepository.java @@ -13,11 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repositories.sample; +package org.springframework.data.elasticsearch.config.notnested; import java.util.List; -import org.springframework.data.elasticsearch.entities.SampleEntity; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** @@ -25,13 +24,14 @@ import org.springframework.data.elasticsearch.repository.ElasticsearchRepository * @author Mohsin Husen * @author Christoph Strobl */ -public interface SampleElasticsearchRepository extends ElasticsearchRepository { +public interface SampleElasticsearchRepository + extends ElasticsearchRepository { long deleteSampleEntityById(String id); - List deleteByAvailable(boolean available); + List deleteByAvailable(boolean available); - List deleteByMessage(String message); + List deleteByMessage(String message); void deleteByType(String type); diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/sample/SampleUUIDKeyedElasticsearchRepository.java b/src/test/java/org/springframework/data/elasticsearch/config/notnested/SampleUUIDKeyedElasticsearchRepository.java similarity index 64% rename from src/test/java/org/springframework/data/elasticsearch/repositories/sample/SampleUUIDKeyedElasticsearchRepository.java rename to src/test/java/org/springframework/data/elasticsearch/config/notnested/SampleUUIDKeyedElasticsearchRepository.java index 6f770bde5..51eaf9474 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/sample/SampleUUIDKeyedElasticsearchRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/notnested/SampleUUIDKeyedElasticsearchRepository.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 the original author or authors. + * Copyright 2018-2019 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. @@ -13,25 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repositories.sample; +package org.springframework.data.elasticsearch.config.notnested; import java.util.List; import java.util.UUID; -import org.springframework.data.elasticsearch.entities.SampleEntityUUIDKeyed; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * @author Gad Akuka * @author Christoph Strobl */ -public interface SampleUUIDKeyedElasticsearchRepository extends ElasticsearchRepository { +interface SampleUUIDKeyedElasticsearchRepository + extends ElasticsearchRepository { long deleteSampleEntityUUIDKeyedById(UUID id); - List deleteByAvailable(boolean available); + List deleteByAvailable(boolean available); - List deleteByMessage(String message); + List deleteByMessage(String message); void deleteByType(String type); diff --git a/src/test/java/org/springframework/data/elasticsearch/core/AliasTests.java b/src/test/java/org/springframework/data/elasticsearch/core/AliasTests.java index ff97fa9c3..f88e39af5 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/AliasTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/AliasTests.java @@ -16,10 +16,19 @@ package org.springframework.data.elasticsearch.core; import static org.apache.commons.lang.RandomStringUtils.*; +import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.lang.Double; +import java.lang.Long; +import java.lang.Object; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -29,19 +38,27 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.query.AliasBuilder; import org.springframework.data.elasticsearch.core.query.AliasQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; -import org.springframework.data.elasticsearch.entities.SampleEntity; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Mohsin Husen * @author Ilkang Na + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-test.xml") @@ -51,16 +68,18 @@ public class AliasTests { private static final String INDEX_NAME_2 = "test-alias-index-2"; private static final String TYPE_NAME = "test-alias-type"; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before() { - Map settings = new HashMap<>(); + private static Map settings = new HashMap<>(); + static { settings.put("index.refresh_interval", "-1"); settings.put("index.number_of_replicas", "0"); settings.put("index.number_of_shards", "2"); settings.put("index.store.type", "fs"); + } + + @Autowired private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { elasticsearchTemplate.deleteIndex(INDEX_NAME_1); elasticsearchTemplate.createIndex(INDEX_NAME_1, settings); @@ -69,143 +88,146 @@ public class AliasTests { elasticsearchTemplate.deleteIndex(INDEX_NAME_2); elasticsearchTemplate.createIndex(INDEX_NAME_2, settings); elasticsearchTemplate.refresh(INDEX_NAME_2); + + IndexInitializer.init(elasticsearchTemplate, SampleEntity.class); } @Test public void shouldAddAlias() { + // given String aliasName = "test-alias"; - AliasQuery aliasQuery = new AliasBuilder() - .withIndexName(INDEX_NAME_1) - .withAliasName(aliasName).build(); + AliasQuery aliasQuery = new AliasBuilder().withIndexName(INDEX_NAME_1).withAliasName(aliasName).build(); + // when elasticsearchTemplate.addAlias(aliasQuery); + // then List aliases = elasticsearchTemplate.queryForAlias(INDEX_NAME_1); - assertThat(aliases, is(notNullValue())); - assertThat(aliases.get(0).alias(), is(aliasName)); + assertThat(aliases).isNotNull(); + assertThat(aliases.get(0).alias()).isEqualTo(aliasName); } @Test public void shouldRemoveAlias() { + // given String indexName = INDEX_NAME_1; String aliasName = "test-alias"; - AliasQuery aliasQuery = new AliasBuilder() - .withIndexName(indexName) - .withAliasName(aliasName).build(); + AliasQuery aliasQuery = new AliasBuilder().withIndexName(indexName).withAliasName(aliasName).build(); + // when elasticsearchTemplate.addAlias(aliasQuery); List aliases = elasticsearchTemplate.queryForAlias(indexName); - assertThat(aliases, is(notNullValue())); - assertThat(aliases.get(0).alias(), is(aliasName)); + assertThat(aliases).isNotNull(); + assertThat(aliases.get(0).alias()).isEqualTo(aliasName); + // then elasticsearchTemplate.removeAlias(aliasQuery); aliases = elasticsearchTemplate.queryForAlias(indexName); - assertThat(aliases, anyOf(is(nullValue()), hasSize(0))); + assertThat(aliases).isEmpty(); } - /* - DATAES-70 - */ - @Test + @Test // DATAES-70 public void shouldAddAliasWithGivenRoutingValue() { - //given - String indexName = INDEX_NAME_1; + + // given String alias = "test-alias"; - AliasQuery aliasQuery = new AliasBuilder() - .withIndexName(indexName) - .withAliasName(alias) - .withRouting("0").build(); + AliasQuery aliasQuery = new AliasBuilder().withIndexName(INDEX_NAME_1).withAliasName(alias).withRouting("0") + .build(); - //when + // when elasticsearchTemplate.addAlias(aliasQuery); String documentId = randomNumeric(5); - SampleEntity sampleEntity = SampleEntity.builder().id(documentId) - .message("some message") + SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") .version(System.currentTimeMillis()).build(); - IndexQuery indexQuery = new IndexQueryBuilder() - .withIndexName(alias) - .withId(sampleEntity.getId()) - .withType(TYPE_NAME) - .withObject(sampleEntity) - .build(); + IndexQuery indexQuery = new IndexQueryBuilder().withIndexName(alias).withId(sampleEntity.getId()) + .withType(TYPE_NAME).withObject(sampleEntity).build(); elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(INDEX_NAME_1); - SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withIndices(alias).withTypes(TYPE_NAME).build(); + SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices(alias) + .withTypes(TYPE_NAME).build(); long count = elasticsearchTemplate.count(query); - //then - List aliases = elasticsearchTemplate.queryForAlias(INDEX_NAME_1); - assertThat(aliases, is(notNullValue())); - assertThat(aliases.get(0).alias(), is(alias)); - assertThat(aliases.get(0).searchRouting(), is("0")); - assertThat(aliases.get(0).indexRouting(), is("0")); - assertThat(count, is(1L)); - //cleanup + // then + List aliases = elasticsearchTemplate.queryForAlias(INDEX_NAME_1); + assertThat(aliases).isNotNull(); + final AliasMetaData aliasMetaData = aliases.get(0); + assertThat(aliasMetaData.alias()).isEqualTo(alias); + assertThat(aliasMetaData.searchRouting()).isEqualTo("0"); + assertThat(aliasMetaData.indexRouting()).isEqualTo("0"); + assertThat(count).isEqualTo(1); + + // cleanup elasticsearchTemplate.removeAlias(aliasQuery); - elasticsearchTemplate.deleteIndex(SampleEntity.class); - elasticsearchTemplate.createIndex(SampleEntity.class); - elasticsearchTemplate.putMapping(SampleEntity.class); - elasticsearchTemplate.refresh(SampleEntity.class); } - /* - DATAES-70 - */ - @Test + @Test // DATAES-70 public void shouldAddAliasForVariousRoutingValues() { - //given + + // given String alias1 = "test-alias-1"; String alias2 = "test-alias-2"; - AliasQuery aliasQuery1 = new AliasBuilder() - .withIndexName(INDEX_NAME_1) - .withAliasName(alias1) - .withIndexRouting("0").build(); + AliasQuery aliasQuery1 = new AliasBuilder().withIndexName(INDEX_NAME_1).withAliasName(alias1).withIndexRouting("0") + .build(); - AliasQuery aliasQuery2 = new AliasBuilder() - .withIndexName(INDEX_NAME_2) - .withAliasName(alias2) - .withSearchRouting("1").build(); + AliasQuery aliasQuery2 = new AliasBuilder().withIndexName(INDEX_NAME_2).withAliasName(alias2).withSearchRouting("1") + .build(); - //when + // when elasticsearchTemplate.addAlias(aliasQuery1); elasticsearchTemplate.addAlias(aliasQuery2); String documentId = randomNumeric(5); - SampleEntity sampleEntity = SampleEntity.builder().id(documentId) - .message("some message") + SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") .version(System.currentTimeMillis()).build(); - IndexQuery indexQuery = new IndexQueryBuilder() - .withIndexName(alias1) - .withType(TYPE_NAME) - .withId(sampleEntity.getId()) - .withObject(sampleEntity).build(); + IndexQuery indexQuery = new IndexQueryBuilder().withIndexName(alias1).withType(TYPE_NAME) + .withId(sampleEntity.getId()).withObject(sampleEntity).build(); elasticsearchTemplate.index(indexQuery); - // then List responseAlias1 = elasticsearchTemplate.queryForAlias(INDEX_NAME_1); - assertThat(responseAlias1, is(notNullValue())); - assertThat(responseAlias1.get(0).alias(), is(alias1)); - assertThat(responseAlias1.get(0).indexRouting(), is("0")); + assertThat(responseAlias1).isNotNull(); + final AliasMetaData aliasMetaData1 = responseAlias1.get(0); + assertThat(aliasMetaData1.alias()).isEqualTo(alias1); + assertThat(aliasMetaData1.indexRouting()).isEqualTo("0"); List responseAlias2 = elasticsearchTemplate.queryForAlias(INDEX_NAME_2); - assertThat(responseAlias2, is(notNullValue())); - assertThat(responseAlias2.get(0).alias(), is(alias2)); - assertThat(responseAlias2.get(0).searchRouting(), is("1")); + assertThat(responseAlias2).isNotNull(); + final AliasMetaData aliasMetaData2 = responseAlias2.get(0); + assertThat(aliasMetaData2.alias()).isEqualTo(alias2); + assertThat(aliasMetaData2.searchRouting()).isEqualTo("1"); - //cleanup + // cleanup elasticsearchTemplate.removeAlias(aliasQuery1); elasticsearchTemplate.removeAlias(aliasQuery2); } + + @Builder + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Document(indexName = "test-index-sample-core-alias", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/DefaultEntityMapperTests.java b/src/test/java/org/springframework/data/elasticsearch/core/DefaultEntityMapperTests.java index 78f8f2673..95fffa9dd 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/DefaultEntityMapperTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/DefaultEntityMapperTests.java @@ -17,23 +17,34 @@ package org.springframework.data.elasticsearch.core; import static org.assertj.core.api.Assertions.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.io.IOException; import java.util.Locale; import org.junit.Before; import org.junit.Test; +import org.springframework.data.annotation.Id; import org.springframework.data.annotation.ReadOnlyProperty; import org.springframework.data.annotation.Transient; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.GeoPointField; import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; -import org.springframework.data.elasticsearch.entities.Car; -import org.springframework.data.elasticsearch.entities.GeoEntity; +import org.springframework.data.geo.Box; +import org.springframework.data.geo.Circle; import org.springframework.data.geo.Point; +import org.springframework.data.geo.Polygon; /** * @author Artur Konczak * @author Mohsin Husen * @author Oliver Gierke + * @author Peter-Josef Meisch */ public class DefaultEntityMapperTests { @@ -49,62 +60,64 @@ public class DefaultEntityMapperTests { @Test public void shouldMapObjectToJsonString() throws IOException { - //Given - //When + // given + + // when String jsonResult = entityMapper.mapToString(Car.builder().model(CAR_MODEL).name(CAR_NAME).build()); - //Then + // then assertThat(jsonResult).isEqualTo(JSON_STRING); } @Test public void shouldMapJsonStringToObject() throws IOException { - //Given - //When + // given + + // when Car result = entityMapper.mapToObject(JSON_STRING, Car.class); - //Then + // then assertThat(result.getName()).isEqualTo(CAR_NAME); assertThat(result.getModel()).isEqualTo(CAR_MODEL); } @Test public void shouldMapGeoPointElasticsearchNames() throws IOException { - //given + // given final Point point = new Point(10, 20); final String pointAsString = point.getX() + "," + point.getY(); - final double[] pointAsArray = {point.getX(), point.getY()}; - final GeoEntity geoEntity = GeoEntity.builder() - .pointA(point).pointB(GeoPoint.fromPoint(point)).pointC(pointAsString).pointD(pointAsArray) - .build(); - //when + final double[] pointAsArray = { point.getX(), point.getY() }; + final GeoEntity geoEntity = GeoEntity.builder().pointA(point).pointB(GeoPoint.fromPoint(point)) + .pointC(pointAsString).pointD(pointAsArray).build(); + // when String jsonResult = entityMapper.mapToString(geoEntity); - //then + // then assertThat(jsonResult).contains(pointTemplate("pointA", point)); assertThat(jsonResult).contains(pointTemplate("pointB", point)); assertThat(jsonResult).contains(String.format(Locale.ENGLISH, "\"%s\":\"%s\"", "pointC", pointAsString)); - assertThat(jsonResult).contains(String.format(Locale.ENGLISH, "\"%s\":[%.1f,%.1f]", "pointD", pointAsArray[0], pointAsArray[1])); + assertThat(jsonResult) + .contains(String.format(Locale.ENGLISH, "\"%s\":[%.1f,%.1f]", "pointD", pointAsArray[0], pointAsArray[1])); } - + @Test // DATAES-464 public void ignoresReadOnlyProperties() throws IOException { - + // given Sample sample = new Sample(); sample.readOnly = "readOnly"; sample.property = "property"; sample.transientProperty = "transient"; sample.annotatedTransientProperty = "transient"; - + // when String result = entityMapper.mapToString(sample); - + // then assertThat(result).contains("\"property\""); - + assertThat(result).doesNotContain("readOnly"); assertThat(result).doesNotContain("transientProperty"); assertThat(result).doesNotContain("annotatedTransientProperty"); @@ -113,13 +126,74 @@ public class DefaultEntityMapperTests { private String pointTemplate(String name, Point point) { return String.format(Locale.ENGLISH, "\"%s\":{\"lat\":%.1f,\"lon\":%.1f}", name, point.getX(), point.getY()); } - + public static class Sample { - - + public @ReadOnlyProperty String readOnly; public @Transient String annotatedTransientProperty; public transient String transientProperty; public String property; } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + static class Car { + + private String name; + private String model; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + } + + /** + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-geo-core-default-entity-mapper", type = "geo-test-index", shards = 1, replicas = 0, + refreshInterval = "-1") + static class GeoEntity { + + @Id private String id; + + // geo shape - Spring Data + private Box box; + private Circle circle; + private Polygon polygon; + + // geo point - Custom implementation + Spring Data + @GeoPointField private Point pointA; + + private GeoPoint pointB; + + @GeoPointField private String pointC; + + @GeoPointField private double[] pointD; + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/DefaultResultMapperTests.java b/src/test/java/org/springframework/data/elasticsearch/core/DefaultResultMapperTests.java index 3f6ee48dd..6a0a34d0f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/DefaultResultMapperTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/DefaultResultMapperTests.java @@ -16,13 +16,20 @@ package org.springframework.data.elasticsearch.core; import static java.util.Arrays.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; +import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import java.lang.Double; +import java.lang.Long; +import java.lang.Object; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; @@ -48,13 +55,17 @@ import org.junit.runners.Parameterized.Parameters; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.core.convert.support.DefaultConversionService; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; -import org.springframework.data.elasticsearch.entities.Car; -import org.springframework.data.elasticsearch.entities.SampleEntity; import com.fasterxml.jackson.databind.util.ArrayIterator; @@ -65,6 +76,7 @@ import com.fasterxml.jackson.databind.util.ArrayIterator; * @author Mark Paluch * @author Ilkang Na * @author Christoph Strobl + * @author Peter-Josef Meisch */ @RunWith(Parameterized.class) public class DefaultResultMapperTests { @@ -99,7 +111,8 @@ public class DefaultResultMapperTests { @Test public void shouldMapAggregationsToPage() { - // Given + + // given SearchHit[] hits = { createCarHit("Ford", "Grat"), createCarHit("BMW", "Arrow") }; SearchHits searchHits = mock(SearchHits.class); when(searchHits.getTotalHits()).thenReturn(2L); @@ -109,70 +122,70 @@ public class DefaultResultMapperTests { Aggregations aggregations = new Aggregations(asList(createCarAggregation())); when(response.getAggregations()).thenReturn(aggregations); - // When - AggregatedPage page = (AggregatedPage) resultMapper.mapResults(response, Car.class, Pageable.unpaged()); + // when + AggregatedPage page = resultMapper.mapResults(response, Car.class, Pageable.unpaged()); - // Then + // then page.hasFacets(); - assertThat(page.hasAggregations(), is(true)); - assertThat(page.getAggregation("Diesel").getName(), is("Diesel")); + assertThat(page.hasAggregations()).isTrue(); + assertThat(page.getAggregation("Diesel").getName()).isEqualTo("Diesel"); } @Test public void shouldMapSearchRequestToPage() { - // Given + + // given SearchHit[] hits = { createCarHit("Ford", "Grat"), createCarHit("BMW", "Arrow") }; SearchHits searchHits = mock(SearchHits.class); when(searchHits.getTotalHits()).thenReturn(2L); when(searchHits.iterator()).thenReturn(new ArrayIterator(hits)); when(response.getHits()).thenReturn(searchHits); - // When + // when Page page = resultMapper.mapResults(response, Car.class, Pageable.unpaged()); - // Then - assertThat(page.hasContent(), is(true)); - assertThat(page.getTotalElements(), is(2L)); - assertThat(page.getContent().get(0).getName(), is("Ford")); + // then + assertThat(page.hasContent()).isTrue(); + assertThat(page.getTotalElements()).isEqualTo(2); + assertThat(page.getContent().get(0).getName()).isEqualTo("Ford"); } @Test public void shouldMapPartialSearchRequestToObject() { - // Given + + // given SearchHit[] hits = { createCarPartialHit("Ford", "Grat"), createCarPartialHit("BMW", "Arrow") }; SearchHits searchHits = mock(SearchHits.class); when(searchHits.getTotalHits()).thenReturn(2L); when(searchHits.iterator()).thenReturn(new ArrayIterator(hits)); when(response.getHits()).thenReturn(searchHits); - // When + // when Page page = resultMapper.mapResults(response, Car.class, Pageable.unpaged()); - // Then - assertThat(page.hasContent(), is(true)); - assertThat(page.getTotalElements(), is(2L)); - assertThat(page.getContent().get(0).getName(), is("Ford")); + // then + assertThat(page.hasContent()).isTrue(); + assertThat(page.getTotalElements()).isEqualTo(2); + assertThat(page.getContent().get(0).getName()).isEqualTo("Ford"); } @Test public void shouldMapGetRequestToObject() { - // Given + + // given GetResponse response = mock(GetResponse.class); when(response.getSourceAsString()).thenReturn(createJsonCar("Ford", "Grat")); - // When + // when Car result = resultMapper.mapResult(response, Car.class); - // Then - assertThat(result, notNullValue()); - assertThat(result.getModel(), is("Grat")); - assertThat(result.getName(), is("Ford")); + // then + assertThat(result).isNotNull(); + assertThat(result.getModel()).isEqualTo("Grat"); + assertThat(result.getName()).isEqualTo("Ford"); } - /** - * @see DATAES-281. - */ - @Test + @Test // DATAES-281 @Ignore("fix me - UnsupportedOperation") public void setsIdentifierOnImmutableType() { @@ -182,24 +195,26 @@ public class DefaultResultMapperTests { ImmutableEntity result = resultMapper.mapResult(response, ImmutableEntity.class); - assertThat(result, is(notNullValue())); - assertThat(result.getId(), is("identifier")); + assertThat(result).isNotNull(); + assertThat(result.getId()).isEqualTo("identifier"); } @Test // DATAES-198 public void setsVersionFromGetResponse() { + GetResponse response = mock(GetResponse.class); when(response.getSourceAsString()).thenReturn("{}"); when(response.getVersion()).thenReturn(1234L); SampleEntity result = resultMapper.mapResult(response, SampleEntity.class); - assertThat(result, is(notNullValue())); - assertThat(result.getVersion(), is(1234L)); + assertThat(result).isNotNull(); + assertThat(result.getVersion()).isEqualTo(1234); } @Test // DATAES-198 public void setsVersionFromMultiGetResponse() { + GetResponse response1 = mock(GetResponse.class); when(response1.getSourceAsString()).thenReturn("{}"); when(response1.isExists()).thenReturn(true); @@ -216,15 +231,15 @@ public class DefaultResultMapperTests { LinkedList results = resultMapper.mapResults(multiResponse, SampleEntity.class); - assertThat(results, is(notNullValue())); - assertThat(results, hasSize(2)); + assertThat(results).isNotNull().hasSize(2); - assertThat(results.get(0).getVersion(), is(1234L)); - assertThat(results.get(1).getVersion(), is(5678L)); + assertThat(results.get(0).getVersion()).isEqualTo(1234); + assertThat(results.get(1).getVersion()).isEqualTo(5678); } @Test // DATAES-198 public void setsVersionFromSearchResponse() { + SearchHit hit1 = mock(SearchHit.class); when(hit1.getSourceAsString()).thenReturn("{}"); when(hit1.getVersion()).thenReturn(1234L); @@ -243,25 +258,28 @@ public class DefaultResultMapperTests { AggregatedPage results = resultMapper.mapResults(searchResponse, SampleEntity.class, mock(Pageable.class)); - assertThat(results, is(notNullValue())); + assertThat(results).isNotNull(); - assertThat(results.getContent().get(0).getVersion(), is(1234L)); - assertThat(results.getContent().get(1).getVersion(), is(5678L)); + assertThat(results.getContent().get(0).getVersion()).isEqualTo(1234); + assertThat(results.getContent().get(1).getVersion()).isEqualTo(5678); } private Aggregation createCarAggregation() { + Aggregation aggregation = mock(Terms.class); when(aggregation.getName()).thenReturn("Diesel"); return aggregation; } private SearchHit createCarHit(String name, String model) { + SearchHit hit = mock(SearchHit.class); when(hit.getSourceAsString()).thenReturn(createJsonCar(name, model)); return hit; } private SearchHit createCarPartialHit(String name, String model) { + SearchHit hit = mock(SearchHit.class); when(hit.getSourceAsString()).thenReturn(null); when(hit.getFields()).thenReturn(createCarFields(name, model)); @@ -269,6 +287,7 @@ public class DefaultResultMapperTests { } private String createJsonCar(String name, String model) { + final String q = "\""; StringBuffer sb = new StringBuffer(); sb.append("{").append(q).append("name").append(q).append(":").append(q).append(name).append(q).append(","); @@ -277,6 +296,7 @@ public class DefaultResultMapperTests { } private Map createCarFields(String name, String model) { + Map result = new HashMap<>(); result.put("name", new DocumentField("name", asList(name))); result.put("model", new DocumentField("model", asList(model))); @@ -290,4 +310,107 @@ public class DefaultResultMapperTests { private final String id, name; } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + static class Car { + + private String name; + private String model; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-default-result-mapper", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + SampleEntity that = (SampleEntity) o; + + if (available != that.available) + return false; + if (rate != that.rate) + return false; + if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) + : that.highlightedMessage != null) + return false; + if (id != null ? !id.equals(that.id) : that.id != null) + return false; + if (location != null ? !location.equals(that.location) : that.location != null) + return false; + if (message != null ? !message.equals(that.message) : that.message != null) + return false; + if (type != null ? !type.equals(that.type) : that.type != null) + return false; + if (version != null ? !version.equals(that.version) : that.version != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + result = 31 * result + (message != null ? message.hashCode() : 0); + result = 31 * result + rate; + result = 31 * result + (available ? 1 : 0); + result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0); + result = 31 * result + (location != null ? location.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchEntityMapperUnitTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchEntityMapperUnitTests.java index e72e28570..7b04f9928 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchEntityMapperUnitTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchEntityMapperUnitTests.java @@ -17,10 +17,14 @@ package org.springframework.data.elasticsearch.core; import static org.assertj.core.api.Assertions.*; +import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; +import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; +import lombok.Setter; import java.io.IOException; import java.util.ArrayList; @@ -43,19 +47,22 @@ import org.springframework.data.annotation.Transient; import org.springframework.data.annotation.TypeAlias; import org.springframework.data.convert.ReadingConverter; import org.springframework.data.convert.WritingConverter; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.GeoPointField; import org.springframework.data.elasticsearch.core.convert.ElasticsearchCustomConversions; import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; -import org.springframework.data.elasticsearch.entities.Car; -import org.springframework.data.elasticsearch.entities.GeoEntity; +import org.springframework.data.geo.Box; +import org.springframework.data.geo.Circle; import org.springframework.data.geo.Point; +import org.springframework.data.geo.Polygon; /** * @author Christoph Strobl */ public class ElasticsearchEntityMapperUnitTests { - static final String JSON_STRING = "{\"_class\":\"org.springframework.data.elasticsearch.entities.Car\",\"name\":\"Grat\",\"model\":\"Ford\"}"; + static final String JSON_STRING = "{\"_class\":\"org.springframework.data.elasticsearch.core.ElasticsearchEntityMapperUnitTests$Car\",\"name\":\"Grat\",\"model\":\"Ford\"}"; static final String CAR_MODEL = "Ford"; static final String CAR_NAME = "Grat"; ElasticsearchEntityMapper entityMapper; @@ -674,4 +681,66 @@ public class ElasticsearchEntityMapperUnitTests { return new ShotGun(source.get("model").toString()); } } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + static class Car { + + private String name; + private String model; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + } + + /** + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-geo-core-entity-mapper", type = "geo-test-index", shards = 1, replicas = 0, + refreshInterval = "-1") + static class GeoEntity { + + @Id private String id; + + // geo shape - Spring Data + private Box box; + private Circle circle; + private Polygon polygon; + + // geo point - Custom implementation + Spring Data + @GeoPointField private Point pointA; + + private GeoPoint pointB; + + @GeoPointField private String pointC; + + @GeoPointField private double[] pointD; + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplateTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplateTests.java index 35dfe29a0..1e809966c 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplateTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchRestTemplateTests.java @@ -16,15 +16,33 @@ package org.springframework.data.elasticsearch.core; import static org.apache.commons.lang.RandomStringUtils.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.lang.Double; +import java.lang.Long; +import java.lang.Object; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.common.xcontent.XContentType; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.query.UpdateQuery; import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder; -import org.springframework.data.elasticsearch.entities.SampleEntity; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -40,6 +58,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Alen Turkovic * @author Sascha Woo * @author Don Wellington + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-rest-template-test.xml") @@ -47,6 +66,7 @@ public class ElasticsearchRestTemplateTests extends ElasticsearchTemplateTests { @Test(expected = ElasticsearchStatusException.class) public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() { + // when IndexRequest indexRequest = new IndexRequest(); indexRequest.source("{}", XContentType.JSON); @@ -54,4 +74,74 @@ public class ElasticsearchRestTemplateTests extends ElasticsearchTemplateTests { .withIndexRequest(indexRequest).build(); elasticsearchTemplate.update(updateQuery); } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-core-rest-template", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + SampleEntity that = (SampleEntity) o; + + if (available != that.available) + return false; + if (rate != that.rate) + return false; + if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) + : that.highlightedMessage != null) + return false; + if (id != null ? !id.equals(that.id) : that.id != null) + return false; + if (location != null ? !location.equals(that.location) : that.location != null) + return false; + if (message != null ? !message.equals(that.message) : that.message != null) + return false; + if (type != null ? !type.equals(that.type) : that.type != null) + return false; + if (version != null ? !version.equals(that.version) : that.version != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + result = 31 * result + (message != null ? message.hashCode() : 0); + result = 31 * result + rate; + result = 31 * result + (available ? 1 : 0); + result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0); + result = 31 * result + (location != null ? location.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateCustomMapperTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateCustomMapperTests.java index b312832e3..cb8eb5254 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateCustomMapperTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateCustomMapperTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.elasticsearch.core; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,26 +25,27 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Artur Konczak + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-custom-mapper.xml") public class ElasticsearchTemplateCustomMapperTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired private ElasticsearchTemplate elasticsearchTemplate; - @Autowired - private EntityMapper entityMapper; + @Autowired private EntityMapper entityMapper; - @Autowired - private ResultsMapper resultsMapper; + @Autowired private ResultsMapper resultsMapper; @Test public void shouldUseCustomMapper() { - //given - //when - //them - assertThat(elasticsearchTemplate.getResultsMapper(), is(resultsMapper)); - assertThat(elasticsearchTemplate.getResultsMapper().getEntityMapper(), is(entityMapper)); + + // given + + // when + + // then + assertThat(elasticsearchTemplate.getResultsMapper()).isSameAs(resultsMapper); + assertThat(elasticsearchTemplate.getResultsMapper().getEntityMapper()).isSameAs(entityMapper); } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateParentChildTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateParentChildTests.java index 79c8a540f..ee08f9631 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateParentChildTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateParentChildTests.java @@ -15,10 +15,9 @@ */ package org.springframework.data.elasticsearch.core; +import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.common.xcontent.XContentFactory.*; -import static org.elasticsearch.join.query.JoinQueryBuilders.hasChildQuery; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.elasticsearch.join.query.JoinQueryBuilders.*; import java.util.List; @@ -29,48 +28,46 @@ import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; -import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.style.ToStringCreator; +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.annotations.Parent; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplateParentChildTests.ParentEntity.ChildEntity; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.UpdateQuery; -import org.springframework.data.elasticsearch.entities.ParentEntity; -import org.springframework.data.elasticsearch.entities.ParentEntity.ChildEntity; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Philipp Jardas + * @author Peter-Josef Meisch */ -@Ignore(value = "DATAES-421") @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateParentChildTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { - clean(); - elasticsearchTemplate.createIndex(ParentEntity.class); - elasticsearchTemplate.createIndex(ChildEntity.class); - elasticsearchTemplate.putMapping(ChildEntity.class); - } - @After - public void clean() { - elasticsearchTemplate.deleteIndex(ChildEntity.class); - elasticsearchTemplate.deleteIndex(ParentEntity.class); + IndexInitializer.init(elasticsearchTemplate, ParentEntity.class); + IndexInitializer.init(elasticsearchTemplate, ChildEntity.class); } @Ignore(value = "DATAES-421") @Test public void shouldIndexParentChildEntity() { + // index two parents ParentEntity parent1 = index("parent1", "First Parent"); ParentEntity parent2 = index("parent2", "Second Parent"); @@ -84,16 +81,19 @@ public class ElasticsearchTemplateParentChildTests { elasticsearchTemplate.refresh(ChildEntity.class); // find all parents that have the first child - QueryBuilder query = hasChildQuery(ParentEntity.CHILD_TYPE, QueryBuilders.termQuery("name", child1name.toLowerCase()), ScoreMode.None); + QueryBuilder query = hasChildQuery(ParentEntity.CHILD_TYPE, + QueryBuilders.termQuery("name", child1name.toLowerCase()), ScoreMode.None); List parents = elasticsearchTemplate.queryForList(new NativeSearchQuery(query), ParentEntity.class); // we're expecting only the first parent as result - assertThat("parents", parents, contains(hasProperty("id", is(parent1.getId())))); + assertThat(parents).hasSize(1); + assertThat(parents.get(0).getId()).isEqualTo(parent1.getId()); } @Ignore(value = "DATAES-421") @Test public void shouldUpdateChild() throws Exception { + // index parent and child ParentEntity parent = index("parent", "Parent"); ChildEntity child = index("child", parent.getId(), "Child"); @@ -103,16 +103,17 @@ public class ElasticsearchTemplateParentChildTests { UpdateRequest updateRequest = new UpdateRequest(ParentEntity.INDEX, ParentEntity.CHILD_TYPE, child.getId()); updateRequest.routing(parent.getId()); XContentBuilder builder; - builder = jsonBuilder().startObject().field("name", newChildName).endObject(); + builder = jsonBuilder().startObject().field("name", newChildName).endObject(); updateRequest.doc(builder); final UpdateResponse response = update(updateRequest); - assertThat(response.getShardInfo().getSuccessful(), is(1)); + assertThat(response.getShardInfo().getSuccessful()).isEqualTo(1); } @Ignore(value = "DATAES-421") @Test(expected = RoutingMissingException.class) public void shouldFailWithRoutingMissingExceptionOnUpdateChildIfNotRoutingSetOnUpdateRequest() throws Exception { + // index parent and child ParentEntity parent = index("parent", "Parent"); ChildEntity child = index("child", parent.getId(), "Child"); @@ -129,6 +130,7 @@ public class ElasticsearchTemplateParentChildTests { @Ignore(value = "DATAES-421") @Test(expected = RoutingMissingException.class) public void shouldFailWithRoutingMissingExceptionOnUpdateChildIfRoutingOnlySetOnRequestDoc() throws Exception { + // index parent and child ParentEntity parent = index("parent", "Parent"); ChildEntity child = index("child", parent.getId(), "Child"); @@ -144,6 +146,7 @@ public class ElasticsearchTemplateParentChildTests { } private ParentEntity index(String parentId, String name) { + ParentEntity parent = new ParentEntity(parentId, name); IndexQuery index = new IndexQuery(); index.setId(parent.getId()); @@ -154,6 +157,7 @@ public class ElasticsearchTemplateParentChildTests { } private ChildEntity index(String childId, String parentId, String name) { + ChildEntity child = new ChildEntity(childId, parentId, name); IndexQuery index = new IndexQuery(); index.setId(child.getId()); @@ -165,6 +169,7 @@ public class ElasticsearchTemplateParentChildTests { } private UpdateResponse update(UpdateRequest updateRequest) { + final UpdateQuery update = new UpdateQuery(); update.setId(updateRequest.id()); update.setType(updateRequest.type()); @@ -172,4 +177,76 @@ public class ElasticsearchTemplateParentChildTests { update.setUpdateRequest(updateRequest); return elasticsearchTemplate.update(update); } + + /** + * @author Philipp Jardas + * @author Mohsin Husen + */ + @Document( + indexName = org.springframework.data.elasticsearch.core.ElasticsearchTemplateParentChildTests.ParentEntity.INDEX, + type = org.springframework.data.elasticsearch.core.ElasticsearchTemplateParentChildTests.ParentEntity.PARENT_TYPE, + shards = 1, replicas = 0, refreshInterval = "-1") + static class ParentEntity { + + public static final String INDEX = "parent-child"; + public static final String PARENT_TYPE = "parent-entity"; + public static final String CHILD_TYPE = "child-entity"; + + @Id private String id; + @Field(type = FieldType.Text, store = true) private String name; + + public ParentEntity() {} + + public ParentEntity(String id, String name) { + this.id = id; + this.name = name; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return new ToStringCreator(this).append("id", id).append("name", name).toString(); + } + + @Document(indexName = INDEX, type = CHILD_TYPE, shards = 1, replicas = 0, refreshInterval = "-1") + static class ChildEntity { + + @Id private String id; + @Field(type = FieldType.Text, store = true) @Parent(type = PARENT_TYPE) private String parentId; + @Field(type = FieldType.Text, store = true) private String name; + + public ChildEntity() {} + + public ChildEntity(String id, String parentId, String name) { + this.id = id; + this.parentId = parentId; + this.name = name; + } + + public String getId() { + return id; + } + + public String getParentId() { + return parentId; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return new ToStringCreator(this).append("id", id).append("parentId", parentId).append("name", name).toString(); + } + } + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java index f950845ec..f8b89989a 100755 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java @@ -16,13 +16,25 @@ package org.springframework.data.elasticsearch.core; import static org.apache.commons.lang.RandomStringUtils.*; +import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; import static org.springframework.data.elasticsearch.utils.IndexBuilder.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.lang.Double; +import java.lang.Integer; +import java.lang.Long; +import java.lang.Object; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; @@ -32,12 +44,15 @@ import java.util.UUID; import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; import org.assertj.core.util.Lists; import org.elasticsearch.action.get.MultiGetItemResponse; import org.elasticsearch.action.get.MultiGetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.IndicesOptions; +import org.elasticsearch.index.VersionType; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptType; import org.elasticsearch.search.SearchHit; @@ -46,12 +61,13 @@ import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; -import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; @@ -59,18 +75,19 @@ import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Order; import org.springframework.data.elasticsearch.ElasticsearchException; 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.InnerField; +import org.springframework.data.elasticsearch.annotations.MultiField; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage; import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.query.*; -import org.springframework.data.elasticsearch.entities.Book; -import org.springframework.data.elasticsearch.entities.GTEVersionEntity; -import org.springframework.data.elasticsearch.entities.HetroEntity1; -import org.springframework.data.elasticsearch.entities.HetroEntity2; -import org.springframework.data.elasticsearch.entities.SampleEntity; -import org.springframework.data.elasticsearch.entities.SampleEntityUUIDKeyed; -import org.springframework.data.elasticsearch.entities.SampleMappingEntity; -import org.springframework.data.elasticsearch.entities.UseServerConfigurationEntity; import org.springframework.data.util.CloseableIterator; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Base for testing rest/transport templates @@ -92,10 +109,11 @@ import org.springframework.data.util.CloseableIterator; * @author Dmitriy Yakovlev * @author Peter-Josef Meisch */ -@Ignore +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateTests { - private static final String INDEX_NAME_SAMPLE_ENTITY = "test-index-sample"; + private static final String INDEX_NAME_SAMPLE_ENTITY = "test-index-sample-core-template"; private static final String INDEX_1_NAME = "test-index-1"; private static final String INDEX_2_NAME = "test-index-2"; private static final String INDEX_3_NAME = "test-index-3"; @@ -104,11 +122,14 @@ public class ElasticsearchTemplateTests { private final SearchResultMapper searchResultMapper = new SearchResultMapperAdapter() { @Override public AggregatedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { + List result = new ArrayList<>(); for (SearchHit searchHit : response.getHits()) { + if (response.getHits().getHits().length <= 0) { return new AggregatedPageImpl(Collections.emptyList(), response.getScrollId()); } + String message = (String) searchHit.getSourceAsMap().get("message"); SampleEntity sampleEntity = new SampleEntity(); sampleEntity.setId(searchHit.getId()); @@ -119,6 +140,7 @@ public class ElasticsearchTemplateTests { if (result.size() > 0) { return new AggregatedPageImpl((List) result, response.getScrollId()); } + return new AggregatedPageImpl(Collections.emptyList(), response.getScrollId()); } }; @@ -139,10 +161,12 @@ public class ElasticsearchTemplateTests { @After public void after() { + deleteIndices(); } private void deleteIndices() { + elasticsearchTemplate.deleteIndex(SampleEntity.class); elasticsearchTemplate.deleteIndex(SampleEntityUUIDKeyed.class); elasticsearchTemplate.deleteIndex(UseServerConfigurationEntity.class); @@ -153,11 +177,9 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.deleteIndex(INDEX_3_NAME); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldReturnCountForGivenCriteriaQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -167,14 +189,18 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); + // when + long count = elasticsearchTemplate.count(criteriaQuery, SampleEntity.class); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1); } @Test public void shouldReturnCountForGivenSearchQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -184,33 +210,38 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(SampleEntity.class); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); + // when + long count = elasticsearchTemplate.count(searchQuery, SampleEntity.class); // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1); } @Test public void shouldReturnObjectForGivenId() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") .version(System.currentTimeMillis()).build(); IndexQuery indexQuery = getIndexQuery(sampleEntity); elasticsearchTemplate.index(indexQuery); + // when GetQuery getQuery = new GetQuery(); getQuery.setId(documentId); SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); + // then - assertNotNull("entity can't be null....", sampleEntity1); - assertEquals(sampleEntity, sampleEntity1); + assertThat(sampleEntity1).isNotNull(); + assertThat(sampleEntity1).isEqualTo(sampleEntity); } @Test public void shouldReturnObjectsForGivenIdsUsingMultiGet() { + // given - List indexQueries = new ArrayList<>(); // first document String documentId = randomNumeric(5); SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId).message("some message") @@ -221,7 +252,7 @@ public class ElasticsearchTemplateTests { SampleEntity sampleEntity2 = SampleEntity.builder().id(documentId2).message("some message") .version(System.currentTimeMillis()).build(); - indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2)); + List indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2)); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); @@ -229,16 +260,17 @@ public class ElasticsearchTemplateTests { // when SearchQuery query = new NativeSearchQueryBuilder().withIds(Arrays.asList(documentId, documentId2)).build(); LinkedList sampleEntities = elasticsearchTemplate.multiGet(query, SampleEntity.class); + // then - assertThat(sampleEntities.size(), is(equalTo(2))); - assertEquals(sampleEntities.get(0), sampleEntity1); - assertEquals(sampleEntities.get(1), sampleEntity2); + assertThat(sampleEntities).hasSize(2); + assertThat(sampleEntities.get(0)).isEqualTo(sampleEntity1); + assertThat(sampleEntities.get(1)).isEqualTo(sampleEntity2); } @Test public void shouldReturnObjectsForGivenIdsUsingMultiGetWithFields() { + // given - List indexQueries = new ArrayList<>(); // first document String documentId = randomNumeric(5); SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId).message("some message").type("type1") @@ -249,7 +281,7 @@ public class ElasticsearchTemplateTests { SampleEntity sampleEntity2 = SampleEntity.builder().id(documentId2).message("some message").type("type2") .version(System.currentTimeMillis()).build(); - indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2)); + List indexQueries = getIndexQueries(Arrays.asList(sampleEntity1, sampleEntity2)); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); @@ -272,12 +304,14 @@ public class ElasticsearchTemplateTests { return list; } }); + // then - assertThat(sampleEntities.size(), is(equalTo(2))); + assertThat(sampleEntities).hasSize(2); } @Test public void shouldReturnPageForGivenSearchQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -289,16 +323,18 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.refresh(SampleEntity.class); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); + // when Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then - assertThat(sampleEntities, is(notNullValue())); - assertThat(sampleEntities.getTotalElements(), greaterThanOrEqualTo(1L)); + assertThat(sampleEntities).isNotNull(); + assertThat(sampleEntities.getTotalElements()).isGreaterThanOrEqualTo(1); } - // DATAES-422 - Add support for IndicesOptions in search queries - @Test + @Test // DATAES-422 - Add support for IndicesOptions in search queries public void shouldPassIndicesOptionsForGivenSearchQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -314,15 +350,18 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withIndices(INDEX_1_NAME, INDEX_2_NAME).withIndicesOptions(IndicesOptions.lenientExpandOpen()).build(); Page entities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then - assertThat(entities, is(notNullValue())); - assertThat(entities.getTotalElements(), greaterThanOrEqualTo(1L)); + assertThat(entities).isNotNull(); + assertThat(entities.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldDoBulkIndex() { + // given List indexQueries = new ArrayList<>(); + // first document String documentId = randomNumeric(5); SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId).message("some message") @@ -338,14 +377,16 @@ public class ElasticsearchTemplateTests { // when elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), is(equalTo(2L))); + assertThat(sampleEntities.getTotalElements()).isEqualTo(2); } @Test public void shouldDoBulkUpdate() { + // given String documentId = randomNumeric(5); String messageBeforeUpdate = "some test message"; @@ -369,15 +410,17 @@ public class ElasticsearchTemplateTests { // when elasticsearchTemplate.bulkUpdate(queries); + // then GetQuery getQuery = new GetQuery(); getQuery.setId(documentId); SampleEntity indexedEntity = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); - assertThat(indexedEntity.getMessage(), is(messageAfterUpdate)); + assertThat(indexedEntity.getMessage()).isEqualTo(messageAfterUpdate); } @Test public void shouldDeleteDocumentForGivenId() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -386,17 +429,20 @@ public class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); elasticsearchTemplate.index(indexQuery); + // when elasticsearchTemplate.delete(INDEX_NAME_SAMPLE_ENTITY, TYPE_NAME, documentId); elasticsearchTemplate.refresh(SampleEntity.class); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(0); } @Test public void shouldDeleteEntityForGivenId() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -405,17 +451,20 @@ public class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); elasticsearchTemplate.index(indexQuery); + // when elasticsearchTemplate.delete(SampleEntity.class, documentId); elasticsearchTemplate.refresh(SampleEntity.class); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(0); } @Test public void shouldDeleteDocumentForGivenQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -431,10 +480,11 @@ public class ElasticsearchTemplateTests { deleteQuery.setQuery(termQuery("id", documentId)); elasticsearchTemplate.delete(deleteQuery, SampleEntity.class); elasticsearchTemplate.refresh(SampleEntity.class); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(0); } @Test // DATAES-547 @@ -474,7 +524,7 @@ public class ElasticsearchTemplateTests { .withIndices(INDEX_1_NAME, INDEX_2_NAME) // .build(); - assertThat(elasticsearchTemplate.count(searchQuery), equalTo(0L)); + assertThat(elasticsearchTemplate.count(searchQuery)).isEqualTo(0); } @Test // DATAES-547 @@ -514,11 +564,12 @@ public class ElasticsearchTemplateTests { .withIndices(INDEX_1_NAME, INDEX_2_NAME) // .build(); - assertThat(elasticsearchTemplate.count(searchQuery), equalTo(2L)); + assertThat(elasticsearchTemplate.count(searchQuery)).isEqualTo(2); } @Test public void shouldFilterSearchResultsForGivenFilter() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -530,14 +581,17 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFilter(boolQuery().filter(termQuery("id", documentId))).build(); + // when Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(1); } @Test public void shouldSortResultsGivenSortCriteria() { + // given List indexQueries = new ArrayList<>(); // first document @@ -562,15 +616,18 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withSort(new FieldSortBuilder("rate").order(SortOrder.ASC)).build(); + // when Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then - assertThat(sampleEntities.getTotalElements(), equalTo(3L)); - assertThat(sampleEntities.getContent().get(0).getRate(), is(sampleEntity2.getRate())); + assertThat(sampleEntities.getTotalElements()).isEqualTo(3); + assertThat(sampleEntities.getContent().get(0).getRate()).isEqualTo(sampleEntity2.getRate()); } @Test public void shouldSortResultsGivenMultipleSortCriteria() { + // given List indexQueries = new ArrayList<>(); // first document @@ -596,16 +653,19 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withSort(new FieldSortBuilder("rate").order(SortOrder.ASC)) .withSort(new FieldSortBuilder("message").order(SortOrder.ASC)).build(); + // when Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then - assertThat(sampleEntities.getTotalElements(), equalTo(3L)); - assertThat(sampleEntities.getContent().get(0).getRate(), is(sampleEntity2.getRate())); - assertThat(sampleEntities.getContent().get(1).getMessage(), is(sampleEntity1.getMessage())); + assertThat(sampleEntities.getTotalElements()).isEqualTo(3); + assertThat(sampleEntities.getContent().get(0).getRate()).isEqualTo(sampleEntity2.getRate()); + assertThat(sampleEntities.getContent().get(1).getMessage()).isEqualTo(sampleEntity1.getMessage()); } @Test // DATAES-312 public void shouldSortResultsGivenNullFirstSortCriteria() { + // given List indexQueries; @@ -636,13 +696,14 @@ public class ElasticsearchTemplateTests { Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); // then - assertThat(sampleEntities.getTotalElements(), equalTo(3L)); - assertThat(sampleEntities.getContent().get(0).getRate(), is(sampleEntity3.getRate())); - assertThat(sampleEntities.getContent().get(1).getMessage(), is(sampleEntity1.getMessage())); + assertThat(sampleEntities.getTotalElements()).isEqualTo(3); + assertThat(sampleEntities.getContent().get(0).getRate()).isEqualTo(sampleEntity3.getRate()); + assertThat(sampleEntities.getContent().get(1).getMessage()).isEqualTo(sampleEntity1.getMessage()); } @Test // DATAES-312 public void shouldSortResultsGivenNullLastSortCriteria() { + // given List indexQueries; @@ -673,13 +734,14 @@ public class ElasticsearchTemplateTests { Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); // then - assertThat(sampleEntities.getTotalElements(), equalTo(3L)); - assertThat(sampleEntities.getContent().get(0).getRate(), is(sampleEntity1.getRate())); - assertThat(sampleEntities.getContent().get(1).getMessage(), is(sampleEntity2.getMessage())); + assertThat(sampleEntities.getTotalElements()).isEqualTo(3); + assertThat(sampleEntities.getContent().get(0).getRate()).isEqualTo(sampleEntity1.getRate()); + assertThat(sampleEntities.getContent().get(1).getMessage()).isEqualTo(sampleEntity2.getMessage()); } @Test // DATAES-467 public void shouldSortResultsByScore() { + // given List entities = Arrays.asList( // SampleEntity.builder().id("1").message("abc").build(), // @@ -696,11 +758,12 @@ public class ElasticsearchTemplateTests { Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); // then - assertThat(sampleEntities.getTotalElements(), equalTo(3L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(3); } @Test public void shouldExecuteStringQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -712,14 +775,17 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.refresh(SampleEntity.class); StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); + // when Page sampleEntities = elasticsearchTemplate.queryForPage(stringQuery, SampleEntity.class); + // then - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(1); } @Test public void shouldUseScriptedFields() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -737,18 +803,21 @@ public class ElasticsearchTemplateTests { Map params = new HashMap<>(); params.put("factor", 2); + // when SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withScriptField( new ScriptField("scriptedRate", new Script(ScriptType.INLINE, "expression", "doc['rate'] * factor", params))) .build(); Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); - assertThat(sampleEntities.getContent().get(0).getScriptedRate(), equalTo(4.0)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(1); + assertThat(sampleEntities.getContent().get(0).getScriptedRate()).isEqualTo(4.0); } @Test public void shouldReturnPageableResultsGivenStringQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -760,15 +829,17 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.refresh(SampleEntity.class); StringQuery stringQuery = new StringQuery(matchAllQuery().toString(), PageRequest.of(0, 10)); + // when Page sampleEntities = elasticsearchTemplate.queryForPage(stringQuery, SampleEntity.class); // then - assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(sampleEntities.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldReturnSortedPageableResultsGivenStringQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -785,14 +856,17 @@ public class ElasticsearchTemplateTests { StringQuery stringQuery = new StringQuery(matchAllQuery().toString(), PageRequest.of(0, 10), Sort.by(Order.asc("message"))); + // when Page sampleEntities = elasticsearchTemplate.queryForPage(stringQuery, SampleEntity.class); + // then - assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(sampleEntities.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldReturnObjectMatchingGivenStringQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -804,27 +878,32 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.refresh(SampleEntity.class); StringQuery stringQuery = new StringQuery(termQuery("id", documentId).toString()); + // when SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(stringQuery, SampleEntity.class); + // then - assertThat(sampleEntity1, is(notNullValue())); - assertThat(sampleEntity1.getId(), is(equalTo(documentId))); + assertThat(sampleEntity1).isNotNull(); + assertThat(sampleEntity1.getId()).isEqualTo(documentId); } @Test public void shouldCreateIndexGivenEntityClass() { + // when boolean created = elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.putMapping(SampleEntity.class); final Map setting = elasticsearchTemplate.getSetting(SampleEntity.class); + // then - assertThat(created, is(true)); - assertThat(setting.get("index.number_of_shards"), Matchers. is("1")); - assertThat(setting.get("index.number_of_replicas"), Matchers. is("0")); + assertThat(created).isTrue(); + assertThat(setting.get("index.number_of_shards")).isEqualTo("1"); + assertThat(setting.get("index.number_of_replicas")).isEqualTo("0"); } @Test public void shouldExecuteGivenCriteriaQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("test message") @@ -838,12 +917,14 @@ public class ElasticsearchTemplateTests { // when SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); + // then - assertThat(sampleEntity1, is(notNullValue())); + assertThat(sampleEntity1).isNotNull(); } @Test public void shouldDeleteGivenCriteriaQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("test message") @@ -858,15 +939,17 @@ public class ElasticsearchTemplateTests { // when elasticsearchTemplate.delete(criteriaQuery, SampleEntity.class); elasticsearchTemplate.refresh(SampleEntity.class); + // then StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); List sampleEntities = elasticsearchTemplate.queryForList(stringQuery, SampleEntity.class); - assertThat(sampleEntities.size(), is(0)); + assertThat(sampleEntities).isEmpty(); } @Test public void shouldReturnSpecifiedFields() { + // given String documentId = randomNumeric(5); String message = "some test message"; @@ -890,14 +973,16 @@ public class ElasticsearchTemplateTests { return new AggregatedPageImpl<>((List) values); } }); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - assertThat(page.getContent().get(0), is(message)); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1); + assertThat(page.getContent().get(0)).isEqualTo(message); } @Test public void shouldReturnFieldsBasedOnSourceFilter() { + // given String documentId = randomNumeric(5); String message = "some test message"; @@ -914,16 +999,19 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).withSourceFilter(sourceFilter.build()).build(); + // when Page page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - assertThat(page.getContent().get(0).getMessage(), is(message)); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1); + assertThat(page.getContent().get(0).getMessage()).isEqualTo(message); } @Test public void shouldReturnSimilarResultsGivenMoreLikeThisQuery() { + // given String sampleMessage = "So we build a web site or an application and want to add search to it, " + "and then it hits us: getting search working is hard. We want our search solution to be fast," @@ -949,26 +1037,26 @@ public class ElasticsearchTemplateTests { moreLikeThisQuery.setId(documentId2); moreLikeThisQuery.addFields("message"); moreLikeThisQuery.setMinDocFreq(1); + // when Page sampleEntities = elasticsearchTemplate.moreLikeThis(moreLikeThisQuery, SampleEntity.class); // then - assertThat(sampleEntities.getTotalElements(), is(equalTo(1L))); - assertThat(sampleEntities.getContent(), hasItem(sampleEntity)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(1); + assertThat(sampleEntities.getContent()).contains(sampleEntity); } - /* - DATAES-167 - */ - @Test + @Test // DATAES-167 public void shouldReturnResultsWithScanAndScrollForGivenCriteriaQuery() { + // given List entities = createSampleEntitiesWithMessage("Test message", 30); + // when elasticsearchTemplate.bulkIndex(entities); elasticsearchTemplate.refresh(SampleEntity.class); - // then + // then CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.addIndices(INDEX_NAME_SAMPLE_ENTITY); criteriaQuery.addTypes(TYPE_NAME); @@ -981,16 +1069,19 @@ public class ElasticsearchTemplateTests { scroll = elasticsearchTemplate.continueScroll(scroll.getScrollId(), 1000, SampleEntity.class); } elasticsearchTemplate.clearScroll(scroll.getScrollId()); - assertThat(sampleEntities.size(), is(equalTo(30))); + assertThat(sampleEntities).hasSize(30); } @Test public void shouldReturnResultsWithScanAndScrollForGivenSearchQuery() { + // given List entities = createSampleEntitiesWithMessage("Test message", 30); + // when elasticsearchTemplate.bulkIndex(entities); elasticsearchTemplate.refresh(SampleEntity.class); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) @@ -1003,21 +1094,20 @@ public class ElasticsearchTemplateTests { scroll = elasticsearchTemplate.continueScroll(scroll.getScrollId(), 1000, SampleEntity.class); } elasticsearchTemplate.clearScroll(scroll.getScrollId()); - assertThat(sampleEntities.size(), is(equalTo(30))); + assertThat(sampleEntities).hasSize(30); } - /* - DATAES-167 - */ - @Test + @Test // DATAES-167 public void shouldReturnResultsWithScanAndScrollForSpecifiedFieldsForCriteriaQuery() { + // given List entities = createSampleEntitiesWithMessage("Test message", 30); + // when elasticsearchTemplate.bulkIndex(entities); elasticsearchTemplate.refresh(SampleEntity.class); - // then + // then CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.addIndices(INDEX_NAME_SAMPLE_ENTITY); criteriaQuery.addTypes(TYPE_NAME); @@ -1034,21 +1124,20 @@ public class ElasticsearchTemplateTests { scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class, searchResultMapper); } elasticsearchTemplate.clearScroll(scrollId); - assertThat(sampleEntities.size(), is(equalTo(30))); + assertThat(sampleEntities).hasSize(30); } - /* - DATAES-84 - */ - @Test + @Test // DATAES-84 public void shouldReturnResultsWithScanAndScrollForSpecifiedFieldsForSearchCriteria() { + // given List entities = createSampleEntitiesWithMessage("Test message", 30); + // when elasticsearchTemplate.bulkIndex(entities); elasticsearchTemplate.refresh(SampleEntity.class); - // then + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).withFields("message").withQuery(matchAllQuery()) .withPageable(PageRequest.of(0, 10)).build(); @@ -1063,21 +1152,20 @@ public class ElasticsearchTemplateTests { scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class, searchResultMapper); } elasticsearchTemplate.clearScroll(scrollId); - assertThat(sampleEntities.size(), is(equalTo(30))); + assertThat(sampleEntities).hasSize(30); } - /* - DATAES-167 - */ - @Test + @Test // DATAES-167 public void shouldReturnResultsForScanAndScrollWithCustomResultMapperForGivenCriteriaQuery() { + // given List entities = createSampleEntitiesWithMessage("Test message", 30); + // when elasticsearchTemplate.bulkIndex(entities); elasticsearchTemplate.refresh(SampleEntity.class); - // then + // then CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.addIndices(INDEX_NAME_SAMPLE_ENTITY); criteriaQuery.addTypes(TYPE_NAME); @@ -1093,18 +1181,20 @@ public class ElasticsearchTemplateTests { scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class, searchResultMapper); } elasticsearchTemplate.clearScroll(scrollId); - assertThat(sampleEntities.size(), is(equalTo(30))); + assertThat(sampleEntities).hasSize(30); } @Test public void shouldReturnResultsForScanAndScrollWithCustomResultMapperForGivenSearchQuery() { + // given List entities = createSampleEntitiesWithMessage("Test message", 30); + // when elasticsearchTemplate.bulkIndex(entities); elasticsearchTemplate.refresh(SampleEntity.class); - // then + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).withPageable(PageRequest.of(0, 10)).build(); @@ -1118,21 +1208,20 @@ public class ElasticsearchTemplateTests { scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class, searchResultMapper); } elasticsearchTemplate.clearScroll(scrollId); - assertThat(sampleEntities.size(), is(equalTo(30))); + assertThat(sampleEntities).hasSize(30); } - /* - DATAES-217 - */ - @Test + @Test // DATAES-217 public void shouldReturnResultsWithScanAndScrollForGivenCriteriaQueryAndClass() { + // given List entities = createSampleEntitiesWithMessage("Test message", 30); + // when elasticsearchTemplate.bulkIndex(entities); elasticsearchTemplate.refresh(SampleEntity.class); - // then + // then CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.setPageable(PageRequest.of(0, 10)); @@ -1145,21 +1234,20 @@ public class ElasticsearchTemplateTests { scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class); } elasticsearchTemplate.clearScroll(scrollId); - assertThat(sampleEntities.size(), is(equalTo(30))); + assertThat(sampleEntities).hasSize(30); } - /* - DATAES-217 - */ - @Test + @Test // DATAES-217 public void shouldReturnResultsWithScanAndScrollForGivenSearchQueryAndClass() { + // given List entities = createSampleEntitiesWithMessage("Test message", 30); + // when elasticsearchTemplate.bulkIndex(entities); elasticsearchTemplate.refresh(SampleEntity.class); - // then + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPageable(PageRequest.of(0, 10)).build(); @@ -1172,21 +1260,20 @@ public class ElasticsearchTemplateTests { scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class); } elasticsearchTemplate.clearScroll(scrollId); - assertThat(sampleEntities.size(), is(equalTo(30))); + assertThat(sampleEntities).hasSize(30); } - /* - DATAES-167 - */ - @Test + @Test // DATAES-167 public void shouldReturnResultsWithStreamForGivenCriteriaQuery() { + // given List entities = createSampleEntitiesWithMessage("Test message", 30); + // when elasticsearchTemplate.bulkIndex(entities); elasticsearchTemplate.refresh(SampleEntity.class); - // then + // then CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.addIndices(INDEX_NAME_SAMPLE_ENTITY); criteriaQuery.addTypes(TYPE_NAME); @@ -1197,7 +1284,7 @@ public class ElasticsearchTemplateTests { while (stream.hasNext()) { sampleEntities.add(stream.next()); } - assertThat(sampleEntities.size(), is(equalTo(30))); + assertThat(sampleEntities).hasSize(30); } private static List createSampleEntitiesWithMessage(String message, int numberOfEntities) { @@ -1219,6 +1306,7 @@ public class ElasticsearchTemplateTests { @Test public void shouldReturnListForGivenCriteria() { + // given List indexQueries = new ArrayList<>(); // first document @@ -1241,7 +1329,7 @@ public class ElasticsearchTemplateTests { // when elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); - // when + CriteriaQuery singleCriteriaQuery = new CriteriaQuery(new Criteria("message").contains("test")); CriteriaQuery multipleCriteriaQuery = new CriteriaQuery( new Criteria("message").contains("some").and("message").contains("message")); @@ -1250,12 +1338,13 @@ public class ElasticsearchTemplateTests { List sampleEntitiesForAndCriteria = elasticsearchTemplate.queryForList(multipleCriteriaQuery, SampleEntity.class); // then - assertThat(sampleEntitiesForSingleCriteria.size(), is(2)); - assertThat(sampleEntitiesForAndCriteria.size(), is(1)); + assertThat(sampleEntitiesForSingleCriteria).hasSize(2); + assertThat(sampleEntitiesForAndCriteria).hasSize(1); } @Test public void shouldReturnListForGivenStringQuery() { + // given // first document String documentId = randomNumeric(5); @@ -1277,35 +1366,44 @@ public class ElasticsearchTemplateTests { // when elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); - // when + StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); List sampleEntities = elasticsearchTemplate.queryForList(stringQuery, SampleEntity.class); + // then - assertThat(sampleEntities.size(), is(3)); + assertThat(sampleEntities).hasSize(3); } @Test public void shouldPutMappingForGivenEntity() throws Exception { + // given Class entity = SampleMappingEntity.class; elasticsearchTemplate.deleteIndex(entity); elasticsearchTemplate.createIndex(entity); + // when - assertThat(elasticsearchTemplate.putMapping(entity), is(true)); + + // then + assertThat(elasticsearchTemplate.putMapping(entity)).isTrue(); } @Test public void shouldDeleteIndexForGivenEntity() { + // given - Class clazz = SampleEntity.class; + Class clazz = SampleEntity.class; + // when elasticsearchTemplate.deleteIndex(clazz); + // then - assertThat(elasticsearchTemplate.indexExists(clazz), is(false)); + assertThat(elasticsearchTemplate.indexExists(clazz)).isFalse(); } @Test public void shouldDoPartialUpdateForExistingDocument() { + // given String documentId = randomNumeric(5); String messageBeforeUpdate = "some test message"; @@ -1323,17 +1421,20 @@ public class ElasticsearchTemplateTests { indexRequest.source("message", messageAfterUpdate); UpdateQuery updateQuery = new UpdateQueryBuilder().withId(documentId).withClass(SampleEntity.class) .withIndexRequest(indexRequest).build(); + // when elasticsearchTemplate.update(updateQuery); + // then GetQuery getQuery = new GetQuery(); getQuery.setId(documentId); SampleEntity indexedEntity = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); - assertThat(indexedEntity.getMessage(), is(messageAfterUpdate)); + assertThat(indexedEntity.getMessage()).isEqualTo(messageAfterUpdate); } @Test public void shouldDoUpsertIfDocumentDoesNotExist() { + // given String documentId = randomNumeric(5); String message = "test message"; @@ -1341,13 +1442,15 @@ public class ElasticsearchTemplateTests { indexRequest.source("message", message); UpdateQuery updateQuery = new UpdateQueryBuilder().withId(documentId).withDoUpsert(true) .withClass(SampleEntity.class).withIndexRequest(indexRequest).build(); + // when elasticsearchTemplate.update(updateQuery); + // then GetQuery getQuery = new GetQuery(); getQuery.setId(documentId); SampleEntity indexedEntity = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); - assertThat(indexedEntity.getMessage(), is(message)); + assertThat(indexedEntity.getMessage()).isEqualTo(message); } @Test @@ -1363,6 +1466,7 @@ public class ElasticsearchTemplateTests { IndexQuery indexQuery = getIndexQuery(sampleEntity); + // when elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(SampleEntity.class); @@ -1392,7 +1496,8 @@ public class ElasticsearchTemplateTests { } }); - assertThat(sampleEntities.getContent().get(0).getHighlightedMessage(), is(highlightedMessage)); + // then + assertThat(sampleEntities.getContent().get(0).getHighlightedMessage()).isEqualTo(highlightedMessage); } @Test // DATAES-412 @@ -1427,10 +1532,10 @@ public class ElasticsearchTemplateTests { HighlightField highlightFieldMessage = highlightFields.get("message"); // then - assertNotNull(highlightFieldType); - assertNotNull(highlightFieldMessage); - assertThat(highlightFieldType.fragments()[0].toString(), is(highlightedType)); - assertThat(highlightFieldMessage.fragments()[0].toString(), is(highlightedMessage)); + assertThat(highlightFieldType).isNotNull(); + assertThat(highlightFieldMessage).isNotNull(); + assertThat(highlightFieldType.fragments()[0].toString()).isEqualTo(highlightedType); + assertThat(highlightFieldMessage.fragments()[0].toString()).isEqualTo(highlightedMessage); } return null; } @@ -1456,6 +1561,7 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test")) .withHighlightBuilder(new HighlightBuilder().encoder("html")) .withHighlightFields(new HighlightBuilder.Field("message")).build(); + // when elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapperAdapter() { @Override @@ -1465,8 +1571,8 @@ public class ElasticsearchTemplateTests { HighlightField highlightFieldMessage = highlightFields.get("message"); // then - assertNotNull(highlightFieldMessage); - assertThat(highlightFieldMessage.fragments()[0].toString(), is(highlightedMessage)); + assertThat(highlightFieldMessage).isNotNull(); + assertThat(highlightFieldMessage.fragments()[0].toString()).isEqualTo(highlightedMessage); } return null; } @@ -1491,6 +1597,7 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test")) .withHighlightBuilder(new HighlightBuilder().field("message")).build(); + // when elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() { @Override @@ -1500,8 +1607,8 @@ public class ElasticsearchTemplateTests { HighlightField highlightFieldMessage = highlightFields.get("message"); // then - assertNotNull(highlightFieldMessage); - assertThat(highlightFieldMessage.fragments()[0].toString(), is(highlightedMessage)); + assertThat(highlightFieldMessage).isNotNull(); + assertThat(highlightFieldMessage.fragments()[0].toString()).isEqualTo(highlightedMessage); } return null; } @@ -1515,6 +1622,7 @@ public class ElasticsearchTemplateTests { @Test // DATAES-487 public void shouldReturnSameEntityForMultiSearch() { + // given List indexQueries = new ArrayList<>(); @@ -1524,21 +1632,24 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); + // when List queries = new ArrayList<>(); queries.add(new NativeSearchQueryBuilder().withQuery(termQuery("message", "ab")).build()); queries.add(new NativeSearchQueryBuilder().withQuery(termQuery("message", "bc")).build()); queries.add(new NativeSearchQueryBuilder().withQuery(termQuery("message", "ac")).build()); + // then List> sampleEntities = elasticsearchTemplate.queryForPage(queries, SampleEntity.class); for (Page sampleEntity : sampleEntities) { - assertThat(sampleEntity.getTotalElements(), equalTo(1L)); + assertThat(sampleEntity.getTotalElements()).isEqualTo(1); } } @Test // DATAES-487 public void shouldReturnDifferentEntityForMultiSearch() { + // given Class clazz = Book.class; elasticsearchTemplate.deleteIndex(clazz); @@ -1554,21 +1665,26 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); elasticsearchTemplate.refresh(clazz); + // when List queries = new ArrayList<>(); queries.add(new NativeSearchQueryBuilder().withQuery(termQuery("message", "ab")).build()); queries.add(new NativeSearchQueryBuilder().withQuery(termQuery("description", "bc")).build()); + // then List> pages = elasticsearchTemplate.queryForPage(queries, Lists.newArrayList(SampleEntity.class, clazz)); - assertThat(pages.get(0).getTotalElements(), equalTo(1L)); - assertThat(pages.get(0).getContent().get(0).getClass(), equalTo(SampleEntity.class)); - assertThat(pages.get(1).getTotalElements(), equalTo(1L)); - assertThat(pages.get(1).getContent().get(0).getClass(), equalTo(clazz)); + Page page0 = pages.get(0); + assertThat(page0.getTotalElements()).isEqualTo(1L); + assertThat(page0.getContent().get(0).getClass()).isEqualTo(SampleEntity.class); + Page page1 = pages.get(1); + assertThat(page1.getTotalElements()).isEqualTo(1L); + assertThat(page1.getContent().get(0).getClass()).isEqualTo(clazz); } @Test public void shouldDeleteDocumentBySpecifiedTypeUsingDeleteQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -1578,6 +1694,7 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(SampleEntity.class); + // when DeleteQuery deleteQuery = new DeleteQuery(); deleteQuery.setQuery(termQuery("id", documentId)); @@ -1585,10 +1702,11 @@ public class ElasticsearchTemplateTests { deleteQuery.setType(TYPE_NAME); elasticsearchTemplate.delete(deleteQuery); elasticsearchTemplate.refresh(INDEX_NAME_SAMPLE_ENTITY); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(0); } @Test @@ -1601,11 +1719,13 @@ public class ElasticsearchTemplateTests { indexQuery.setSource(documentSource); indexQuery.setIndexName(INDEX_NAME_SAMPLE_ENTITY); indexQuery.setType(TYPE_NAME); + // when elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(SampleEntity.class); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", indexQuery.getId())) .withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).build(); + // then Page page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapperAdapter() { @@ -1621,13 +1741,14 @@ public class ElasticsearchTemplateTests { return new AggregatedPageImpl<>((List) values); } }); - assertThat(page, is(notNullValue())); - assertThat(page.getContent().size(), is(1)); - assertThat(page.getContent().get(0).getId(), is(indexQuery.getId())); + assertThat(page).isNotNull(); + assertThat(page.getContent()).hasSize(1); + assertThat(page.getContent().get(0).getId()).isEqualTo(indexQuery.getId()); } @Test(expected = ElasticsearchException.class) public void shouldThrowElasticsearchExceptionWhenNoDocumentSpecified() { + // given IndexQuery indexQuery = new IndexQuery(); indexQuery.setId("2333343434"); @@ -1649,8 +1770,7 @@ public class ElasticsearchTemplateTests { .withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).withPageable(PageRequest.of(0, 100)).build(); // then List ids = elasticsearchTemplate.queryForIds(searchQuery); - assertThat(ids, is(notNullValue())); - assertThat(ids.size(), is(30)); + assertThat(ids).hasSize(30); } @Test @@ -1671,9 +1791,10 @@ public class ElasticsearchTemplateTests { .withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).withMinScore(2.0F).build(); Page page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then - assertThat(page.getTotalElements(), is(1L)); - assertThat(page.getContent().get(0).getMessage(), is("ab")); + assertThat(page.getTotalElements()).isEqualTo(1); + assertThat(page.getContent().get(0).getMessage()).isEqualTo("ab"); } @Test // DATAES-462 @@ -1696,13 +1817,14 @@ public class ElasticsearchTemplateTests { Page page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); // then - assertThat(page, instanceOf(AggregatedPage.class)); - assertThat(((AggregatedPage) page).getMaxScore(), greaterThan(0f)); - assertThat(page.getContent().get(0).getScore(), greaterThan(0f)); + assertThat(page).isInstanceOf(AggregatedPage.class); + assertThat(((AggregatedPage) page).getMaxScore()).isGreaterThan(0f); + assertThat(page.getContent().get(0).getScore()).isGreaterThan(0f); } @Test public void shouldDoIndexWithoutId() { + // given // document SampleEntity sampleEntity = new SampleEntity(); @@ -1711,19 +1833,22 @@ public class ElasticsearchTemplateTests { IndexQuery indexQuery = new IndexQuery(); indexQuery.setObject(sampleEntity); + // when String documentId = elasticsearchTemplate.index(indexQuery); + // then - assertThat(sampleEntity.getId(), is(equalTo(documentId))); + assertThat(sampleEntity.getId()).isEqualTo(documentId); GetQuery getQuery = new GetQuery(); getQuery.setId(documentId); SampleEntity result = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); - assertThat(result.getId(), is(equalTo(documentId))); + assertThat(result.getId()).isEqualTo(documentId); } @Test public void shouldDoBulkIndexWithoutId() { + // given List indexQueries = new ArrayList<>(); // first document @@ -1743,20 +1868,24 @@ public class ElasticsearchTemplateTests { IndexQuery indexQuery2 = new IndexQuery(); indexQuery2.setObject(sampleEntity2); indexQueries.add(indexQuery2); + // when elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), is(equalTo(2L))); + assertThat(sampleEntities.getTotalElements()).isEqualTo(2); - assertThat(sampleEntities.getContent().get(0).getId(), is(notNullValue())); - assertThat(sampleEntities.getContent().get(1).getId(), is(notNullValue())); + final List content = sampleEntities.getContent(); + assertThat(content.get(0).getId()).isNotNull(); + assertThat(content.get(1).getId()).isNotNull(); } @Test public void shouldIndexMapWithIndexNameAndTypeAtRuntime() { + // given Map person1 = new HashMap<>(); person1.put("userId", "1"); @@ -1818,16 +1947,16 @@ public class ElasticsearchTemplateTests { return null; } }); - assertThat(sampleEntities.getTotalElements(), is(equalTo(2L))); - assertThat(sampleEntities.getContent().get(0).get("userId"), is(person1.get("userId"))); - assertThat(sampleEntities.getContent().get(1).get("userId"), is(person2.get("userId"))); + + assertThat(sampleEntities.getTotalElements()).isEqualTo(2); + final List content = sampleEntities.getContent(); + assertThat(content.get(0).get("userId")).isEqualTo(person1.get("userId")); + assertThat(content.get(1).get("userId")).isEqualTo(person2.get("userId")); } - /* - DATAES-523 - */ - @Test + @Test // DATAES-523 public void shouldIndexGteEntityWithVersionType() { + // given String documentId = randomNumeric(5); GTEVersionEntity entity = GTEVersionEntity.builder().id(documentId).name("FooBar") @@ -1837,14 +1966,7 @@ public class ElasticsearchTemplateTests { .withIndexName(INDEX_NAME_SAMPLE_ENTITY).withType(TYPE_NAME).withVersion(entity.getVersion()) .withObject(entity); - Exception ex = null; - - try { - elasticsearchTemplate.index(indexQueryBuilder.build()); - } catch (Exception e) { - ex = e; - } - assertNull(ex); + elasticsearchTemplate.index(indexQueryBuilder.build()); elasticsearchTemplate.refresh(INDEX_NAME_SAMPLE_ENTITY); SearchQuery searchQuery = new NativeSearchQueryBuilder().withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME) @@ -1852,31 +1974,22 @@ public class ElasticsearchTemplateTests { // when Page entities = elasticsearchTemplate.queryForPage(searchQuery, GTEVersionEntity.class); // then - assertThat(entities, is(notNullValue())); - assertThat(entities.getTotalElements(), greaterThanOrEqualTo(1L)); + assertThat(entities).isNotNull(); + assertThat(entities.getTotalElements()).isGreaterThanOrEqualTo(1); // reindex with same version - try { - elasticsearchTemplate.index(indexQueryBuilder.build()); - } catch (Exception e) { - ex = e; - } - assertNull(ex); + elasticsearchTemplate.index(indexQueryBuilder.build()); elasticsearchTemplate.refresh(INDEX_NAME_SAMPLE_ENTITY); // reindex with version one below - try { + assertThatThrownBy(() -> { elasticsearchTemplate.index(indexQueryBuilder.withVersion(entity.getVersion() - 1).build()); - } catch (Exception e) { - ex = e; - } - assertNotNull(ex); - String message = ex.getMessage().toLowerCase(); - assertTrue("Exception is version conflict", message.contains("version") && message.contains("conflict")); + }).hasMessageContaining("version").hasMessageContaining("conflict"); } @Test public void shouldIndexSampleEntityWithIndexAndTypeAtRuntime() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -1890,18 +2003,18 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME) .withQuery(matchAllQuery()).build(); + // when Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then - assertThat(sampleEntities, is(notNullValue())); - assertThat(sampleEntities.getTotalElements(), greaterThanOrEqualTo(1L)); + assertThat(sampleEntities).isNotNull(); + assertThat(sampleEntities.getTotalElements()).isGreaterThanOrEqualTo(1); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldReturnCountForGivenCriteriaQueryWithGivenIndexUsingCriteriaQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -1912,17 +2025,17 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.addIndices(INDEX_NAME_SAMPLE_ENTITY); + // when long count = elasticsearchTemplate.count(criteriaQuery); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1); } - /* - DATAES-67 - */ - @Test + @Test // DATAES-67 public void shouldReturnCountForGivenSearchQueryWithGivenIndexUsingSearchQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -1933,17 +2046,17 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.refresh(SampleEntity.class); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withIndices(INDEX_NAME_SAMPLE_ENTITY).build(); + // when long count = elasticsearchTemplate.count(searchQuery); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldReturnCountForGivenCriteriaQueryWithGivenIndexAndTypeUsingCriteriaQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -1955,17 +2068,17 @@ public class ElasticsearchTemplateTests { CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.addIndices(INDEX_NAME_SAMPLE_ENTITY); criteriaQuery.addTypes(TYPE_NAME); + // when + long count = elasticsearchTemplate.count(criteriaQuery); // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1); } - /* - DATAES-67 - */ - @Test + @Test // DATAES-67 public void shouldReturnCountForGivenSearchQueryWithGivenIndexAndTypeUsingSearchQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -1976,17 +2089,17 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.refresh(SampleEntity.class); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).build(); + // when long count = elasticsearchTemplate.count(searchQuery); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldReturnCountForGivenCriteriaQueryWithGivenMultiIndices() { + // given cleanUpIndices(); String documentId1 = randomNumeric(5); @@ -2009,17 +2122,17 @@ public class ElasticsearchTemplateTests { CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.addIndices(INDEX_1_NAME, INDEX_2_NAME); + // when long count = elasticsearchTemplate.count(criteriaQuery); + // then - assertThat(count, is(equalTo(2L))); + assertThat(count).isEqualTo(2); } - /* - DATAES-67 - */ - @Test + @Test // DATAES-67 public void shouldReturnCountForGivenSearchQueryWithGivenMultiIndices() { + // given cleanUpIndices(); String documentId1 = randomNumeric(5); @@ -2042,10 +2155,12 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withIndices(INDEX_1_NAME, INDEX_2_NAME).build(); + // when long count = elasticsearchTemplate.count(searchQuery); + // then - assertThat(count, is(equalTo(2L))); + assertThat(count).isEqualTo(2); } private void cleanUpIndices() { @@ -2057,39 +2172,36 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.refresh(INDEX_2_NAME); } - /* - DATAES-71 - */ - @Test + @Test // DATAES-71 public void shouldCreatedIndexWithSpecifiedIndexName() { + // given elasticsearchTemplate.deleteIndex(INDEX_3_NAME); + // when elasticsearchTemplate.createIndex(INDEX_3_NAME); + // then - assertThat(elasticsearchTemplate.indexExists(INDEX_3_NAME), is(true)); + assertThat(elasticsearchTemplate.indexExists(INDEX_3_NAME)).isTrue(); } - /* - DATAES-72 - */ - @Test + @Test // DATAES-72 public void shouldDeleteIndexForSpecifiedIndexName() { + // given elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.refresh(SampleEntity.class); // when elasticsearchTemplate.deleteIndex(INDEX_3_NAME); + // then - assertThat(elasticsearchTemplate.indexExists(INDEX_3_NAME), is(false)); + assertThat(elasticsearchTemplate.indexExists(INDEX_3_NAME)).isFalse(); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldReturnCountForGivenCriteriaQueryWithGivenIndexNameForSpecificIndex() { + // given cleanUpIndices(); String documentId1 = randomNumeric(5); @@ -2112,17 +2224,17 @@ public class ElasticsearchTemplateTests { CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.addIndices(INDEX_1_NAME); + // when long count = elasticsearchTemplate.count(criteriaQuery); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1); } - /* - DATAES-67 - */ - @Test + @Test // DATAES-67 public void shouldReturnCountForGivenSearchQueryWithGivenIndexNameForSpecificIndex() { + // given cleanUpIndices(); String documentId1 = randomNumeric(5); @@ -2145,14 +2257,17 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices(INDEX_1_NAME) .build(); + // when long count = elasticsearchTemplate.count(searchQuery); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1); } @Test(expected = IllegalArgumentException.class) public void shouldThrowAnExceptionForGivenCriteriaQueryWhenNoIndexSpecifiedForCountQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -2162,17 +2277,17 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); + // when long count = elasticsearchTemplate.count(criteriaQuery); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1); } - /* - DATAES-67 - */ - @Test(expected = IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) // DATAES-67 public void shouldThrowAnExceptionForGivenSearchQueryWhenNoIndexSpecifiedForCountQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message") @@ -2182,17 +2297,14 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(SampleEntity.class); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); + // when - long count = elasticsearchTemplate.count(searchQuery); - // then - assertThat(count, is(equalTo(1L))); + elasticsearchTemplate.count(searchQuery); } - /* - DATAES-71 - */ - @Test + @Test // DATAES-71 public void shouldCreateIndexWithGivenSettings() { + // given String settings = "{\n" + " \"index\": {\n" + " \"number_of_shards\": \"1\",\n" + " \"number_of_replicas\": \"0\",\n" + " \"analysis\": {\n" @@ -2202,43 +2314,39 @@ public class ElasticsearchTemplateTests { + " }\n" + " }\n" + " }\n" + "}"; elasticsearchTemplate.deleteIndex(INDEX_3_NAME); + // when elasticsearchTemplate.createIndex(INDEX_3_NAME, settings); + // then Map map = elasticsearchTemplate.getSetting(INDEX_3_NAME); - boolean hasAnalyzer = map.containsKey("index.analysis.analyzer.emailAnalyzer.tokenizer"); - String emailAnalyzer = (String) map.get("index.analysis.analyzer.emailAnalyzer.tokenizer"); - assertThat(elasticsearchTemplate.indexExists(INDEX_3_NAME), is(true)); - assertThat(hasAnalyzer, is(true)); - assertThat(emailAnalyzer, is("uax_url_email")); + assertThat(elasticsearchTemplate.indexExists(INDEX_3_NAME)).isTrue(); + assertThat(map.containsKey("index.analysis.analyzer.emailAnalyzer.tokenizer")).isTrue(); + assertThat(map.get("index.analysis.analyzer.emailAnalyzer.tokenizer")).isEqualTo("uax_url_email"); } - /* - DATAES-71 - */ - @Test + @Test // DATAES-71 public void shouldCreateGivenSettingsForGivenIndex() { + // given // delete , create and apply mapping in before method // then Map map = elasticsearchTemplate.getSetting(SampleEntity.class); - assertThat(elasticsearchTemplate.indexExists(SampleEntity.class), is(true)); - assertThat(map.containsKey("index.refresh_interval"), is(true)); - assertThat(map.containsKey("index.number_of_replicas"), is(true)); - assertThat(map.containsKey("index.number_of_shards"), is(true)); - assertThat(map.containsKey("index.store.type"), is(true)); - assertThat((String) map.get("index.refresh_interval"), is("-1")); - assertThat((String) map.get("index.number_of_replicas"), is("0")); - assertThat((String) map.get("index.number_of_shards"), is("1")); - assertThat((String) map.get("index.store.type"), is("fs")); + assertThat(elasticsearchTemplate.indexExists(SampleEntity.class)).isTrue(); + assertThat(map.containsKey("index.refresh_interval")).isTrue(); + assertThat(map.containsKey("index.number_of_replicas")).isTrue(); + assertThat(map.containsKey("index.number_of_shards")).isTrue(); + assertThat(map.containsKey("index.store.type")).isTrue(); + assertThat(map.get("index.refresh_interval")).isEqualTo("-1"); + assertThat(map.get("index.number_of_replicas")).isEqualTo("0"); + assertThat(map.get("index.number_of_shards")).isEqualTo("1"); + assertThat(map.get("index.store.type")).isEqualTo("fs"); } - /* - DATAES-88 - */ - @Test + @Test // DATAES-88 public void shouldCreateIndexWithGivenClassAndSettings() { + // given String settings = "{\n" + " \"index\": {\n" + " \"number_of_shards\": \"1\",\n" + " \"number_of_replicas\": \"0\",\n" + " \"analysis\": {\n" @@ -2247,6 +2355,7 @@ public class ElasticsearchTemplateTests { + " \"tokenizer\": \"uax_url_email\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; + // when elasticsearchTemplate.deleteIndex(SampleEntity.class); elasticsearchTemplate.createIndex(SampleEntity.class, settings); elasticsearchTemplate.putMapping(SampleEntity.class); @@ -2254,15 +2363,16 @@ public class ElasticsearchTemplateTests { // then Map map = elasticsearchTemplate.getSetting(SampleEntity.class); - assertThat(elasticsearchTemplate.indexExists(INDEX_NAME_SAMPLE_ENTITY), is(true)); - assertThat(map.containsKey("index.number_of_replicas"), is(true)); - assertThat(map.containsKey("index.number_of_shards"), is(true)); - assertThat((String) map.get("index.number_of_replicas"), is("0")); - assertThat((String) map.get("index.number_of_shards"), is("1")); + assertThat(elasticsearchTemplate.indexExists(INDEX_NAME_SAMPLE_ENTITY)).isTrue(); + assertThat(map.containsKey("index.number_of_replicas")).isTrue(); + assertThat(map.containsKey("index.number_of_shards")).isTrue(); + assertThat((String) map.get("index.number_of_replicas")).isEqualTo("0"); + assertThat((String) map.get("index.number_of_shards")).isEqualTo("1"); } @Test public void shouldTestResultsAcrossMultipleIndices() { + // given String documentId1 = randomNumeric(5); SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId1).message("some message") @@ -2284,21 +2394,21 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withIndices(INDEX_1_NAME, INDEX_2_NAME).build(); + // when List sampleEntities = elasticsearchTemplate.queryForList(searchQuery, SampleEntity.class); // then - assertThat(sampleEntities.size(), is(equalTo(2))); + assertThat(sampleEntities).hasSize(2); } @Test - /** + /* * This is basically a demonstration to show composing entities out of heterogeneous indexes. */ public void shouldComposeObjectsReturnedFromHeterogeneousIndexes() { - // Given - + // given HetroEntity1 entity1 = new HetroEntity1(randomNumeric(3), "aFirstName"); HetroEntity2 entity2 = new HetroEntity2(randomNumeric(4), "aLastName"); @@ -2311,8 +2421,7 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.refresh(INDEX_1_NAME); elasticsearchTemplate.refresh(INDEX_2_NAME); - // When - + // when SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withTypes("hetro") .withIndices(INDEX_1_NAME, INDEX_2_NAME).build(); Page page = elasticsearchTemplate.queryForPage(searchQuery, ResultAggregator.class, @@ -2334,24 +2443,27 @@ public class ElasticsearchTemplateTests { } }); - assertThat(page.getTotalElements(), is(2l)); + assertThat(page.getTotalElements()).isEqualTo(2); } @Test public void shouldCreateIndexUsingServerDefaultConfiguration() { + // given // when boolean created = elasticsearchTemplate.createIndex(UseServerConfigurationEntity.class); + // then - assertThat(created, is(true)); + assertThat(created).isTrue(); final Map setting = elasticsearchTemplate.getSetting(UseServerConfigurationEntity.class); - assertThat(setting.get("index.number_of_shards"), Matchers. is("5")); - assertThat(setting.get("index.number_of_replicas"), Matchers. is("1")); + assertThat(setting.get("index.number_of_shards")).isEqualTo("5"); + assertThat(setting.get("index.number_of_replicas")).isEqualTo("1"); } @Test public void shouldReadFileFromClasspathRetainingNewlines() { + // given String settingsFile = "/settings/test-settings.yml"; @@ -2359,28 +2471,33 @@ public class ElasticsearchTemplateTests { String content = ElasticsearchTemplate.readFileFromClasspath(settingsFile); // then - assertThat(content, - is("index:\n" + " number_of_shards: 1\n" + " number_of_replicas: 0\n" + " analysis:\n" + " analyzer:\n" - + " emailAnalyzer:\n" + " type: custom\n" + " tokenizer: uax_url_email\n")); + assertThat(content).isEqualTo( + "index:\n" + " number_of_shards: 1\n" + " number_of_replicas: 0\n" + " analysis:\n" + " analyzer:\n" + + " emailAnalyzer:\n" + " type: custom\n" + " tokenizer: uax_url_email\n"); } @Test // DATAES-531 public void shouldReturnMappingForGivenEntityClass() { + + // given + // when boolean created = elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.putMapping(SampleEntity.class); - final Map mapping = elasticsearchTemplate.getMapping(SampleEntity.class); + final Map mapping = elasticsearchTemplate.getMapping(SampleEntity.class); + // then - assertThat(created, is(true)); - assertThat(mapping, notNullValue()); - assertThat(((Map) ((Map) mapping.get("properties")).get("message")).get("type"), Matchers. is("text")); + assertThat(created).isTrue(); + assertThat(mapping).isNotNull(); + assertThat(((Map) ((Map) mapping.get("properties")).get("message")).get("type")) + .isEqualTo("text"); } @Test // DATAES-525 public void shouldDeleteOnlyDocumentsMatchedByDeleteQuery() { - List indexQueries = new ArrayList<>(); // given + List indexQueries = new ArrayList<>(); // document to be deleted String documentIdToDelete = UUID.randomUUID().toString(); indexQueries.add(getIndexQuery(SampleEntity.builder().id(documentIdToDelete).message("some message") @@ -2403,12 +2520,13 @@ public class ElasticsearchTemplateTests { // document with id "remainingDocumentId" should still be indexed SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); - assertThat(sampleEntities.getContent().get(0).getId(), is(remainingDocumentId)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(1); + assertThat(sampleEntities.getContent().get(0).getId()).isEqualTo(remainingDocumentId); } @Test // DATAES-525 public void shouldDeleteOnlyDocumentsMatchedByCriteriaQuery() { + List indexQueries = new ArrayList<>(); // given @@ -2433,15 +2551,15 @@ public class ElasticsearchTemplateTests { // document with id "remainingDocumentId" should still be indexed SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); - assertThat(sampleEntities.getContent().get(0).getId(), is(remainingDocumentId)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(1); + assertThat(sampleEntities.getContent().get(0).getId()).isEqualTo(remainingDocumentId); } @Test // DATAES-525 public void shouldDeleteDocumentForGivenIdOnly() { - List indexQueries = new ArrayList<>(); // given + List indexQueries = new ArrayList<>(); // document to be deleted String documentIdToDelete = UUID.randomUUID().toString(); indexQueries.add(getIndexQuery(SampleEntity.builder().id(documentIdToDelete).message("some message") @@ -2462,12 +2580,13 @@ public class ElasticsearchTemplateTests { // document with id "remainingDocumentId" should still be indexed SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); - assertThat(sampleEntities.getContent().get(0).getId(), is(remainingDocumentId)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(1L); + assertThat(sampleEntities.getContent().get(0).getId()).isEqualTo(remainingDocumentId); } @Test // DATAES-525 public void shouldApplyCriteriaQueryToScanAndScrollForGivenCriteriaQuery() { + // given List indexQueries = new ArrayList<>(); indexQueries.add(getIndexQuery(SampleEntity.builder().id(UUID.randomUUID().toString()) @@ -2497,13 +2616,14 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.clearScroll(scroll.getScrollId()); // then - assertThat(sampleEntities.size(), is(equalTo(2))); - assertThat(sampleEntities.stream().map(SampleEntity::getMessage).collect(Collectors.toList()), - not(contains(notFindableMessage))); + assertThat(sampleEntities).hasSize(2); + assertThat(sampleEntities.stream().map(SampleEntity::getMessage).collect(Collectors.toList())) + .doesNotContain(notFindableMessage); } @Test // DATAES-525 public void shouldApplySearchQueryToScanAndScrollForGivenSearchQuery() { + // given List indexQueries = new ArrayList<>(); indexQueries.add(getIndexQuery(SampleEntity.builder().id(UUID.randomUUID().toString()) @@ -2531,20 +2651,22 @@ public class ElasticsearchTemplateTests { elasticsearchTemplate.clearScroll(scroll.getScrollId()); // then - assertThat(sampleEntities.size(), is(equalTo(2))); - assertThat(sampleEntities.stream().map(SampleEntity::getMessage).collect(Collectors.toList()), - not(contains(notFindableMessage))); + assertThat(sampleEntities).hasSize(2); + assertThat(sampleEntities.stream().map(SampleEntity::getMessage).collect(Collectors.toList())) + .doesNotContain(notFindableMessage); } @Test // DATAES-565 public void shouldRespectSourceFilterWithScanAndScrollForGivenSearchQuery() { + // given List entities = createSampleEntitiesWithMessage("Test message", 3); + // when elasticsearchTemplate.bulkIndex(entities); elasticsearchTemplate.refresh(SampleEntity.class); - // then + // then SourceFilter sourceFilter = new FetchSourceFilter(new String[] { "id" }, new String[] {}); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) @@ -2558,15 +2680,16 @@ public class ElasticsearchTemplateTests { scroll = elasticsearchTemplate.continueScroll(scroll.getScrollId(), 1000, SampleEntity.class); } elasticsearchTemplate.clearScroll(scroll.getScrollId()); - assertThat(sampleEntities.size(), is(equalTo(3))); - assertThat(sampleEntities.stream().map(SampleEntity::getId).collect(Collectors.toList()), - everyItem(notNullValue())); - assertThat(sampleEntities.stream().map(SampleEntity::getMessage).collect(Collectors.toList()), - everyItem(nullValue())); + assertThat(sampleEntities).hasSize(3); + assertThat(sampleEntities.stream().map(SampleEntity::getId).collect(Collectors.toList())) + .doesNotContain((String) null); + assertThat(sampleEntities.stream().map(SampleEntity::getMessage).collect(Collectors.toList())) + .containsOnly((String) null); } @Test // DATAES-457 public void shouldSortResultsGivenSortCriteriaWithScanAndScroll() { + // given List indexQueries = new ArrayList<>(); // first document @@ -2592,6 +2715,7 @@ public class ElasticsearchTemplateTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withSort(new FieldSortBuilder("rate").order(SortOrder.ASC)) .withSort(new FieldSortBuilder("message").order(SortOrder.DESC)).withPageable(PageRequest.of(0, 10)).build(); + // when ScrolledPage scroll = (ScrolledPage) elasticsearchTemplate.startScroll(1000, searchQuery, SampleEntity.class); @@ -2601,17 +2725,19 @@ public class ElasticsearchTemplateTests { scroll = (ScrolledPage) elasticsearchTemplate.continueScroll(scroll.getScrollId(), 1000, SampleEntity.class); } + // then - assertThat(sampleEntities.size(), equalTo(3)); - assertThat(sampleEntities.get(0).getRate(), is(sampleEntity2.getRate())); - assertThat(sampleEntities.get(1).getRate(), is(sampleEntity3.getRate())); - assertThat(sampleEntities.get(1).getMessage(), is(sampleEntity3.getMessage())); - assertThat(sampleEntities.get(2).getRate(), is(sampleEntity1.getRate())); - assertThat(sampleEntities.get(2).getMessage(), is(sampleEntity1.getMessage())); + assertThat(sampleEntities).hasSize(3); + assertThat(sampleEntities.get(0).getRate()).isEqualTo(sampleEntity2.getRate()); + assertThat(sampleEntities.get(1).getRate()).isEqualTo(sampleEntity3.getRate()); + assertThat(sampleEntities.get(1).getMessage()).isEqualTo(sampleEntity3.getMessage()); + assertThat(sampleEntities.get(2).getRate()).isEqualTo(sampleEntity1.getRate()); + assertThat(sampleEntities.get(2).getMessage()).isEqualTo(sampleEntity1.getMessage()); } @Test // DATAES-457 public void shouldSortResultsGivenSortCriteriaFromPageableWithScanAndScroll() { + // given List indexQueries = new ArrayList<>(); // first document @@ -2638,6 +2764,7 @@ public class ElasticsearchTemplateTests { .withPageable( PageRequest.of(0, 10, Sort.by(Sort.Direction.ASC, "rate").and(Sort.by(Sort.Direction.DESC, "message")))) .build(); + // when ScrolledPage scroll = (ScrolledPage) elasticsearchTemplate.startScroll(1000, searchQuery, SampleEntity.class); @@ -2647,13 +2774,14 @@ public class ElasticsearchTemplateTests { scroll = (ScrolledPage) elasticsearchTemplate.continueScroll(scroll.getScrollId(), 1000, SampleEntity.class); } + // then - assertThat(sampleEntities.size(), equalTo(3)); - assertThat(sampleEntities.get(0).getRate(), is(sampleEntity2.getRate())); - assertThat(sampleEntities.get(1).getRate(), is(sampleEntity3.getRate())); - assertThat(sampleEntities.get(1).getMessage(), is(sampleEntity3.getMessage())); - assertThat(sampleEntities.get(2).getRate(), is(sampleEntity1.getRate())); - assertThat(sampleEntities.get(2).getMessage(), is(sampleEntity1.getMessage())); + assertThat(sampleEntities).hasSize(3); + assertThat(sampleEntities.get(0).getRate()).isEqualTo(sampleEntity2.getRate()); + assertThat(sampleEntities.get(1).getRate()).isEqualTo(sampleEntity3.getRate()); + assertThat(sampleEntities.get(1).getMessage()).isEqualTo(sampleEntity3.getMessage()); + assertThat(sampleEntities.get(2).getRate()).isEqualTo(sampleEntity1.getRate()); + assertThat(sampleEntities.get(2).getMessage()).isEqualTo(sampleEntity1.getMessage()); } private IndexQuery getIndexQuery(SampleEntity sampleEntity) { @@ -2682,4 +2810,396 @@ public class ElasticsearchTemplateTests { this.lastName = lastName; } } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = INDEX_NAME_SAMPLE_ENTITY, type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @org.springframework.data.elasticsearch.annotations.Field(type = Text, store = true, + fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + SampleEntity that = (SampleEntity) o; + + if (available != that.available) + return false; + if (rate != that.rate) + return false; + if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) + : that.highlightedMessage != null) + return false; + if (id != null ? !id.equals(that.id) : that.id != null) + return false; + if (location != null ? !location.equals(that.location) : that.location != null) + return false; + if (message != null ? !message.equals(that.message) : that.message != null) + return false; + if (type != null ? !type.equals(that.type) : that.type != null) + return false; + if (version != null ? !version.equals(that.version) : that.version != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + result = 31 * result + (message != null ? message.hashCode() : 0); + result = 31 * result + rate; + result = 31 * result + (available ? 1 : 0); + result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0); + result = 31 * result + (location != null ? location.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } + } + + /** + * @author Gad Akuka + * @author Rizwan Idrees + * @author Mohsin Husen + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-uuid-keyed-core-template", type = "test-type-uuid-keyed", shards = 1, replicas = 0, + refreshInterval = "-1") + static class SampleEntityUUIDKeyed { + + @Id private UUID id; + private String type; + @Field(type = FieldType.Text, fielddata = true) private String message; + private int rate; + @ScriptedField private Long scriptedRate; + private boolean available; + private String highlightedMessage; + + private GeoPoint location; + + @Version private Long version; + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + SampleEntityUUIDKeyed that = (SampleEntityUUIDKeyed) o; + + if (available != that.available) + return false; + if (rate != that.rate) + return false; + if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) + : that.highlightedMessage != null) + return false; + if (id != null ? !id.equals(that.id) : that.id != null) + return false; + if (location != null ? !location.equals(that.location) : that.location != null) + return false; + if (message != null ? !message.equals(that.message) : that.message != null) + return false; + if (type != null ? !type.equals(that.type) : that.type != null) + return false; + if (version != null ? !version.equals(that.version) : that.version != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + result = 31 * result + (message != null ? message.hashCode() : 0); + result = 31 * result + rate; + result = 31 * result + (available ? 1 : 0); + result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0); + result = 31 * result + (location != null ? location.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Nordine Bittich + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-book-core-template", type = "book", shards = 1, replicas = 0, + refreshInterval = "-1") + static class Book { + + @Id private String id; + private String name; + @Field(type = FieldType.Object) private Author author; + @Field(type = FieldType.Nested) private Map> buckets = new HashMap<>(); + @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"), + otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop", + searchAnalyzer = "standard") }) private String description; + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class Author { + + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + /** + * @author Ivan Greene + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-version-core-template", type = "test-type", shards = 1, replicas = 0, + refreshInterval = "-1", versionType = VersionType.EXTERNAL_GTE) + static class GTEVersionEntity { + + @Version private Long version; + + @Id private String id; + + private String name; + } + + /** + * @author Abdul Waheed + * @author Mohsin Husen + */ + @Document(indexName = "test-index-hetro1-core-template", type = "hetro", replicas = 0, shards = 1) + static class HetroEntity1 { + + @Id private String id; + private String firstName; + @Version private Long version; + + public HetroEntity1(String id, String firstName) { + this.id = id; + this.firstName = firstName; + this.version = System.currentTimeMillis(); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public Long getVersion() { + return version; + } + + public void setVersion(Long version) { + this.version = version; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof SampleEntity)) { + return false; + } + if (this == obj) { + return true; + } + HetroEntity1 rhs = (HetroEntity1) obj; + return new EqualsBuilder().append(this.id, rhs.id).append(this.firstName, rhs.firstName) + .append(this.version, rhs.version).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(id).append(firstName).append(version).toHashCode(); + } + } + + /** + * @author Abdul Waheed + * @author Mohsin Husen + */ + @Document(indexName = "test-index-hetro2-core-template", type = "hetro", replicas = 0, shards = 1) + static class HetroEntity2 { + + @Id private String id; + private String lastName; + @Version private Long version; + + public HetroEntity2(String id, String lastName) { + this.id = id; + this.lastName = lastName; + this.version = System.currentTimeMillis(); + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public Long getVersion() { + return version; + } + + public void setVersion(Long version) { + this.version = version; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof SampleEntity)) { + return false; + } + if (this == obj) { + return true; + } + HetroEntity2 rhs = (HetroEntity2) obj; + return new EqualsBuilder().append(this.id, rhs.id).append(this.lastName, rhs.lastName) + .append(this.version, rhs.version).isEquals(); + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(id).append(lastName).append(version).toHashCode(); + } + } + + /** + * Created by akonczak on 12/12/2015. + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-server-configuration", type = "test-type", useServerConfiguration = true, + shards = 10, replicas = 10, refreshInterval = "-1") + static class UseServerConfigurationEntity { + + @Id private String id; + + private String val; + + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + @Document(indexName = "test-index-sample-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleMappingEntity { + + @Id private String id; + + @Field(type = Text, index = false, store = true, analyzer = "standard") private String message; + + private SampleMappingEntity.NestedEntity nested; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + static class NestedEntity { + + @Field(type = Text) private String someField; + + public String getSomeField() { + return someField; + } + + public void setSomeField(String someField) { + this.someField = someField; + } + } + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTransportTemplateTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTransportTemplateTests.java index 253da30d2..bc3579c03 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTransportTemplateTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTransportTemplateTests.java @@ -1,18 +1,53 @@ +/* + * Copyright 2018-2019 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; import static org.apache.commons.lang.RandomStringUtils.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.lang.Double; +import java.lang.Long; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.engine.DocumentMissingException; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.query.UpdateQuery; import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder; -import org.springframework.data.elasticsearch.entities.SampleEntity; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +/** + * @author Peter-Josef Meisch + */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTests { @@ -22,8 +57,35 @@ public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTe // when IndexRequest indexRequest = new IndexRequest(); indexRequest.source("{}", XContentType.JSON); - UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)) - .withClass(SampleEntity.class).withIndexRequest(indexRequest).build(); + UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)).withClass(SampleEntity.class) + .withIndexRequest(indexRequest).build(); elasticsearchTemplate.update(updateQuery); } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-core-transport-template", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/LogEntityTests.java b/src/test/java/org/springframework/data/elasticsearch/core/LogEntityTests.java index cb1a4d46f..955ea35cc 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/LogEntityTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/LogEntityTests.java @@ -15,14 +15,14 @@ */ package org.springframework.data.elasticsearch.core; +import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.Matchers.*; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; +import java.util.Date; import java.util.List; import org.elasticsearch.action.search.SearchPhaseExecutionException; @@ -30,11 +30,13 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.elasticsearch.core.facet.LogEntity; -import org.springframework.data.elasticsearch.core.facet.LogEntityBuilder; +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.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -43,79 +45,188 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * * @author Artur Konczak * @author Mohsin Husen + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class LogEntityTests { - @Autowired - private ElasticsearchTemplate template; + @Autowired private ElasticsearchTemplate template; @Before public void before() throws ParseException { - template.deleteIndex(LogEntity.class); - template.createIndex(LogEntity.class); - template.putMapping(LogEntity.class); + + IndexInitializer.init(template, LogEntity.class); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - IndexQuery indexQuery1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse("2013-10-18 18:01")).code(2) - .ip("10.10.10.1").buildIndex(); + IndexQuery indexQuery1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse("2013-10-18 18:01")) + .code(2).ip("10.10.10.1").buildIndex(); - IndexQuery indexQuery2 = new LogEntityBuilder("2").action("update").date(dateFormatter.parse("2013-10-19 18:02")).code(2) - .ip("10.10.10.2").buildIndex(); + IndexQuery indexQuery2 = new LogEntityBuilder("2").action("update").date(dateFormatter.parse("2013-10-19 18:02")) + .code(2).ip("10.10.10.2").buildIndex(); - IndexQuery indexQuery3 = new LogEntityBuilder("3").action("update").date(dateFormatter.parse("2013-10-19 18:03")).code(2) - .ip("10.10.10.3").buildIndex(); + IndexQuery indexQuery3 = new LogEntityBuilder("3").action("update").date(dateFormatter.parse("2013-10-19 18:03")) + .code(2).ip("10.10.10.3").buildIndex(); - IndexQuery indexQuery4 = new LogEntityBuilder("4").action("update").date(dateFormatter.parse("2013-10-19 18:04")).code(2) - .ip("10.10.10.4").buildIndex(); + IndexQuery indexQuery4 = new LogEntityBuilder("4").action("update").date(dateFormatter.parse("2013-10-19 18:04")) + .code(2).ip("10.10.10.4").buildIndex(); template.bulkIndex(Arrays.asList(indexQuery1, indexQuery2, indexQuery3, indexQuery4)); template.refresh(LogEntity.class); } - /* - DATAES-66 - */ - @Test - public void shouldIndexGivenLogEntityWithIPFieldType() throws ParseException { - //when - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(termQuery("ip", "10.10.10.1")).build(); + @Test // DATAES-66 + public void shouldIndexGivenLogEntityWithIPFieldType() { + // when + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("ip", "10.10.10.1")).build(); List entities = template.queryForList(searchQuery, LogEntity.class); - //then - assertThat(entities, is(notNullValue())); - assertThat(entities.size(), is(1)); + + // then + assertThat(entities).isNotNull().hasSize(1); } - /* - DATAES-66 - */ - @Test(expected = SearchPhaseExecutionException.class) + @Test(expected = SearchPhaseExecutionException.class) // DATAES-66 public void shouldThrowExceptionWhenInvalidIPGivenForSearchQuery() { - //when - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(termQuery("ip", "10.10.10")).build(); + // when + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("ip", "10.10.10")).build(); List entities = template.queryForList(searchQuery, LogEntity.class); - //then - assertThat(entities, is(notNullValue())); - assertThat(entities.size(), is(1)); + + // then + assertThat(entities).isNotNull().hasSize(1); } - /* - DATAES-66 - */ - @Test + @Test // DATAES-66 public void shouldReturnLogsForGivenIPRanges() { - //when + + // when SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(rangeQuery("ip").from("10.10.10.1").to("10.10.10.3")).build(); - List entities = template.queryForList(searchQuery, LogEntity.class); - //then - assertThat(entities, is(notNullValue())); - assertThat(entities.size(), is(3)); + + // then + assertThat(entities).isNotNull().hasSize(3); + } + + /** + * Simple type to test facets + * + * @author Artur Konczak + * @author Mohsin Husen + */ + + @Document(indexName = "test-index-log-core", type = "test-log-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class LogEntity { + + private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); + + @Id private String id; + + private String action; + + private long sequenceCode; + + @Field(type = Ip) private String ip; + + @Field(type = Date) private java.util.Date date; + + private LogEntity() {} + + public LogEntity(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getAction() { + return action; + } + + public String toString() { + return new StringBuffer().append("{id:").append(id).append(",action:").append(action).append(",code:") + .append(sequenceCode).append(",date:").append(format.format(date)).append("}").toString(); + } + + public void setAction(String action) { + this.action = action; + } + + public long getSequenceCode() { + return sequenceCode; + } + + public void setSequenceCode(long sequenceCode) { + this.sequenceCode = sequenceCode; + } + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + } + + /** + * Simple type to test facets + * + * @author Artur Konczak + * @author Mohsin Husen + */ + + static class LogEntityBuilder { + + private LogEntity result; + + public LogEntityBuilder(String id) { + result = new LogEntity(id); + } + + public LogEntityBuilder action(String action) { + result.setAction(action); + return this; + } + + public LogEntityBuilder code(long sequenceCode) { + result.setSequenceCode(sequenceCode); + return this; + } + + public LogEntityBuilder date(Date date) { + result.setDate(date); + return this; + } + + public LogEntityBuilder ip(String ip) { + result.setIp(ip); + return this; + } + + public LogEntity build() { + return result; + } + + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/MappingBuilderTests.java b/src/test/java/org/springframework/data/elasticsearch/core/MappingBuilderTests.java index 48b5a59f9..45500e7c8 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/MappingBuilderTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/MappingBuilderTests.java @@ -16,48 +16,58 @@ package org.springframework.data.elasticsearch.core; +import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.skyscreamer.jsonassert.JSONAssert.assertEquals; +import static org.skyscreamer.jsonassert.JSONAssert.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; import static org.springframework.data.elasticsearch.utils.IndexBuilder.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.io.IOException; +import java.lang.Boolean; +import java.lang.Integer; import java.math.BigDecimal; +import java.util.Collection; import java.util.Collections; import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; +import org.assertj.core.data.Percentage; import org.json.JSONException; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Transient; import org.springframework.data.elasticsearch.annotations.CompletionField; 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.GeoPointField; import org.springframework.data.elasticsearch.annotations.InnerField; import org.springframework.data.elasticsearch.annotations.Mapping; import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.annotations.Parent; -import org.springframework.data.elasticsearch.builder.SampleInheritedEntityBuilder; +import org.springframework.data.elasticsearch.annotations.Setting; import org.springframework.data.elasticsearch.core.completion.Completion; import org.springframework.data.elasticsearch.core.geo.GeoPoint; +import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; -import org.springframework.data.elasticsearch.entities.Book; -import org.springframework.data.elasticsearch.entities.CopyToEntity; -import org.springframework.data.elasticsearch.entities.GeoEntity; -import org.springframework.data.elasticsearch.entities.Group; -import org.springframework.data.elasticsearch.entities.NormalizerEntity; -import org.springframework.data.elasticsearch.entities.SampleInheritedEntity; -import org.springframework.data.elasticsearch.entities.SampleTransientEntity; -import org.springframework.data.elasticsearch.entities.SimpleRecursiveEntity; -import org.springframework.data.elasticsearch.entities.StockPrice; -import org.springframework.data.elasticsearch.entities.User; +import org.springframework.data.geo.Box; +import org.springframework.data.geo.Circle; +import org.springframework.data.geo.Point; +import org.springframework.data.geo.Polygon; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -77,9 +87,23 @@ public class MappingBuilderTests extends MappingContextBaseTests { @Autowired private ElasticsearchTemplate elasticsearchTemplate; + @Before + public void before() { + + elasticsearchTemplate.deleteIndex(StockPrice.class); + elasticsearchTemplate.deleteIndex(SimpleRecursiveEntity.class); + elasticsearchTemplate.deleteIndex(StockPrice.class); + elasticsearchTemplate.deleteIndex(SampleInheritedEntity.class); + elasticsearchTemplate.deleteIndex(User.class); + elasticsearchTemplate.deleteIndex(Group.class); + elasticsearchTemplate.deleteIndex(Book.class); + elasticsearchTemplate.deleteIndex(NormalizerEntity.class); + elasticsearchTemplate.deleteIndex(CopyToEntity.class); + } + @Test public void shouldNotFailOnCircularReference() { - elasticsearchTemplate.deleteIndex(SimpleRecursiveEntity.class); + elasticsearchTemplate.createIndex(SimpleRecursiveEntity.class); elasticsearchTemplate.putMapping(SimpleRecursiveEntity.class); elasticsearchTemplate.refresh(SimpleRecursiveEntity.class); @@ -115,7 +139,6 @@ public class MappingBuilderTests extends MappingContextBaseTests { // Given // When - elasticsearchTemplate.deleteIndex(StockPrice.class); elasticsearchTemplate.createIndex(StockPrice.class); elasticsearchTemplate.putMapping(StockPrice.class); String symbol = "AU"; @@ -128,11 +151,12 @@ public class MappingBuilderTests extends MappingContextBaseTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); List result = elasticsearchTemplate.queryForList(searchQuery, StockPrice.class); + // Then - assertThat(result.size(), is(1)); + assertThat(result).hasSize(1); StockPrice entry = result.get(0); - assertThat(entry.getSymbol(), is(symbol)); - assertThat(entry.getPrice(), is(BigDecimal.valueOf(price))); + assertThat(entry.getSymbol()).isEqualTo(symbol); + assertThat(entry.getPrice()).isCloseTo(BigDecimal.valueOf(price), Percentage.withPercentage(0.01)); } @Test // DATAES-568 @@ -160,10 +184,9 @@ public class MappingBuilderTests extends MappingContextBaseTests { @Test // DATAES-76 public void shouldAddSampleInheritedEntityDocumentToIndex() { - // Given + // given - // When - elasticsearchTemplate.deleteIndex(SampleInheritedEntity.class); + // when elasticsearchTemplate.createIndex(SampleInheritedEntity.class); elasticsearchTemplate.putMapping(SampleInheritedEntity.class); Date createdDate = new Date(); @@ -175,12 +198,13 @@ public class MappingBuilderTests extends MappingContextBaseTests { SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); List result = elasticsearchTemplate.queryForList(searchQuery, SampleInheritedEntity.class); - // Then - assertThat(result.size(), is(1)); + + // then + assertThat(result).hasSize(1); SampleInheritedEntity entry = result.get(0); - assertThat(entry.getCreatedDate(), is(createdDate)); - assertThat(entry.getMessage(), is(message)); + assertThat(entry.getCreatedDate()).isEqualTo(createdDate); + assertThat(entry.getMessage()).isEqualTo(message); } @Test // DATAES-568 @@ -207,6 +231,7 @@ public class MappingBuilderTests extends MappingContextBaseTests { elasticsearchTemplate.putMapping(User.class); elasticsearchTemplate.createIndex(Group.class); elasticsearchTemplate.putMapping(Group.class); + // when // then @@ -218,7 +243,9 @@ public class MappingBuilderTests extends MappingContextBaseTests { // given elasticsearchTemplate.createIndex(Book.class); elasticsearchTemplate.putMapping(Book.class); + // when + // then } @@ -226,7 +253,6 @@ public class MappingBuilderTests extends MappingContextBaseTests { public void shouldUseBothAnalyzer() { // given - elasticsearchTemplate.deleteIndex(Book.class); elasticsearchTemplate.createIndex(Book.class); elasticsearchTemplate.putMapping(Book.class); @@ -236,19 +262,18 @@ public class MappingBuilderTests extends MappingContextBaseTests { Map prefixDescription = (Map) ((Map) descriptionMapping.get("fields")).get("prefix"); // then - assertThat(prefixDescription.size(), is(3)); - assertThat(prefixDescription.get("type"), equalTo("text")); - assertThat(prefixDescription.get("analyzer"), equalTo("stop")); - assertThat(prefixDescription.get("search_analyzer"), equalTo("standard")); - assertThat(descriptionMapping.get("type"), equalTo("text")); - assertThat(descriptionMapping.get("analyzer"), equalTo("whitespace")); + assertThat(prefixDescription).hasSize(3); + assertThat(prefixDescription.get("type")).isEqualTo("text"); + assertThat(prefixDescription.get("analyzer")).isEqualTo("stop"); + assertThat(prefixDescription.get("search_analyzer")).isEqualTo("standard"); + assertThat(descriptionMapping.get("type")).isEqualTo("text"); + assertThat(descriptionMapping.get("analyzer")).isEqualTo("whitespace"); } @Test // DATAES-492 public void shouldUseKeywordNormalizer() { // given - elasticsearchTemplate.deleteIndex(NormalizerEntity.class); elasticsearchTemplate.createIndex(NormalizerEntity.class); elasticsearchTemplate.putMapping(NormalizerEntity.class); @@ -259,17 +284,16 @@ public class MappingBuilderTests extends MappingContextBaseTests { Map fieldDescriptionLowerCase = (Map) ((Map) ((Map) properties.get("description")).get("fields")).get("lower_case"); // then - assertThat(fieldName.get("type"), equalTo("keyword")); - assertThat(fieldName.get("normalizer"), equalTo("lower_case_normalizer")); - assertThat(fieldDescriptionLowerCase.get("type"), equalTo("keyword")); - assertThat(fieldDescriptionLowerCase.get("normalizer"), equalTo("lower_case_normalizer")); + assertThat(fieldName.get("type")).isEqualTo("keyword"); + assertThat(fieldName.get("normalizer")).isEqualTo("lower_case_normalizer"); + assertThat(fieldDescriptionLowerCase.get("type")).isEqualTo("keyword"); + assertThat(fieldDescriptionLowerCase.get("normalizer")).isEqualTo("lower_case_normalizer"); } @Test // DATAES-503 public void shouldUseCopyTo() { // given - elasticsearchTemplate.deleteIndex(CopyToEntity.class); elasticsearchTemplate.createIndex(CopyToEntity.class); elasticsearchTemplate.putMapping(CopyToEntity.class); @@ -281,8 +305,8 @@ public class MappingBuilderTests extends MappingContextBaseTests { // then List copyToValue = Collections.singletonList("name"); - assertThat(fieldFirstName.get("copy_to"), equalTo(copyToValue)); - assertThat(fieldLastName.get("copy_to"), equalTo(copyToValue)); + assertThat(fieldFirstName.get("copy_to")).isEqualTo(copyToValue); + assertThat(fieldLastName.get("copy_to")).isEqualTo(copyToValue); } @Test // DATAES-568 @@ -455,7 +479,7 @@ public class MappingBuilderTests extends MappingContextBaseTests { /** * MinimalChildEntity * - * @author Peter-josef Meisch + * @author Peter-Josef Meisch */ @Document(indexName = "test-index-minimal", type = "mapping") static class MinimalChildEntity { @@ -464,4 +488,303 @@ public class MappingBuilderTests extends MappingContextBaseTests { @Parent(type = "parentType") private String parentId; } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Nordine Bittich + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-book-mapping-builder", type = "book", shards = 1, replicas = 0, refreshInterval = "-1") + static class Book { + + @Id private String id; + private String name; + @Field(type = FieldType.Object) private Author author; + @Field(type = FieldType.Nested) private Map> buckets = new HashMap<>(); + @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"), + otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop", + searchAnalyzer = "standard") }) private String description; + } + + /** + * @author Stuart Stevenson + * @author Mohsin Husen + */ + @Document(indexName = "test-index-simple-recursive-mapping-builder", type = "circular-object", shards = 1, replicas = 0, + refreshInterval = "-1") + static class SimpleRecursiveEntity { + + @Id private String id; + @Field(type = FieldType.Object, ignoreFields = { "circularObject" }) private SimpleRecursiveEntity circularObject; + } + + /** + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-copy-to-mapping-builder", type = "test", shards = 1, replicas = 0, refreshInterval = "-1") + static class CopyToEntity { + + @Id private String id; + + @Field(type = FieldType.Keyword, copyTo = "name") private String firstName; + + @Field(type = FieldType.Keyword, copyTo = "name") private String lastName; + + @Field(type = FieldType.Keyword) private String name; + } + + /** + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-normalizer-mapping-builder", type = "test", shards = 1, replicas = 0, refreshInterval = "-1") + @Setting(settingPath = "/settings/test-normalizer.json") + static class NormalizerEntity { + + @Id private String id; + + @Field(type = FieldType.Keyword, normalizer = "lower_case_normalizer") private String name; + + @MultiField(mainField = @Field(type = FieldType.Text), otherFields = { @InnerField(suffix = "lower_case", + type = FieldType.Keyword, normalizer = "lower_case_normalizer") }) private String description; + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class Author { + + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + + /** + * @author Kevin Leturc + */ + @Document(indexName = "test-index-sample-inherited-mapping-builder", type = "mapping", shards = 1, replicas = 0, + refreshInterval = "-1") + static class SampleInheritedEntity extends AbstractInheritedEntity { + + @Field(type = Text, index = false, store = true, analyzer = "standard") private String message; + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + } + + /** + * @author Kevin Leturc + */ + static class SampleInheritedEntityBuilder { + + private SampleInheritedEntity result; + + public SampleInheritedEntityBuilder(String id) { + result = new SampleInheritedEntity(); + result.setId(id); + } + + public SampleInheritedEntityBuilder createdDate(Date createdDate) { + result.setCreatedDate(createdDate); + return this; + } + + public SampleInheritedEntityBuilder message(String message) { + result.setMessage(message); + return this; + } + + public SampleInheritedEntity build() { + return result; + } + + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } + } + + /** + * @author Artur Konczak + * @author Mohsin Husen + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-stock-mapping-builder", type = "price", shards = 1, replicas = 0, refreshInterval = "-1") + static class StockPrice { + + @Id private String id; + + private String symbol; + + @Field(type = FieldType.Double) private BigDecimal price; + } + + /** + * @author Kevin Letur + */ + static class AbstractInheritedEntity { + + @Id private String id; + + @Field(type = FieldType.Date, index = false) private Date createdDate; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + } + + /** + * @author Jakub Vavrik + */ + @Document(indexName = "test-index-recursive-mapping-mapping-builder", type = "mapping", shards = 1, replicas = 0, + refreshInterval = "-1") + static class SampleTransientEntity { + + @Id private String id; + + @Field(type = Text, index = false, store = true, analyzer = "standard") private String message; + + @Transient private SampleTransientEntity.NestedEntity nested; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + static class NestedEntity { + + @Field private static SampleTransientEntity.NestedEntity someField = new SampleTransientEntity.NestedEntity(); + @Field private Boolean something; + + public SampleTransientEntity.NestedEntity getSomeField() { + return someField; + } + + public void setSomeField(SampleTransientEntity.NestedEntity someField) { + this.someField = someField; + } + + public Boolean getSomething() { + return something; + } + + public void setSomething(Boolean something) { + this.something = something; + } + } + } + + /** + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-geo-mapping-builder", type = "geo-test-index", shards = 1, replicas = 0, refreshInterval = "-1") + static class GeoEntity { + + @Id private String id; + + // geo shape - Spring Data + private Box box; + private Circle circle; + private Polygon polygon; + + // geo point - Custom implementation + Spring Data + @GeoPointField private Point pointA; + + private GeoPoint pointB; + + @GeoPointField private String pointC; + + @GeoPointField private double[] pointD; + } + + /** + * Created by akonczak on 21/08/2016. + */ + @Document(indexName = "test-index-user-mapping-builder", type = "user") + static class User { + @Id private String id; + + @Field(type = FieldType.Nested, ignoreFields = { "users" }) private Set groups = new HashSet<>(); + } + + /** + * Created by akonczak on 21/08/2016. + */ + @Document(indexName = "test-index-group-mapping-builder", type = "group") + static class Group { + + @Id String id; + + @Field(type = FieldType.Nested, ignoreFields = { "groups" }) private Set users = new HashSet<>(); + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/MappingContextBaseTests.java b/src/test/java/org/springframework/data/elasticsearch/core/MappingContextBaseTests.java index dbac910d3..98f7513b3 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/MappingContextBaseTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/MappingContextBaseTests.java @@ -15,9 +15,6 @@ package org.springframework.data.elasticsearch.core; -import java.util.Collection; -import java.util.Collections; - import org.springframework.data.elasticsearch.config.ElasticsearchConfigurationSupport; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter; @@ -37,13 +34,8 @@ abstract class MappingContextBaseTests { private SimpleElasticsearchMappingContext setupMappingContext() { - SimpleElasticsearchMappingContext mappingContext = new ElasticsearchConfigurationSupport() { - @Override - protected Collection getMappingBasePackages() { - return Collections.singletonList("org.springframework.data.elasticsearch.entities.mapping"); - } - }.elasticsearchMappingContext(); - + SimpleElasticsearchMappingContext mappingContext = new ElasticsearchConfigurationSupport() {} + .elasticsearchMappingContext(); mappingContext.initialize(); return mappingContext; } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateTests.java index ae582db74..47f1fd822 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateTests.java @@ -17,13 +17,21 @@ package org.springframework.data.elasticsearch.core; import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Data; +import lombok.Getter; import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.lang.Double; +import java.lang.Long; +import java.lang.Object; import java.net.ConnectException; import java.util.Arrays; import java.util.Collections; @@ -39,10 +47,10 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; - import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -50,6 +58,10 @@ import org.springframework.data.elasticsearch.ElasticsearchVersion; import org.springframework.data.elasticsearch.ElasticsearchVersionRule; import org.springframework.data.elasticsearch.TestUtils; import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.query.Criteria; import org.springframework.data.elasticsearch.core.query.CriteriaQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; @@ -57,7 +69,6 @@ import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.data.elasticsearch.core.query.StringQuery; -import org.springframework.data.elasticsearch.entities.SampleEntity; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.util.StringUtils; @@ -68,6 +79,7 @@ import org.springframework.util.StringUtils; * @author Christoph Strobl * @author Mark Paluch * @currentRead Golden Fool - Robin Hobb + * @author Peter-Josef Meisch */ @RunWith(SpringRunner.class) @ContextConfiguration("classpath:infrastructure.xml") @@ -75,7 +87,7 @@ public class ReactiveElasticsearchTemplateTests { public @Rule ElasticsearchVersionRule elasticsearchVersion = ElasticsearchVersionRule.any(); - static final String DEFAULT_INDEX = "test-index-sample"; + static final String DEFAULT_INDEX = "reactive-template-test-index"; static final String ALTERNATE_INDEX = "reactive-template-tests-alternate-index"; private ElasticsearchRestTemplate restTemplate; @@ -676,4 +688,74 @@ public class ReactiveElasticsearchTemplateTests { static class Message { String message; } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = DEFAULT_INDEX, type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + SampleEntity that = (SampleEntity) o; + + if (available != that.available) + return false; + if (rate != that.rate) + return false; + if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) + : that.highlightedMessage != null) + return false; + if (id != null ? !id.equals(that.id) : that.id != null) + return false; + if (location != null ? !location.equals(that.location) : that.location != null) + return false; + if (message != null ? !message.equals(that.message) : that.message != null) + return false; + if (type != null ? !type.equals(that.type) : that.type != null) + return false; + if (version != null ? !version.equals(that.version) : that.version != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + result = 31 * result + (message != null ? message.hashCode() : 0); + result = 31 * result + rate; + result = 31 * result + (available ? 1 : 0); + result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0); + result = 31 * result + (location != null ? location.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateUnitTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateUnitTests.java index 8f58907f8..36d744a4a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateUnitTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ReactiveElasticsearchTemplateUnitTests.java @@ -18,13 +18,21 @@ package org.springframework.data.elasticsearch.core; import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.action.search.SearchRequest.*; import static org.mockito.Mockito.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.lang.Double; +import java.lang.Long; +import java.lang.Object; import java.util.Collections; import org.elasticsearch.action.delete.DeleteRequest; @@ -41,15 +49,24 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.query.Criteria; import org.springframework.data.elasticsearch.core.query.CriteriaQuery; import org.springframework.data.elasticsearch.core.query.StringQuery; -import org.springframework.data.elasticsearch.entities.SampleEntity; /** * @author Christoph Strobl * @currentRead Fool's Fate - Robin Hobb + * @author Peter-Josef Meisch */ public class ReactiveElasticsearchTemplateUnitTests { @@ -61,6 +78,7 @@ public class ReactiveElasticsearchTemplateUnitTests { @Before public void setUp() { + template = new ReactiveElasticsearchTemplate(client); } @@ -126,7 +144,6 @@ public class ReactiveElasticsearchTemplateUnitTests { ArgumentCaptor captor = ArgumentCaptor.forClass(SearchRequest.class); when(client.search(captor.capture())).thenReturn(Flux.empty()); - template.find(new CriteriaQuery(new Criteria("*")).setPageable(PageRequest.of(2, 50)), SampleEntity.class) // .as(StepVerifier::create) // .verifyComplete(); @@ -141,7 +158,6 @@ public class ReactiveElasticsearchTemplateUnitTests { ArgumentCaptor captor = ArgumentCaptor.forClass(SearchRequest.class); when(client.scroll(captor.capture())).thenReturn(Flux.empty()); - template.find(new CriteriaQuery(new Criteria("*")).setPageable(Pageable.unpaged()), SampleEntity.class) // .as(StepVerifier::create) // .verifyComplete(); @@ -232,4 +248,74 @@ public class ReactiveElasticsearchTemplateUnitTests { assertThat(captor.getValue().indicesOptions()).isEqualTo(IndicesOptions.LENIENT_EXPAND_OPEN); } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-core-reactive-template-Unit", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + SampleEntity that = (SampleEntity) o; + + if (available != that.available) + return false; + if (rate != that.rate) + return false; + if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) + : that.highlightedMessage != null) + return false; + if (id != null ? !id.equals(that.id) : that.id != null) + return false; + if (location != null ? !location.equals(that.location) : that.location != null) + return false; + if (message != null ? !message.equals(that.message) : that.message != null) + return false; + if (type != null ? !type.equals(that.type) : that.type != null) + return false; + if (version != null ? !version.equals(that.version) : that.version != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + result = 31 * result + (message != null ? message.hashCode() : 0); + result = 31 * result + rate; + result = 31 * result + (available ? 1 : 0); + result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0); + result = 31 * result + (location != null ? location.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/SimpleDynamicTemplatesMappingTests.java b/src/test/java/org/springframework/data/elasticsearch/core/SimpleDynamicTemplatesMappingTests.java index 339537f0c..c03cc8268 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/SimpleDynamicTemplatesMappingTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/SimpleDynamicTemplatesMappingTests.java @@ -3,12 +3,16 @@ package org.springframework.data.elasticsearch.core; import static org.junit.Assert.*; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; - -import org.springframework.data.elasticsearch.entities.SampleDynamicTemplatesEntity; -import org.springframework.data.elasticsearch.entities.SampleDynamicTemplatesEntityTwo; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.DynamicTemplates; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.FieldType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -48,4 +52,31 @@ public class SimpleDynamicTemplatesMappingTests extends MappingContextBaseTests assertEquals(EXPECTED_MAPPING_TWO, mapping); } + + /** + * @author Petr Kukral + */ + @Document(indexName = "test-dynamictemplates", type = "test-dynamictemplatestype", indexStoreType = "memory", + shards = 1, replicas = 0, refreshInterval = "-1") + @DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings.json") + static class SampleDynamicTemplatesEntity { + + @Id private String id; + + @Field(type = FieldType.Object) private Map names = new HashMap(); + } + + /** + * @author Petr Kukral + */ + @Document(indexName = "test-dynamictemplates", type = "test-dynamictemplatestype", indexStoreType = "memory", + shards = 1, replicas = 0, refreshInterval = "-1") + @DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings_two.json") + static class SampleDynamicTemplatesEntityTwo { + + @Id private String id; + + @Field(type = FieldType.Object) private Map names = new HashMap(); + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/SimpleElasticsearchDateMappingTests.java b/src/test/java/org/springframework/data/elasticsearch/core/SimpleElasticsearchDateMappingTests.java index 022906825..294b67e17 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/SimpleElasticsearchDateMappingTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/SimpleElasticsearchDateMappingTests.java @@ -16,12 +16,17 @@ package org.springframework.data.elasticsearch.core; import static org.junit.Assert.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; import java.io.IOException; +import java.util.Date; import org.junit.Test; - -import org.springframework.data.elasticsearch.entities.SampleDateMappingEntity; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.DateFormat; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.FieldType; /** * @author Jakub Vavrik @@ -43,4 +48,63 @@ public class SimpleElasticsearchDateMappingTests extends MappingContextBaseTests assertEquals(EXPECTED_MAPPING, mapping); } + + /** + * @author Jakub Vavrik + */ + @Document(indexName = "test-index-date-mapping-core", type = "mapping", shards = 1, replicas = 0, + refreshInterval = "-1") + static class SampleDateMappingEntity { + + @Id private String id; + + @Field(type = Text, index = false, store = true, analyzer = "standard") private String message; + + @Field(type = Date, format = DateFormat.custom, + pattern = "dd.MM.yyyy hh:mm") private java.util.Date customFormatDate; + + @Field(type = FieldType.Date) private Date defaultFormatDate; + + @Field(type = FieldType.Date, format = DateFormat.basic_date) private Date basicFormatDate; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Date getCustomFormatDate() { + return customFormatDate; + } + + public void setCustomFormatDate(Date customFormatDate) { + this.customFormatDate = customFormatDate; + } + + public Date getDefaultFormatDate() { + return defaultFormatDate; + } + + public void setDefaultFormatDate(Date defaultFormatDate) { + this.defaultFormatDate = defaultFormatDate; + } + + public Date getBasicFormatDate() { + return basicFormatDate; + } + + public void setBasicFormatDate(Date basicFormatDate) { + this.basicFormatDate = basicFormatDate; + } + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/aggregation/ElasticsearchTemplateAggregationTests.java b/src/test/java/org/springframework/data/elasticsearch/core/aggregation/ElasticsearchTemplateAggregationTests.java index 2683db1dd..5192ee87f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/aggregation/ElasticsearchTemplateAggregationTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/aggregation/ElasticsearchTemplateAggregationTests.java @@ -15,39 +15,44 @@ */ package org.springframework.data.elasticsearch.core.aggregation; -import static org.elasticsearch.action.search.SearchType.*; +import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.search.aggregations.AggregationBuilders.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; + +import java.lang.Integer; +import java.util.ArrayList; +import java.util.List; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.search.aggregations.Aggregations; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +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.InnerField; +import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.ResultsExtractor; -import org.springframework.data.elasticsearch.core.facet.ArticleEntity; -import org.springframework.data.elasticsearch.core.facet.ArticleEntityBuilder; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; -import static org.elasticsearch.search.aggregations.AggregationBuilders.terms; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; /** * @author Rizwan Idrees * @author Mohsin Husen * @author Jonathan Yan * @author Artur Konczak + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-test.xml") @@ -60,20 +65,27 @@ public class ElasticsearchTemplateAggregationTests { public static final int YEAR_2002 = 2002; public static final int YEAR_2001 = 2001; public static final int YEAR_2000 = 2000; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + public static final String INDEX_NAME = "test-index-articles-core-aggregation"; + + @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { - elasticsearchTemplate.deleteIndex(ArticleEntity.class); - elasticsearchTemplate.createIndex(ArticleEntity.class); - elasticsearchTemplate.putMapping(ArticleEntity.class); - elasticsearchTemplate.refresh(ArticleEntity.class); - IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").subject("computing").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex(); - IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").subject("computing").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex(); - IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").subject("computing").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex(); - IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").subject("accounting").addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex(); + IndexInitializer.init(elasticsearchTemplate, ArticleEntity.class); + + IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").subject("computing") + .addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10) + .buildIndex(); + IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").subject("computing") + .addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20) + .buildIndex(); + IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").subject("computing") + .addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000) + .score(30).buildIndex(); + IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").subject("accounting") + .addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000) + .score(40).buildIndex(); elasticsearchTemplate.index(article1); elasticsearchTemplate.index(article2); @@ -82,14 +94,21 @@ public class ElasticsearchTemplateAggregationTests { elasticsearchTemplate.refresh(ArticleEntity.class); } + @After + public void after() { + + elasticsearchTemplate.deleteIndex(ArticleEntity.class); + } + @Test public void shouldReturnAggregatedResponseForGivenSearchQuery() { + // given - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchAllQuery()) - .withSearchType(SearchType.DEFAULT) - .withIndices("test-index-articles").withTypes("article") - .addAggregation(terms("subjects").field("subject")) + SearchQuery searchQuery = new NativeSearchQueryBuilder() // + .withQuery(matchAllQuery()) // + .withSearchType(SearchType.DEFAULT) // + .withIndices(INDEX_NAME).withTypes("article") // + .addAggregation(terms("subjects").field("subject")) // .build(); // when Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor() { @@ -99,9 +118,139 @@ public class ElasticsearchTemplateAggregationTests { } }); // then - assertThat(aggregations, is(notNullValue())); - assertThat(aggregations.asMap().get("subjects"), is(notNullValue())); + assertThat(aggregations).isNotNull(); + assertThat(aggregations.asMap().get("subjects")).isNotNull(); } + + /** + * Simple type to test facets + * + * @author Artur Konczak + * @author Mohsin Husen + */ + @Document(indexName = "test-index-articles-core-aggregation", type = "article", shards = 1, replicas = 0, refreshInterval = "-1") + static class ArticleEntity { + + @Id private String id; + private String title; + @Field(type = Text, fielddata = true) private String subject; + + @MultiField(mainField = @Field(type = Text), + otherFields = { + @InnerField(suffix = "untouched", type = Text, store = true, fielddata = true, analyzer = "keyword"), + @InnerField(suffix = "sort", type = Text, store = true, + analyzer = "keyword") }) private List authors = new ArrayList<>(); + + @Field(type = Integer, store = true) private List publishedYears = new ArrayList<>(); + + private int score; + + private ArticleEntity() { + + } + + public ArticleEntity(String id) { + this.id = id; + } + + public void setId(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public List getPublishedYears() { + return publishedYears; + } + + public void setPublishedYears(List publishedYears) { + this.publishedYears = publishedYears; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + } + + /** + * Simple type to test facets + * + * @author Artur Konczak + * @author Mohsin Husen + */ + static class ArticleEntityBuilder { + + private ArticleEntity result; + + public ArticleEntityBuilder(String id) { + result = new ArticleEntity(id); + } + + public ArticleEntityBuilder title(String title) { + result.setTitle(title); + return this; + } + + public ArticleEntityBuilder subject(String subject) { + result.setSubject(subject); + return this; + } + + public ArticleEntityBuilder addAuthor(String author) { + result.getAuthors().add(author); + return this; + } + + public ArticleEntityBuilder addPublishedYear(Integer year) { + result.getPublishedYears().add(year); + return this; + } + + public ArticleEntityBuilder score(int score) { + result.setScore(score); + return this; + } + + public ArticleEntity build() { + return result; + } + + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } + } + } - - diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/AnnotatedCompletionEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/AnnotatedCompletionEntity.java deleted file mode 100644 index ced246f2f..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/AnnotatedCompletionEntity.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.springframework.data.elasticsearch.core.completion; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.CompletionField; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * @author Mewes Kochheim - */ -@Document(indexName = "test-index-annotated-completion", type = "annotated-completion-type", shards = 1, replicas = 0, refreshInterval = "-1") -public class AnnotatedCompletionEntity { - - @Id - private String id; - private String name; - - @CompletionField(maxInputLength = 100) - private Completion suggest; - - private AnnotatedCompletionEntity() { - } - - public AnnotatedCompletionEntity(String id) { - this.id = id; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Completion getSuggest() { - return suggest; - } - - public void setSuggest(Completion suggest) { - this.suggest = suggest; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/AnnotatedCompletionEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/AnnotatedCompletionEntityBuilder.java deleted file mode 100644 index 93c1152b7..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/AnnotatedCompletionEntityBuilder.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2013-2019 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.completion; - -import org.springframework.data.elasticsearch.core.query.IndexQuery; - -/** - * @author Franck Marchand - * @author Mohsin Husen - * @author Mewes Kochheim - */ -public class AnnotatedCompletionEntityBuilder { - - private AnnotatedCompletionEntity result; - - public AnnotatedCompletionEntityBuilder(String id) { - result = new AnnotatedCompletionEntity(id); - } - - public AnnotatedCompletionEntityBuilder name(String name) { - result.setName(name); - return this; - } - - public AnnotatedCompletionEntityBuilder suggest(String[] input) { - return suggest(input, null); - } - - public AnnotatedCompletionEntityBuilder suggest(String[] input, Integer weight) { - Completion suggest = new Completion(input); - suggest.setWeight(weight); - result.setSuggest(suggest); - return this; - } - - public AnnotatedCompletionEntity build() { - return result; - } - - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionAnnotatedEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionAnnotatedEntity.java deleted file mode 100644 index 897db65da..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionAnnotatedEntity.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.springframework.data.elasticsearch.core.completion; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.CompletionField; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * @author Franck Marchand - * @author Mohsin Husen - * @author Mewes Kochheim - */ -@Document(indexName = "test-index-completion-annotated", type = "completion-annotation-type", shards = 1, replicas = 0, refreshInterval = "-1") -public class CompletionAnnotatedEntity { - - @Id - private String id; - private String name; - - @CompletionField - private Completion suggest; - - private CompletionAnnotatedEntity() { - } - - public CompletionAnnotatedEntity(String id) { - this.id = id; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Completion getSuggest() { - return suggest; - } - - public void setSuggest(Completion suggest) { - this.suggest = suggest; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntity.java deleted file mode 100644 index ed67d6bcb..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntity.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.springframework.data.elasticsearch.core.completion; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.CompletionField; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * @author Mewes Kochheim - */ -@Document(indexName = "test-index-completion", type = "completion-type", shards = 1, replicas = 0, refreshInterval = "-1") -public class CompletionEntity { - - @Id - private String id; - private String name; - - @CompletionField(maxInputLength = 100) - private Completion suggest; - - private CompletionEntity() { - } - - public CompletionEntity(String id) { - this.id = id; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Completion getSuggest() { - return suggest; - } - - public void setSuggest(Completion suggest) { - this.suggest = suggest; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntityAnnotatedBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntityAnnotatedBuilder.java deleted file mode 100644 index 2ff474095..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntityAnnotatedBuilder.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2013-2019 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.completion; - -import org.springframework.data.elasticsearch.core.query.IndexQuery; - -/** - * @author Franck Marchand - * @author Mohsin Husen - * @author Mewes Kochheim - */ -public class CompletionEntityAnnotatedBuilder { - - private CompletionAnnotatedEntity result; - - public CompletionEntityAnnotatedBuilder(String id) { - result = new CompletionAnnotatedEntity(id); - } - - public CompletionEntityAnnotatedBuilder name(String name) { - result.setName(name); - return this; - } - - public CompletionEntityAnnotatedBuilder suggest(String[] input) { - return suggest(input, null); - } - - public CompletionEntityAnnotatedBuilder suggest(String[] input, Integer weight) { - Completion suggest = new Completion(input); - if (weight != null) { - suggest.setWeight(weight); - } - result.setSuggest(suggest); - return this; - } - - public CompletionAnnotatedEntity build() { - return result; - } - - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntityBuilder.java deleted file mode 100644 index 1785d9cbb..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/CompletionEntityBuilder.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2013-2019 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.completion; - -import org.springframework.data.elasticsearch.core.query.IndexQuery; - -/** - * @author Mewes Kochheim - */ -public class CompletionEntityBuilder { - - private CompletionEntity result; - - public CompletionEntityBuilder(String id) { - result = new CompletionEntity(id); - } - - public CompletionEntityBuilder name(String name) { - result.setName(name); - return this; - } - - public CompletionEntityBuilder suggest(String[] input) { - return suggest(input, null); - } - - public CompletionEntityBuilder suggest(String[] input, Integer weight) { - Completion suggest = new Completion(input); - suggest.setWeight(weight); - - result.setSuggest(suggest); - return this; - } - - public CompletionEntity build() { - return result; - } - - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/ContextCompletionEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/ContextCompletionEntity.java deleted file mode 100644 index dd5121fd3..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/ContextCompletionEntity.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.springframework.data.elasticsearch.core.completion; - -import org.elasticsearch.search.suggest.completion.context.ContextMapping; -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.CompletionContext; -import org.springframework.data.elasticsearch.annotations.CompletionContextType; -import org.springframework.data.elasticsearch.annotations.CompletionField; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * @author Mewes Kochheim - * @author Robert Gruendler - */ -@Document(indexName = "test-index-context-completion", type = "context-completion-type", shards = 1, replicas = 0, refreshInterval = "-1") -public class ContextCompletionEntity { - - public static final String LANGUAGE_CATEGORY = "language"; - @Id - private String id; - private String name; - - @CompletionField(maxInputLength = 100, contexts = { - @CompletionContext(name = LANGUAGE_CATEGORY, type = ContextMapping.Type.CATEGORY) - }) - private Completion suggest; - - private ContextCompletionEntity() { - } - - public ContextCompletionEntity(String id) { - this.id = id; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Completion getSuggest() { - return suggest; - } - - public void setSuggest(Completion suggest) { - this.suggest = suggest; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/ContextCompletionEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/ContextCompletionEntityBuilder.java deleted file mode 100644 index cf966df87..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/ContextCompletionEntityBuilder.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2013-2019 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.completion; - -import org.springframework.data.elasticsearch.core.query.IndexQuery; - -import java.util.List; -import java.util.Map; - -/** - * @author Robert Gruendler - */ -public class ContextCompletionEntityBuilder { - - private ContextCompletionEntity result; - - public ContextCompletionEntityBuilder(String id) { - result = new ContextCompletionEntity(id); - } - - public ContextCompletionEntityBuilder name(String name) { - result.setName(name); - return this; - } - - public ContextCompletionEntityBuilder suggest(String[] input, Map> contexts) { - Completion suggest = new Completion(input); - suggest.setContexts(contexts); - - result.setSuggest(suggest); - return this; - } - - public ContextCompletionEntity build() { - return result; - } - - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionTests.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionTests.java index 0a55b8777..fd1b78556 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionTests.java @@ -15,9 +15,7 @@ */ package org.springframework.data.elasticsearch.core.completion; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.ArrayList; import java.util.List; @@ -28,84 +26,85 @@ import org.elasticsearch.search.suggest.SuggestBuilder; import org.elasticsearch.search.suggest.SuggestBuilders; import org.elasticsearch.search.suggest.SuggestionBuilder; import org.elasticsearch.search.suggest.completion.CompletionSuggestion; -import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.CompletionField; +import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.IndexQuery; -import org.springframework.data.elasticsearch.entities.NonDocumentEntity; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.ArrayList; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; - /** * @author Rizwan Idrees * @author Mohsin Husen * @author Franck Marchand * @author Artur Konczak * @author Mewes Kochheim + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateCompletionTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired private ElasticsearchTemplate elasticsearchTemplate; private void loadCompletionObjectEntities() { - elasticsearchTemplate.deleteIndex(CompletionEntity.class); - elasticsearchTemplate.createIndex(CompletionEntity.class); - elasticsearchTemplate.refresh(CompletionEntity.class); - elasticsearchTemplate.putMapping(CompletionEntity.class); + + IndexInitializer.init(elasticsearchTemplate, CompletionEntity.class); List indexQueries = new ArrayList<>(); - indexQueries.add(new CompletionEntityBuilder("1").name("Rizwan Idrees").suggest(new String[]{"Rizwan Idrees"}).buildIndex()); - indexQueries.add(new CompletionEntityBuilder("2").name("Franck Marchand").suggest(new String[]{"Franck", "Marchand"}).buildIndex()); - indexQueries.add(new CompletionEntityBuilder("3").name("Mohsin Husen").suggest(new String[]{"Mohsin", "Husen"}).buildIndex()); - indexQueries.add(new CompletionEntityBuilder("4").name("Artur Konczak").suggest(new String[]{"Artur", "Konczak"}).buildIndex()); + indexQueries.add( + new CompletionEntityBuilder("1").name("Rizwan Idrees").suggest(new String[] { "Rizwan Idrees" }).buildIndex()); + indexQueries.add(new CompletionEntityBuilder("2").name("Franck Marchand") + .suggest(new String[] { "Franck", "Marchand" }).buildIndex()); + indexQueries.add( + new CompletionEntityBuilder("3").name("Mohsin Husen").suggest(new String[] { "Mohsin", "Husen" }).buildIndex()); + indexQueries.add(new CompletionEntityBuilder("4").name("Artur Konczak").suggest(new String[] { "Artur", "Konczak" }) + .buildIndex()); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(CompletionEntity.class); } private void loadAnnotatedCompletionObjectEntities() { - elasticsearchTemplate.deleteIndex(AnnotatedCompletionEntity.class); - elasticsearchTemplate.createIndex(AnnotatedCompletionEntity.class); - elasticsearchTemplate.refresh(AnnotatedCompletionEntity.class); - elasticsearchTemplate.putMapping(AnnotatedCompletionEntity.class); + + IndexInitializer.init(elasticsearchTemplate, AnnotatedCompletionEntity.class); NonDocumentEntity nonDocumentEntity = new NonDocumentEntity(); nonDocumentEntity.setSomeField1("foo"); nonDocumentEntity.setSomeField2("bar"); List indexQueries = new ArrayList<>(); - indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Franck Marchand").suggest(new String[]{"Franck", "Marchand"}).buildIndex()); - indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mohsin Husen").suggest(new String[]{"Mohsin", "Husen"}).buildIndex()); - indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Rizwan Idrees").suggest(new String[]{"Rizwan", "Idrees"}).buildIndex()); - indexQueries.add(new AnnotatedCompletionEntityBuilder("4").name("Artur Konczak").suggest(new String[]{"Artur", "Konczak"}).buildIndex()); + indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Franck Marchand") + .suggest(new String[] { "Franck", "Marchand" }).buildIndex()); + indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mohsin Husen") + .suggest(new String[] { "Mohsin", "Husen" }).buildIndex()); + indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Rizwan Idrees") + .suggest(new String[] { "Rizwan", "Idrees" }).buildIndex()); + indexQueries.add(new AnnotatedCompletionEntityBuilder("4").name("Artur Konczak") + .suggest(new String[] { "Artur", "Konczak" }).buildIndex()); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(AnnotatedCompletionEntity.class); } private void loadAnnotatedCompletionObjectEntitiesWithWeights() { - elasticsearchTemplate.deleteIndex(AnnotatedCompletionEntity.class); - elasticsearchTemplate.createIndex(AnnotatedCompletionEntity.class); - elasticsearchTemplate.putMapping(AnnotatedCompletionEntity.class); - elasticsearchTemplate.refresh(AnnotatedCompletionEntity.class); + + IndexInitializer.init(elasticsearchTemplate, AnnotatedCompletionEntity.class); List indexQueries = new ArrayList<>(); - indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Mewes Kochheim1").suggest(new String[]{"Mewes Kochheim1"},4).buildIndex()); - indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mewes Kochheim2").suggest(new String[]{"Mewes Kochheim2"}, 1).buildIndex()); - indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Mewes Kochheim3").suggest(new String[]{"Mewes Kochheim3"}, 2).buildIndex()); - indexQueries.add(new AnnotatedCompletionEntityBuilder("4").name("Mewes Kochheim4").suggest(new String[]{"Mewes Kochheim4"}, Integer.MAX_VALUE).buildIndex()); + indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Mewes Kochheim1") + .suggest(new String[] { "Mewes Kochheim1" }, 4).buildIndex()); + indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mewes Kochheim2") + .suggest(new String[] { "Mewes Kochheim2" }, 1).buildIndex()); + indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Mewes Kochheim3") + .suggest(new String[] { "Mewes Kochheim3" }, 2).buildIndex()); + indexQueries.add(new AnnotatedCompletionEntityBuilder("4").name("Mewes Kochheim4") + .suggest(new String[] { "Mewes Kochheim4" }, Integer.MAX_VALUE).buildIndex()); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(AnnotatedCompletionEntity.class); @@ -113,74 +112,286 @@ public class ElasticsearchTemplateCompletionTests { @Test public void shouldPutMappingForGivenEntity() throws Exception { - //given + + // given Class entity = CompletionEntity.class; elasticsearchTemplate.createIndex(entity); - //when - assertThat(elasticsearchTemplate.putMapping(entity), is(true)); + // when + assertThat(elasticsearchTemplate.putMapping(entity)).isTrue(); } @Test public void shouldFindSuggestionsForGivenCriteriaQueryUsingCompletionEntity() { - //given + + // given loadCompletionObjectEntities(); - SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO); + SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", + Fuzziness.AUTO); - //when - final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest",completionSuggestionFuzzyBuilder), CompletionEntity.class); + // when + final SearchResponse suggestResponse = elasticsearchTemplate.suggest( + new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), CompletionEntity.class); CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest"); List options = completionSuggestion.getEntries().get(0).getOptions(); - //then - assertThat(options.size(), is(2)); - assertThat(options.get(0).getText().string(), isOneOf("Marchand", "Mohsin")); - assertThat(options.get(1).getText().string(), isOneOf("Marchand", "Mohsin")); + // then + assertThat(options).hasSize(2); + assertThat(options.get(0).getText().string()).isIn("Marchand", "Mohsin"); + assertThat(options.get(1).getText().string()).isIn("Marchand", "Mohsin"); } @Test public void shouldFindSuggestionsForGivenCriteriaQueryUsingAnnotatedCompletionEntity() { - //given - loadAnnotatedCompletionObjectEntities(); - SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO); - //when - final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), CompletionEntity.class); + // given + loadAnnotatedCompletionObjectEntities(); + SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", + Fuzziness.AUTO); + + // when + final SearchResponse suggestResponse = elasticsearchTemplate.suggest( + new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), CompletionEntity.class); CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest"); List options = completionSuggestion.getEntries().get(0).getOptions(); - //then - assertThat(options.size(), is(2)); - assertThat(options.get(0).getText().string(), isOneOf("Marchand", "Mohsin")); - assertThat(options.get(1).getText().string(), isOneOf("Marchand", "Mohsin")); + // then + assertThat(options).hasSize(2); + assertThat(options.get(0).getText().string()).isIn("Marchand", "Mohsin"); + assertThat(options.get(1).getText().string()).isIn("Marchand", "Mohsin"); } @Test public void shouldFindSuggestionsWithWeightsForGivenCriteriaQueryUsingAnnotatedCompletionEntity() { - //given - loadAnnotatedCompletionObjectEntitiesWithWeights(); - SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO); - //when - final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest",completionSuggestionFuzzyBuilder), AnnotatedCompletionEntity.class); + // given + loadAnnotatedCompletionObjectEntitiesWithWeights(); + SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", + Fuzziness.AUTO); + + // when + final SearchResponse suggestResponse = elasticsearchTemplate.suggest( + new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), + AnnotatedCompletionEntity.class); CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest"); List options = completionSuggestion.getEntries().get(0).getOptions(); - //then - assertThat(options.size(), is(4)); + // then + assertThat(options).hasSize(4); for (CompletionSuggestion.Entry.Option option : options) { - if (option.getText().string().equals("Mewes Kochheim1")) { - assertEquals(4, option.getScore(), 0); - } else if (option.getText().string().equals("Mewes Kochheim2")) { - assertEquals(1, option.getScore(), 0); - } else if (option.getText().string().equals("Mewes Kochheim3")) { - assertEquals(2, option.getScore(), 0); - } else if (option.getText().string().equals("Mewes Kochheim4")) { - assertEquals(Integer.MAX_VALUE, option.getScore(), 0); - } else { - fail("Unexpected option"); + switch (option.getText().string()) { + case "Mewes Kochheim1": + assertThat(option.getScore()).isEqualTo(4); + break; + case "Mewes Kochheim2": + assertThat(option.getScore()).isEqualTo(1); + break; + case "Mewes Kochheim3": + assertThat(option.getScore()).isEqualTo(2); + break; + case "Mewes Kochheim4": + assertThat(option.getScore()).isEqualTo(Integer.MAX_VALUE); + break; + default: + fail("Unexpected option"); + break; } } } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class NonDocumentEntity { + + @Id private String someId; + private String someField1; + private String someField2; + + public String getSomeField1() { + return someField1; + } + + public void setSomeField1(String someField1) { + this.someField1 = someField1; + } + + public String getSomeField2() { + return someField2; + } + + public void setSomeField2(String someField2) { + this.someField2 = someField2; + } + } + + /** + * @author Mewes Kochheim + */ + @Document(indexName = "test-index-core-completion", type = "completion-type", shards = 1, replicas = 0, + refreshInterval = "-1") + static class CompletionEntity { + + @Id private String id; + + private String name; + + @CompletionField(maxInputLength = 100) private Completion suggest; + + private CompletionEntity() {} + + public CompletionEntity(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Completion getSuggest() { + return suggest; + } + + public void setSuggest(Completion suggest) { + this.suggest = suggest; + } + } + + /** + * @author Mewes Kochheim + */ + static class CompletionEntityBuilder { + + private CompletionEntity result; + + public CompletionEntityBuilder(String id) { + result = new CompletionEntity(id); + } + + public CompletionEntityBuilder name(String name) { + result.setName(name); + return this; + } + + public CompletionEntityBuilder suggest(String[] input) { + return suggest(input, null); + } + + public CompletionEntityBuilder suggest(String[] input, Integer weight) { + Completion suggest = new Completion(input); + suggest.setWeight(weight); + + result.setSuggest(suggest); + return this; + } + + public CompletionEntity build() { + return result; + } + + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } + } + + /** + * @author Mewes Kochheim + */ + @Document(indexName = "test-index-annotated-completion", type = "annotated-completion-type", shards = 1, replicas = 0, + refreshInterval = "-1") + static class AnnotatedCompletionEntity { + + @Id private String id; + private String name; + + @CompletionField(maxInputLength = 100) private Completion suggest; + + private AnnotatedCompletionEntity() {} + + public AnnotatedCompletionEntity(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Completion getSuggest() { + return suggest; + } + + public void setSuggest(Completion suggest) { + this.suggest = suggest; + } + } + + /** + * @author Franck Marchand + * @author Mohsin Husen + * @author Mewes Kochheim + */ + static class AnnotatedCompletionEntityBuilder { + + private AnnotatedCompletionEntity result; + + public AnnotatedCompletionEntityBuilder(String id) { + result = new AnnotatedCompletionEntity(id); + } + + public AnnotatedCompletionEntityBuilder name(String name) { + result.setName(name); + return this; + } + + public AnnotatedCompletionEntityBuilder suggest(String[] input) { + return suggest(input, null); + } + + public AnnotatedCompletionEntityBuilder suggest(String[] input, Integer weight) { + Completion suggest = new Completion(input); + suggest.setWeight(weight); + result.setSuggest(suggest); + return this; + } + + public AnnotatedCompletionEntity build() { + return result; + } + + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionWithContextsTests.java b/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionWithContextsTests.java index a79a15daa..42f8f5930 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionWithContextsTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/completion/ElasticsearchTemplateCompletionWithContextsTests.java @@ -15,6 +15,14 @@ */ package org.springframework.data.elasticsearch.core.completion; +import static org.assertj.core.api.Assertions.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.xcontent.ToXContent; @@ -24,40 +32,33 @@ import org.elasticsearch.search.suggest.SuggestionBuilder; import org.elasticsearch.search.suggest.completion.CompletionSuggestion; import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder; import org.elasticsearch.search.suggest.completion.context.CategoryQueryContext; +import org.elasticsearch.search.suggest.completion.context.ContextMapping; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.CompletionContext; +import org.springframework.data.elasticsearch.annotations.CompletionField; +import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.IndexQuery; -import org.springframework.data.elasticsearch.entities.NonDocumentEntity; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - /** * @author Robert Gruendler + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateCompletionWithContextsTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired private ElasticsearchTemplate elasticsearchTemplate; private void loadContextCompletionObjectEntities() { - elasticsearchTemplate.deleteIndex(ContextCompletionEntity.class); - elasticsearchTemplate.createIndex(ContextCompletionEntity.class); - elasticsearchTemplate.refresh(ContextCompletionEntity.class); - elasticsearchTemplate.putMapping(ContextCompletionEntity.class); + + IndexInitializer.init(elasticsearchTemplate, ContextCompletionEntity.class); NonDocumentEntity nonDocumentEntity = new NonDocumentEntity(); nonDocumentEntity.setSomeField1("foo"); @@ -67,19 +68,23 @@ public class ElasticsearchTemplateCompletionWithContextsTests { Map> context1 = new HashMap<>(); context1.put(ContextCompletionEntity.LANGUAGE_CATEGORY, Arrays.asList("java", "elastic")); - indexQueries.add(new ContextCompletionEntityBuilder("1").name("Rizwan Idrees").suggest(new String[]{"Rizwan Idrees"}, context1).buildIndex()); + indexQueries.add(new ContextCompletionEntityBuilder("1").name("Rizwan Idrees") + .suggest(new String[] { "Rizwan Idrees" }, context1).buildIndex()); Map> context2 = new HashMap<>(); context2.put(ContextCompletionEntity.LANGUAGE_CATEGORY, Arrays.asList("kotlin", "mongo")); - indexQueries.add(new ContextCompletionEntityBuilder("2").name("Franck Marchand").suggest(new String[]{"Franck", "Marchand"}, context2).buildIndex()); + indexQueries.add(new ContextCompletionEntityBuilder("2").name("Franck Marchand") + .suggest(new String[] { "Franck", "Marchand" }, context2).buildIndex()); Map> context3 = new HashMap<>(); context3.put(ContextCompletionEntity.LANGUAGE_CATEGORY, Arrays.asList("kotlin", "elastic")); - indexQueries.add(new ContextCompletionEntityBuilder("3").name("Mohsin Husen").suggest(new String[]{"Mohsin", "Husen"}, context3).buildIndex()); + indexQueries.add(new ContextCompletionEntityBuilder("3").name("Mohsin Husen") + .suggest(new String[] { "Mohsin", "Husen" }, context3).buildIndex()); Map> context4 = new HashMap<>(); context4.put(ContextCompletionEntity.LANGUAGE_CATEGORY, Arrays.asList("java", "kotlin", "redis")); - indexQueries.add(new ContextCompletionEntityBuilder("4").name("Artur Konczak").suggest(new String[]{"Artur", "Konczak"}, context4).buildIndex()); + indexQueries.add(new ContextCompletionEntityBuilder("4").name("Artur Konczak") + .suggest(new String[] { "Artur", "Konczak" }, context4).buildIndex()); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(ContextCompletionEntity.class); @@ -87,19 +92,22 @@ public class ElasticsearchTemplateCompletionWithContextsTests { @Test public void shouldPutMappingForGivenEntity() throws Exception { - //given - Class entity = ContextCompletionEntity.class; + + // given + Class entity = ContextCompletionEntity.class; elasticsearchTemplate.createIndex(entity); - //when - assertThat(elasticsearchTemplate.putMapping(entity), is(true)); + // when + assertThat(elasticsearchTemplate.putMapping(entity)).isTrue(); } @Test // DATAES-536 public void shouldFindSuggestionsForGivenCriteriaQueryUsingContextCompletionEntityOfMongo() { - //given + + // given loadContextCompletionObjectEntities(); - SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO); + SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", + Fuzziness.AUTO); Map> contextMap = new HashMap<>(); List contexts = new ArrayList<>(1); @@ -112,22 +120,26 @@ public class ElasticsearchTemplateCompletionWithContextsTests { ((CompletionSuggestionBuilder) completionSuggestionFuzzyBuilder).contexts(contextMap); - //when - final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), ContextCompletionEntity.class); - assertNotNull(suggestResponse.getSuggest()); + // when + final SearchResponse suggestResponse = elasticsearchTemplate.suggest( + new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), + ContextCompletionEntity.class); + assertThat(suggestResponse.getSuggest()).isNotNull(); CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest"); List options = completionSuggestion.getEntries().get(0).getOptions(); - //then - assertThat(options.size(), is(1)); - assertThat(options.get(0).getText().string(), isOneOf("Marchand")); + // then + assertThat(options).hasSize(1); + assertThat(options.get(0).getText().string()).isEqualTo("Marchand"); } @Test // DATAES-536 public void shouldFindSuggestionsForGivenCriteriaQueryUsingContextCompletionEntityOfElastic() { - //given + + // given loadContextCompletionObjectEntities(); - SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO); + SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", + Fuzziness.AUTO); Map> contextMap = new HashMap<>(); List contexts = new ArrayList<>(1); @@ -140,22 +152,26 @@ public class ElasticsearchTemplateCompletionWithContextsTests { ((CompletionSuggestionBuilder) completionSuggestionFuzzyBuilder).contexts(contextMap); - //when - final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), ContextCompletionEntity.class); - assertNotNull(suggestResponse.getSuggest()); + // when + final SearchResponse suggestResponse = elasticsearchTemplate.suggest( + new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), + ContextCompletionEntity.class); + assertThat(suggestResponse.getSuggest()).isNotNull(); CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest"); List options = completionSuggestion.getEntries().get(0).getOptions(); - //then - assertThat(options.size(), is(1)); - assertThat(options.get(0).getText().string(), isOneOf( "Mohsin")); + // then + assertThat(options).hasSize(1); + assertThat(options.get(0).getText().string()).isEqualTo("Mohsin"); } @Test // DATAES-536 public void shouldFindSuggestionsForGivenCriteriaQueryUsingContextCompletionEntityOfKotlin() { - //given + + // given loadContextCompletionObjectEntities(); - SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO); + SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", + Fuzziness.AUTO); Map> contextMap = new HashMap<>(); List contexts = new ArrayList<>(1); @@ -168,15 +184,127 @@ public class ElasticsearchTemplateCompletionWithContextsTests { ((CompletionSuggestionBuilder) completionSuggestionFuzzyBuilder).contexts(contextMap); - //when - final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), ContextCompletionEntity.class); - assertNotNull(suggestResponse.getSuggest()); + // when + final SearchResponse suggestResponse = elasticsearchTemplate.suggest( + new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), + ContextCompletionEntity.class); + assertThat(suggestResponse.getSuggest()).isNotNull(); CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest"); List options = completionSuggestion.getEntries().get(0).getOptions(); - //then - assertThat(options.size(), is(2)); - assertThat(options.get(0).getText().string(), isOneOf("Marchand", "Mohsin")); - assertThat(options.get(1).getText().string(), isOneOf("Marchand", "Mohsin")); + // then + assertThat(options).hasSize(2); + assertThat(options.get(0).getText().string()).isIn("Marchand", "Mohsin"); + assertThat(options.get(1).getText().string()).isIn("Marchand", "Mohsin"); } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class NonDocumentEntity { + + @Id private String someId; + private String someField1; + private String someField2; + + public String getSomeField1() { + return someField1; + } + + public void setSomeField1(String someField1) { + this.someField1 = someField1; + } + + public String getSomeField2() { + return someField2; + } + + public void setSomeField2(String someField2) { + this.someField2 = someField2; + } + } + + /** + * @author Mewes Kochheim + * @author Robert Gruendler + */ + @Document(indexName = "test-index-context-completion", type = "context-completion-type", shards = 1, replicas = 0, + refreshInterval = "-1") + static class ContextCompletionEntity { + + public static final String LANGUAGE_CATEGORY = "language"; + @Id private String id; + private String name; + + @CompletionField(maxInputLength = 100, contexts = { + @CompletionContext(name = LANGUAGE_CATEGORY, type = ContextMapping.Type.CATEGORY) }) private Completion suggest; + + private ContextCompletionEntity() {} + + public ContextCompletionEntity(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Completion getSuggest() { + return suggest; + } + + public void setSuggest(Completion suggest) { + this.suggest = suggest; + } + } + + /** + * @author Robert Gruendler + */ + static class ContextCompletionEntityBuilder { + + private ContextCompletionEntity result; + + public ContextCompletionEntityBuilder(String id) { + result = new ContextCompletionEntity(id); + } + + public ContextCompletionEntityBuilder name(String name) { + result.setName(name); + return this; + } + + public ContextCompletionEntityBuilder suggest(String[] input, Map> contexts) { + Completion suggest = new Completion(input); + suggest.setContexts(contexts); + + result.setSuggest(suggest); + return this; + } + + public ContextCompletionEntity build() { + return result; + } + + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverterTests.java b/src/test/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverterTests.java index b00b5ca2d..f3984e449 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverterTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverterTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.elasticsearch.core.convert; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.junit.Test; import org.springframework.core.convert.ConversionService; @@ -26,32 +25,40 @@ import org.springframework.data.mapping.context.MappingContext; /** * @author Rizwan Idrees * @author Mohsin Husen + * @author Peter-Josef Meisch */ public class MappingElasticsearchConverterTests { @Test(expected = IllegalArgumentException.class) public void shouldFailToInitializeGivenMappingContextIsNull() { + // given new MappingElasticsearchConverter(null); } @Test public void shouldReturnMappingContextWithWhichItWasInitialized() { + // given MappingContext mappingContext = new SimpleElasticsearchMappingContext(); MappingElasticsearchConverter converter = new MappingElasticsearchConverter(mappingContext); + // then - assertThat(converter.getMappingContext(), is(notNullValue())); - assertThat(converter.getMappingContext(), is(sameInstance(mappingContext))); + assertThat(converter.getMappingContext()).isNotNull(); + assertThat(converter.getMappingContext()).isSameAs(mappingContext); } @Test public void shouldReturnDefaultConversionService() { + // given - MappingElasticsearchConverter converter = new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext()); + MappingElasticsearchConverter converter = new MappingElasticsearchConverter( + new SimpleElasticsearchMappingContext()); + // when ConversionService conversionService = converter.getConversionService(); + // then - assertThat(conversionService, is(notNullValue())); + assertThat(conversionService).isNotNull(); } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntity.java deleted file mode 100644 index a864d4089..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntity.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2014-2019 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.facet; - -import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; -import static org.springframework.data.elasticsearch.annotations.FieldType.Text; - -import java.util.ArrayList; -import java.util.List; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.*; - -/** - * Simple type to test facets - * - * @author Artur Konczak - * @author Mohsin Husen - */ -@Document(indexName = "test-index-articles", type = "article", shards = 1, replicas = 0, refreshInterval = "-1") -public class ArticleEntity { - - @Id - private String id; - private String title; - @Field(type = Text, fielddata = true) - private String subject; - - @MultiField( - mainField = @Field(type = Text), - otherFields = { - @InnerField(suffix = "untouched", type = Text, store = true, fielddata = true, analyzer = "keyword"), - @InnerField(suffix = "sort", type = Text, store = true, analyzer = "keyword") - } - ) - private List authors = new ArrayList<>(); - - @Field(type = Integer, store = true) - private List publishedYears = new ArrayList<>(); - - private int score; - - private ArticleEntity() { - - } - - public ArticleEntity(String id) { - this.id = id; - } - - public void setId(String id) { - this.id = id; - } - - public String getId() { - return id; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getSubject() { - return subject; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public List getAuthors() { - return authors; - } - - public void setAuthors(List authors) { - this.authors = authors; - } - - public List getPublishedYears() { - return publishedYears; - } - - public void setPublishedYears(List publishedYears) { - this.publishedYears = publishedYears; - } - - public int getScore() { - return score; - } - - public void setScore(int score) { - this.score = score; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntityBuilder.java deleted file mode 100644 index 69bcb32b7..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntityBuilder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2014-2019 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.facet; - -import org.springframework.data.elasticsearch.core.query.IndexQuery; - -/** - * Simple type to test facets - * - * @author Artur Konczak - * @author Mohsin Husen - */ -public class ArticleEntityBuilder { - - private ArticleEntity result; - - public ArticleEntityBuilder(String id) { - result = new ArticleEntity(id); - } - - public ArticleEntityBuilder title(String title) { - result.setTitle(title); - return this; - } - - public ArticleEntityBuilder subject(String subject) { - result.setSubject(subject); - return this; - } - - public ArticleEntityBuilder addAuthor(String author) { - result.getAuthors().add(author); - return this; - } - - public ArticleEntityBuilder addPublishedYear(Integer year) { - result.getPublishedYears().add(year); - return this; - } - - public ArticleEntityBuilder score(int score) { - result.setScore(score); - return this; - } - - public ArticleEntity build() { - return result; - } - - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateFacetTests.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateFacetTests.java index cff5909bd..95170a76c 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateFacetTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateFacetTests.java @@ -16,10 +16,22 @@ package org.springframework.data.elasticsearch.core.facet; +import static org.assertj.core.api.Assertions.*; +import static org.elasticsearch.index.query.QueryBuilders.*; + +import java.util.ArrayList; +import java.util.List; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +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.annotations.InnerField; +import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.FacetedPage; import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage; @@ -38,19 +50,17 @@ import org.springframework.data.elasticsearch.core.facet.result.TermResult; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; /** * @author Rizwan Idrees * @author Mohsin Husen * @author Jonathan Yan * @author Artur Konczak + * @author Peter-Josef Meisch */ - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateFacetTests { @@ -63,20 +73,22 @@ public class ElasticsearchTemplateFacetTests { private static final int YEAR_2001 = 2001; private static final int YEAR_2000 = 2000; private static final String PUBLISHED_YEARS = "publishedYears"; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + + @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { - elasticsearchTemplate.deleteIndex(ArticleEntity.class); - elasticsearchTemplate.createIndex(ArticleEntity.class); - elasticsearchTemplate.putMapping(ArticleEntity.class); - elasticsearchTemplate.refresh(ArticleEntity.class); - IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex(); - IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex(); - IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex(); - IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex(); + IndexInitializer.init(elasticsearchTemplate, ArticleEntity.class); + + IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").addAuthor(RIZWAN_IDREES) + .addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex(); + IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").addAuthor(RIZWAN_IDREES) + .addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex(); + IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").addAuthor(RIZWAN_IDREES) + .addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex(); + IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").addAuthor(RIZWAN_IDREES) + .addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex(); elasticsearchTemplate.index(article1); elasticsearchTemplate.index(article2); @@ -90,32 +102,34 @@ public class ElasticsearchTemplateFacetTests { // given String facetName = "fauthors"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").build()).build(); + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").build()).build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(RIZWAN_IDREES)); - assertThat(term.getCount(), is(4l)); + assertThat(term.getTerm()).isEqualTo(RIZWAN_IDREES); + assertThat(term.getCount()).isEqualTo(4); term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(3l)); + assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK); + assertThat(term.getCount()).isEqualTo(3); term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(2l)); + assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN); + assertThat(term.getCount()).isEqualTo(2); term = facet.getTerms().get(3); - assertThat(term.getTerm(), is(JONATHAN_YAN)); - assertThat(term.getCount(), is(1l)); - - assertThat(facet.getTotal(), is(4l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(0l)); + assertThat(term.getTerm()).isEqualTo(JONATHAN_YAN); + assertThat(term.getCount()).isEqualTo(1); + + assertThat(facet.getTotal()).isEqualTo(4); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(0); } @Test @@ -124,56 +138,63 @@ public class ElasticsearchTemplateFacetTests { // given String facetName = "fauthors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").build()).build(); + .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").build()) + .build(); // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(RIZWAN_IDREES)); - assertThat(term.getCount(), is(4l)); + assertThat(term.getTerm()).isEqualTo(RIZWAN_IDREES); + assertThat(term.getCount()).isEqualTo(4); term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(3l)); + assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK); + assertThat(term.getCount()).isEqualTo(3); term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(2l)); - - assertThat(facet.getTotal(), is(4l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(0l)); + assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN); + assertThat(term.getCount()).isEqualTo(2); + + assertThat(facet.getTotal()).isEqualTo(4); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(0); } @Test public void shouldExcludeTermsFromFacetedAuthorsForGivenQuery() { + // given String facetName = "fauthors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").excludeTerms(RIZWAN_IDREES, ARTUR_KONCZAK).build()).build(); + .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched") + .excludeTerms(RIZWAN_IDREES, ARTUR_KONCZAK).build()) + .build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); - assertThat(facet.getTerms().size(), is(2)); + assertThat(facet.getTerms()).hasSize(2); Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(2l)); + assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN); + assertThat(term.getCount()).isEqualTo(2); Term term1 = facet.getTerms().get(1); - assertThat(term1.getTerm(), is(JONATHAN_YAN)); - assertThat(term1.getCount(), is(1l)); - - assertThat(facet.getTotal(), is(2l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(0l)); + assertThat(term1.getTerm()).isEqualTo(JONATHAN_YAN); + assertThat(term1.getCount()).isEqualTo(1); + + assertThat(facet.getTotal()).isEqualTo(2); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(0); } @Test @@ -183,31 +204,33 @@ public class ElasticsearchTemplateFacetTests { String facetName = "fauthors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").ascTerm().build()).build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(3l)); + assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK); + assertThat(term.getCount()).isEqualTo(3); term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(JONATHAN_YAN)); - assertThat(term.getCount(), is(1l)); + assertThat(term.getTerm()).isEqualTo(JONATHAN_YAN); + assertThat(term.getCount()).isEqualTo(1); term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(2l)); + assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN); + assertThat(term.getCount()).isEqualTo(2); term = facet.getTerms().get(3); - assertThat(term.getTerm(), is(RIZWAN_IDREES)); - assertThat(term.getCount(), is(4l)); + assertThat(term.getTerm()).isEqualTo(RIZWAN_IDREES); + assertThat(term.getCount()).isEqualTo(4); - assertThat(facet.getTotal(), is(4l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(0l)); + assertThat(facet.getTotal()).isEqualTo(4); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(0); } @Test @@ -217,31 +240,33 @@ public class ElasticsearchTemplateFacetTests { String facetName = "fauthors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").ascCount().build()).build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(JONATHAN_YAN)); - assertThat(term.getCount(), is(1l)); + assertThat(term.getTerm()).isEqualTo(JONATHAN_YAN); + assertThat(term.getCount()).isEqualTo(1); term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(2l)); + assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN); + assertThat(term.getCount()).isEqualTo(2); term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(3l)); + assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK); + assertThat(term.getCount()).isEqualTo(3); term = facet.getTerms().get(3); - assertThat(term.getTerm(), is(RIZWAN_IDREES)); - assertThat(term.getCount(), is(4l)); - - assertThat(facet.getTotal(), is(4l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(0l)); + assertThat(term.getTerm()).isEqualTo(RIZWAN_IDREES); + assertThat(term.getCount()).isEqualTo(4); + + assertThat(facet.getTotal()).isEqualTo(4); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(0); } @Test @@ -251,29 +276,31 @@ public class ElasticsearchTemplateFacetTests { String facetName = "fyears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new TermFacetRequestBuilder(facetName).fields("publishedYears").descCount().build()).build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); - assertThat(facet.getTerms().size(), is(equalTo(3))); + assertThat(facet.getTerms()).hasSize(3); Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(Long.toString(YEAR_2000))); - assertThat(term.getCount(), is(3l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2000)); + assertThat(term.getCount()).isEqualTo(3); term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(Long.toString(YEAR_2001))); - assertThat(term.getCount(), is(2l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2001)); + assertThat(term.getCount()).isEqualTo(2); term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(Long.toString(YEAR_2002))); - assertThat(term.getCount(), is(1l)); - - assertThat(facet.getTotal(), is(3l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(0l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2002)); + assertThat(term.getCount()).isEqualTo(1); + + assertThat(facet.getTotal()).isEqualTo(3); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(0); } @Test @@ -282,32 +309,35 @@ public class ElasticsearchTemplateFacetTests { // given String facetName = "fyears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("publishedYears").descCount().build()).build(); + .withFacet( + new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("publishedYears").descCount().build()) + .build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); - assertThat(facet.getTerms().size(), is(equalTo(3))); + assertThat(facet.getTerms()).hasSize(3); Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(Long.toString(YEAR_2000))); - assertThat(term.getCount(), is(3l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2000)); + assertThat(term.getCount()).isEqualTo(3); term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(Long.toString(YEAR_2001))); - assertThat(term.getCount(), is(2l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2001)); + assertThat(term.getCount()).isEqualTo(2); term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(Long.toString(YEAR_2002))); - assertThat(term.getCount(), is(1l)); - - assertThat(facet.getTotal(), is(3l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(0l)); - } + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2002)); + assertThat(term.getCount()).isEqualTo(1); + assertThat(facet.getTotal()).isEqualTo(3); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(0); + } @Test(expected = IllegalArgumentException.class) public void shouldThrowExeptionsForMultiFieldFacet() { @@ -315,46 +345,50 @@ public class ElasticsearchTemplateFacetTests { // given String facetName = "fyears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(facetName).fields("publishedYears", "authors.untouched").ascTerm().build()).build(); + .withFacet( + new TermFacetRequestBuilder(facetName).fields("publishedYears", "authors.untouched").ascTerm().build()) + .build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); - assertThat(facet.getTerms().size(), is(equalTo(7))); + assertThat(facet.getTerms()).hasSize(7); Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(Long.toString(YEAR_2000))); - assertThat(term.getCount(), is(3l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2000)); + assertThat(term.getCount()).isEqualTo(3); term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(Long.toString(YEAR_2001))); - assertThat(term.getCount(), is(2l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2001)); + assertThat(term.getCount()).isEqualTo(2); term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(Long.toString(YEAR_2002))); - assertThat(term.getCount(), is(1l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2002)); + assertThat(term.getCount()).isEqualTo(1); term = facet.getTerms().get(3); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(3l)); + assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK); + assertThat(term.getCount()).isEqualTo(3); term = facet.getTerms().get(4); - assertThat(term.getTerm(), is(JONATHAN_YAN)); - assertThat(term.getCount(), is(1l)); + assertThat(term.getTerm()).isEqualTo(JONATHAN_YAN); + assertThat(term.getCount()).isEqualTo(1); term = facet.getTerms().get(5); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(2l)); + assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN); + assertThat(term.getCount()).isEqualTo(2); term = facet.getTerms().get(6); - assertThat(term.getTerm(), is(RIZWAN_IDREES)); - assertThat(term.getCount(), is(4l)); - - assertThat(facet.getTotal(), is(16l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(1l)); + assertThat(term.getTerm()).isEqualTo(RIZWAN_IDREES); + assertThat(term.getCount()).isEqualTo(4); + + assertThat(facet.getTotal()).isEqualTo(16); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(1); } @Test @@ -365,50 +399,50 @@ public class ElasticsearchTemplateFacetTests { String stringFacetName = "fyears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new TermFacetRequestBuilder(numberFacetName).fields("publishedYears").ascTerm().build()) - .withFacet(new TermFacetRequestBuilder(stringFacetName).fields("authors.untouched").ascTerm().build()) - .build(); + .withFacet(new TermFacetRequestBuilder(stringFacetName).fields("authors.untouched").ascTerm().build()).build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult numberFacet = (TermResult) result.getFacet(numberFacetName); - assertThat(numberFacet.getTerms().size(), is(equalTo(3))); + assertThat(numberFacet.getTerms()).hasSize(3); Term numberTerm = numberFacet.getTerms().get(0); - assertThat(numberTerm.getTerm(), is(Long.toString(YEAR_2000))); - assertThat(numberTerm.getCount(), is(3l)); + assertThat(numberTerm.getTerm()).isEqualTo(Long.toString(YEAR_2000)); + assertThat(numberTerm.getCount()).isEqualTo(3); numberTerm = numberFacet.getTerms().get(1); - assertThat(numberTerm.getTerm(), is(Long.toString(YEAR_2001))); - assertThat(numberTerm.getCount(), is(2l)); + assertThat(numberTerm.getTerm()).isEqualTo(Long.toString(YEAR_2001)); + assertThat(numberTerm.getCount()).isEqualTo(2); numberTerm = numberFacet.getTerms().get(2); - assertThat(numberTerm.getTerm(), is(Long.toString(YEAR_2002))); - assertThat(numberTerm.getCount(), is(1l)); + assertThat(numberTerm.getTerm()).isEqualTo(Long.toString(YEAR_2002)); + assertThat(numberTerm.getCount()).isEqualTo(1); TermResult stringFacet = (TermResult) result.getFacet(stringFacetName); Term stringTerm = stringFacet.getTerms().get(0); - assertThat(stringTerm.getTerm(), is(ARTUR_KONCZAK)); - assertThat(stringTerm.getCount(), is(3l)); + assertThat(stringTerm.getTerm()).isEqualTo(ARTUR_KONCZAK); + assertThat(stringTerm.getCount()).isEqualTo(3); stringTerm = stringFacet.getTerms().get(1); - assertThat(stringTerm.getTerm(), is(JONATHAN_YAN)); - assertThat(stringTerm.getCount(), is(1l)); + assertThat(stringTerm.getTerm()).isEqualTo(JONATHAN_YAN); + assertThat(stringTerm.getCount()).isEqualTo(1); stringTerm = stringFacet.getTerms().get(2); - assertThat(stringTerm.getTerm(), is(MOHSIN_HUSEN)); - assertThat(stringTerm.getCount(), is(2l)); + assertThat(stringTerm.getTerm()).isEqualTo(MOHSIN_HUSEN); + assertThat(stringTerm.getCount()).isEqualTo(2); stringTerm = stringFacet.getTerms().get(3); - assertThat(stringTerm.getTerm(), is(RIZWAN_IDREES)); - assertThat(stringTerm.getCount(), is(4l)); - - assertThat(stringFacet.getTotal(), is(4l)); - assertThat(stringFacet.getOther(), is(0l)); - assertThat(stringFacet.getMissing(), is(0l)); - } + assertThat(stringTerm.getTerm()).isEqualTo(RIZWAN_IDREES); + assertThat(stringTerm.getCount()).isEqualTo(4); + assertThat(stringFacet.getTotal()).isEqualTo(4); + assertThat(stringFacet.getOther()).isEqualTo(0); + assertThat(stringFacet.getMissing()).isEqualTo(0); + } @Test(expected = UnsupportedOperationException.class) public void shouldThrowExceptionForNativeFacets() { @@ -417,202 +451,351 @@ public class ElasticsearchTemplateFacetTests { String facetName = "fyears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new NativeFacetRequest()).build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); - assertThat(facet.getTerms().size(), is(equalTo(3))); + assertThat(facet.getTerms()).hasSize(3); Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(Long.toString(YEAR_2000))); - assertThat(term.getCount(), is(3l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2000)); + assertThat(term.getCount()).isEqualTo(3); term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(Long.toString(YEAR_2001))); - assertThat(term.getCount(), is(2l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2001)); + assertThat(term.getCount()).isEqualTo(2); term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(Long.toString(YEAR_2002))); - assertThat(term.getCount(), is(1l)); - - assertThat(facet.getTotal(), is(6l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(1l)); + assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2002)); + assertThat(term.getCount()).isEqualTo(1); + + assertThat(facet.getTotal()).isEqualTo(6); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(1); } @Test public void shouldFilterResultByRegexForGivenQuery() { + // given String facetName = "regex_authors"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").regex("Art.*").build()).build(); + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withFacet( + new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").regex("Art.*").build()) + .build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); - assertThat(facet.getTerms().size(), is(1)); + assertThat(facet.getTerms()).hasSize(1); Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(3l)); + assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK); + assertThat(term.getCount()).isEqualTo(3); - assertThat(facet.getTotal(), is(1l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(0l)); + assertThat(facet.getTotal()).isEqualTo(1); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(0); } @Test public void shouldReturnAllTermsForGivenQuery() { - // given + // given String facetName = "all_authors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").allTerms().build()).build(); + .withFacet( + new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").allTerms().build()) + .build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); TermResult facet = (TermResult) result.getFacet(facetName); - assertThat(facet.getTerms().size(), is(4)); - - assertThat(facet.getTotal(), is(4l)); - assertThat(facet.getOther(), is(0l)); - assertThat(facet.getMissing(), is(0l)); - } + assertThat(facet.getTerms()).hasSize(4); + assertThat(facet.getTotal()).isEqualTo(4); + assertThat(facet.getOther()).isEqualTo(0); + assertThat(facet.getMissing()).isEqualTo(0); + } @Test public void shouldReturnRangeFacetForGivenQuery() { + // given String facetName = "rangeYears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet( - new RangeFacetRequestBuilder(facetName).field(PUBLISHED_YEARS) - .to(YEAR_2000).range(YEAR_2000, YEAR_2002).from(YEAR_2002).build() - ).build(); + .withFacet(new RangeFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).to(YEAR_2000) + .range(YEAR_2000, YEAR_2002).from(YEAR_2002).build()) + .build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); RangeResult facet = (RangeResult) result.getFacet(facetName); - assertThat(facet.getRanges().size(), is(equalTo(3))); + assertThat(facet.getRanges()).hasSize(3); Range range = facet.getRanges().get(0); - assertThat(range.getFrom(), is(Double.NEGATIVE_INFINITY)); - assertThat(range.getTo(), is((double) YEAR_2000)); - assertThat(range.getCount(), is(0L)); - assertThat(range.getTotal(), is(0.0)); + assertThat(range.getFrom()).isEqualTo(Double.NEGATIVE_INFINITY); + assertThat(range.getTo()).isEqualTo((double) YEAR_2000); + assertThat(range.getCount()).isEqualTo(0); + assertThat(range.getTotal()).isEqualTo(0.0); range = facet.getRanges().get(1); - assertThat(range.getFrom(), is((double) YEAR_2000)); - assertThat(range.getTo(), is((double) YEAR_2002)); - assertThat(range.getCount(), is(3L)); - assertThat(range.getTotal(), is(12004.0)); + assertThat(range.getFrom()).isEqualTo((double) YEAR_2000); + assertThat(range.getTo()).isEqualTo((double) YEAR_2002); + assertThat(range.getCount()).isEqualTo(3); + assertThat(range.getTotal()).isEqualTo(12004.0); range = facet.getRanges().get(2); - assertThat(range.getFrom(), is((double) YEAR_2002)); - assertThat(range.getTo(), is(Double.POSITIVE_INFINITY)); - assertThat(range.getCount(), is(1L)); - assertThat(range.getTotal(), is(6003.0)); + assertThat(range.getFrom()).isEqualTo((double) YEAR_2002); + assertThat(range.getTo()).isEqualTo(Double.POSITIVE_INFINITY); + assertThat(range.getCount()).isEqualTo(1); + assertThat(range.getTotal()).isEqualTo(6003.0); } @Test public void shouldReturnKeyValueRangeFacetForStringValuesInGivenQuery() { + // given String facetName = "rangeScoreOverYears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet( - new RangeFacetRequestBuilder(facetName).fields(PUBLISHED_YEARS, "score") - .to(YEAR_2000).range(YEAR_2000, YEAR_2002).from(YEAR_2002).build() - ).build(); + .withFacet(new RangeFacetRequestBuilder(facetName).fields(PUBLISHED_YEARS, "score").to(YEAR_2000) + .range(YEAR_2000, YEAR_2002).from(YEAR_2002).build()) + .build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); RangeResult facet = (RangeResult) result.getFacet(facetName); - assertThat(facet.getRanges().size(), is(equalTo(3))); + assertThat(facet.getRanges()).hasSize(3); Range range = facet.getRanges().get(0); - assertThat(range.getFrom(), is(Double.NEGATIVE_INFINITY)); - assertThat(range.getTo(), is((double) YEAR_2000)); - assertThat(range.getCount(), is(0L)); - assertThat(range.getTotal(), is(0.0)); + assertThat(range.getFrom()).isEqualTo(Double.NEGATIVE_INFINITY); + assertThat(range.getTo()).isEqualTo((double) YEAR_2000); + assertThat(range.getCount()).isEqualTo(0); + assertThat(range.getTotal()).isEqualTo(0.0); range = facet.getRanges().get(1); - assertThat(range.getFrom(), is((double) YEAR_2000)); - assertThat(range.getTo(), is((double) YEAR_2002)); - assertThat(range.getCount(), is(3L)); - assertThat(range.getTotal(), is(90.0)); + assertThat(range.getFrom()).isEqualTo((double) YEAR_2000); + assertThat(range.getTo()).isEqualTo((double) YEAR_2002); + assertThat(range.getCount()).isEqualTo(3); + assertThat(range.getTotal()).isEqualTo(90.0); range = facet.getRanges().get(2); - assertThat(range.getFrom(), is((double) YEAR_2002)); - assertThat(range.getTo(), is(Double.POSITIVE_INFINITY)); - assertThat(range.getCount(), is(1L)); - assertThat(range.getTotal(), is(40.0)); + assertThat(range.getFrom()).isEqualTo((double) YEAR_2002); + assertThat(range.getTo()).isEqualTo(Double.POSITIVE_INFINITY); + assertThat(range.getCount()).isEqualTo(1); + assertThat(range.getTotal()).isEqualTo(40.0); } @Test public void shouldReturnStatisticalFacetForGivenQuery() { + // given String facetName = "statPublishedYear"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new StatisticalFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).build() - ).build(); + .withFacet(new StatisticalFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).build()).build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); StatisticalResult facet = (StatisticalResult) result.getFacet(facetName); - assertThat(facet.getCount(), is(equalTo(6L))); - assertThat(facet.getMax(), is(equalTo(2002.0))); - assertThat(facet.getMin(), is(equalTo(2000.0))); + assertThat(facet.getCount()).isEqualTo(6); + assertThat(facet.getMax()).isEqualTo(2002.0); + assertThat(facet.getMin()).isEqualTo(2000.0); } @Test public void shouldReturnHistogramFacetForGivenQuery() { + // given String facetName = "numberPublicationPerYear"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new HistogramFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).interval(1).build() - ).build(); + .withFacet(new HistogramFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).interval(1).build()).build(); + // when FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + assertThat(result.getNumberOfElements()).isEqualTo(4); HistogramResult facet = (HistogramResult) result.getFacet(facetName); - assertThat(facet.getIntervalUnit().size(), is(equalTo(3))); + assertThat(facet.getIntervalUnit()).hasSize(3); IntervalUnit unit = facet.getIntervalUnit().get(0); - assertThat(unit.getKey(), is(Long.valueOf(YEAR_2000))); - assertThat(unit.getCount(), is(3L)); + assertThat(unit.getKey()).isEqualTo(Long.valueOf(YEAR_2000)); + assertThat(unit.getCount()).isEqualTo(3); unit = facet.getIntervalUnit().get(1); - assertThat(unit.getKey(), is(Long.valueOf(YEAR_2001))); - assertThat(unit.getCount(), is(2L)); + assertThat(unit.getKey()).isEqualTo(Long.valueOf(YEAR_2001)); + assertThat(unit.getCount()).isEqualTo(2); unit = facet.getIntervalUnit().get(2); - assertThat(unit.getKey(), is(Long.valueOf(YEAR_2002))); - assertThat(unit.getCount(), is(1L)); + assertThat(unit.getKey()).isEqualTo(Long.valueOf(YEAR_2002)); + assertThat(unit.getCount()).isEqualTo(1); } @Test - public void shouldNotThrowExceptionForNoFacets() - { + public void shouldNotThrowExceptionForNoFacets() { + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); AggregatedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - assertThat(result.hasFacets(), is(false)); + assertThat(result.hasFacets()).isEqualTo(false); } -} + /** + * Simple type to test facets + * + * @author Artur Konczak + * @author Mohsin Husen + */ + @Document(indexName = "test-index-articles-core-facet", type = "article", shards = 1, replicas = 0, refreshInterval = "-1") + static class ArticleEntity { + + @Id private String id; + private String title; + @Field(type = FieldType.Text, fielddata = true) private String subject; + + @MultiField(mainField = @Field(type = FieldType.Text), + otherFields = { + @InnerField(suffix = "untouched", type = FieldType.Text, store = true, fielddata = true, + analyzer = "keyword"), + @InnerField(suffix = "sort", type = FieldType.Text, store = true, + analyzer = "keyword") }) private List authors = new ArrayList<>(); + + @Field(type = FieldType.Integer, store = true) private List publishedYears = new ArrayList<>(); + + private int score; + + private ArticleEntity() { + + } + + public ArticleEntity(String id) { + this.id = id; + } + + public void setId(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public List getAuthors() { + return authors; + } + + public void setAuthors(List authors) { + this.authors = authors; + } + + public List getPublishedYears() { + return publishedYears; + } + + public void setPublishedYears(List publishedYears) { + this.publishedYears = publishedYears; + } + + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + } + + /** + * Simple type to test facets + * + * @author Artur Konczak + * @author Mohsin Husen + */ + static class ArticleEntityBuilder { + + private ArticleEntity result; + + public ArticleEntityBuilder(String id) { + result = new ArticleEntity(id); + } + + public ArticleEntityBuilder title(String title) { + result.setTitle(title); + return this; + } + + public ArticleEntityBuilder subject(String subject) { + result.setSubject(subject); + return this; + } + + public ArticleEntityBuilder addAuthor(String author) { + result.getAuthors().add(author); + return this; + } + + public ArticleEntityBuilder addPublishedYear(Integer year) { + result.getPublishedYears().add(year); + return this; + } + + public ArticleEntityBuilder score(int score) { + result.setScore(score); + return this; + } + + public ArticleEntity build() { + return result; + } + + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } + } + +} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntity.java deleted file mode 100644 index 88032bacd..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntity.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2014-2019 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.facet; - -import static org.springframework.data.elasticsearch.annotations.FieldType.*; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; - -/** - * Simple type to test facets - * - * @author Artur Konczak - * @author Mohsin Husen - */ - -@Document(indexName = "test-index-log", type = "test-log-type", shards = 1, replicas = 0, refreshInterval = "-1") -public class LogEntity { - - private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); - - @Id - private String id; - - private String action; - - private long sequenceCode; - - @Field(type = Ip) - private String ip; - - @Field(type = Date) - private Date date; - - private LogEntity() { - } - - public LogEntity(String id) { - this.id = id; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getAction() { - return action; - } - - public String toString() { - return new StringBuffer().append("{id:").append(id).append(",action:").append(action).append(",code:").append(sequenceCode).append(",date:").append(format.format(date)).append("}").toString(); - } - - public void setAction(String action) { - this.action = action; - } - - public long getSequenceCode() { - return sequenceCode; - } - - public void setSequenceCode(long sequenceCode) { - this.sequenceCode = sequenceCode; - } - - public String getIp() { - return ip; - } - - public void setIp(String ip) { - this.ip = ip; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntityBuilder.java deleted file mode 100644 index 8be27a0ac..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntityBuilder.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2014-2019 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.facet; - -import java.util.Date; - -import org.springframework.data.elasticsearch.core.query.IndexQuery; - -/** - * Simple type to test facets - * - * @author Artur Konczak - * @author Mohsin Husen - */ - -public class LogEntityBuilder { - - private LogEntity result; - - public LogEntityBuilder(String id) { - result = new LogEntity(id); - } - - public LogEntityBuilder action(String action) { - result.setAction(action); - return this; - } - - public LogEntityBuilder code(long sequenceCode) { - result.setSequenceCode(sequenceCode); - return this; - } - - public LogEntityBuilder date(Date date) { - result.setDate(date); - return this; - } - - public LogEntityBuilder ip(String ip) { - result.setIp(ip); - return this; - } - - public LogEntity build() { - return result; - } - - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntity.java deleted file mode 100644 index 8908f482b..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntity.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2013-2019 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.geo; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * @author Franck Marchand - * @author Mohsin Husen - */ -@Document(indexName = "test-index-author-marker", type = "geo-class-point-type", shards = 1, replicas = 0, refreshInterval = "-1") -public class AuthorMarkerEntity { - - @Id - private String id; - private String name; - - private GeoPoint location; - - private AuthorMarkerEntity() { - } - - public AuthorMarkerEntity(String id) { - this.id = id; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public GeoPoint getLocation() { - return location; - } - - public void setLocation(GeoPoint location) { - this.location = location; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntityBuilder.java deleted file mode 100644 index 1da5ac0bd..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntityBuilder.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2013-2019 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.geo; - -import org.springframework.data.elasticsearch.core.query.IndexQuery; - -/** - * @author Franck Marchand - * @author Mohsin Husen - */ - -public class AuthorMarkerEntityBuilder { - - private AuthorMarkerEntity result; - - public AuthorMarkerEntityBuilder(String id) { - result = new AuthorMarkerEntity(id); - } - - public AuthorMarkerEntityBuilder name(String name) { - result.setName(name); - return this; - } - - public AuthorMarkerEntityBuilder location(double latitude, double longitude) { - result.setLocation(new GeoPoint(latitude, longitude)); - return this; - } - - public AuthorMarkerEntity build() { - return result; - } - - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java b/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java index 097b20a5d..d7be19000 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java @@ -15,55 +15,66 @@ */ package org.springframework.data.elasticsearch.core.geo; +import static org.assertj.core.api.Assertions.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.util.ArrayList; import java.util.List; + import org.elasticsearch.common.geo.GeoHashUtils; import org.elasticsearch.index.query.QueryBuilders; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +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.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.Criteria; import org.springframework.data.elasticsearch.core.query.CriteriaQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.data.geo.Point; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; /** * @author Rizwan Idrees * @author Mohsin Husen * @author Franck Marchand * @author Artur Konczak + * @author Peter-Josef Meisch * - * Basic info: - * latitude - horizontal lines (equator = 0.0, values -90.0 to 90.0) - * longitude - vertical lines (Greenwich = 0.0, values -180 to 180) - * London [lat,lon] = [51.50985,-0.118082] - geohash = gcpvj3448 - * Bouding Box for London = (bbox=-0.489,51.28,0.236,51.686) - * bbox = left,bottom,right,top - * bbox = min Longitude , min Latitude , max Longitude , max Latitude - * + * Basic info: latitude - horizontal lines (equator = 0.0, values -90.0 to 90.0) longitude - + * vertical lines (Greenwich = 0.0, values -180 to 180) London [lat,lon] = [51.50985,-0.118082] - geohash = + * gcpvj3448 Bouding Box for London = (bbox=-0.489,51.28,0.236,51.686) bbox = left,bottom,right,top bbox = min + * Longitude , min Latitude , max Longitude , max Latitude */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateGeoTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + + IndexInitializer.init(elasticsearchTemplate, AuthorMarkerEntity.class); + IndexInitializer.init(elasticsearchTemplate, LocationMarkerEntity.class); + } private void loadClassBaseEntities() { - elasticsearchTemplate.deleteIndex(AuthorMarkerEntity.class); - elasticsearchTemplate.createIndex(AuthorMarkerEntity.class); - elasticsearchTemplate.putMapping(AuthorMarkerEntity.class); - elasticsearchTemplate.refresh(AuthorMarkerEntity.class); List indexQueries = new ArrayList<>(); - indexQueries.add(new AuthorMarkerEntityBuilder("1").name("Franck Marchand").location(45.7806d, 3.0875d).buildIndex()); + indexQueries + .add(new AuthorMarkerEntityBuilder("1").name("Franck Marchand").location(45.7806d, 3.0875d).buildIndex()); indexQueries.add(new AuthorMarkerEntityBuilder("2").name("Mohsin Husen").location(51.5171d, 0.1062d).buildIndex()); indexQueries.add(new AuthorMarkerEntityBuilder("3").name("Rizwan Idrees").location(51.5171d, 0.1062d).buildIndex()); elasticsearchTemplate.bulkIndex(indexQueries); @@ -71,33 +82,29 @@ public class ElasticsearchTemplateGeoTests { } private void loadAnnotationBaseEntities() { - elasticsearchTemplate.deleteIndex(LocationMarkerEntity.class); - elasticsearchTemplate.createIndex(LocationMarkerEntity.class); - elasticsearchTemplate.putMapping(LocationMarkerEntity.class); - elasticsearchTemplate.refresh(LocationMarkerEntity.class); List indexQueries = new ArrayList<>(); - double[] lonLatArray = {0.100000, 51.000000}; + double[] lonLatArray = { 0.100000, 51.000000 }; String latLonString = "51.000000, 0.100000"; String geohash = "u10j46mkfekr"; - GeoHashUtils.stringEncode(0.100000,51.000000); - LocationMarkerEntity location1 = LocationMarkerEntity.builder() - .id("1").name("Artur Konczak") - .locationAsString(latLonString) - .locationAsArray(lonLatArray) + GeoHashUtils.stringEncode(0.100000, 51.000000); + LocationMarkerEntity location1 = LocationMarkerEntity.builder() // + .id("1").name("Artur Konczak") // + .locationAsString(latLonString) // + .locationAsArray(lonLatArray) // .locationAsGeoHash(geohash) .build(); - LocationMarkerEntity location2 = LocationMarkerEntity.builder() - .id("2").name("Mohsin Husen") - .locationAsString(geohash.substring(0, 8)) - .locationAsArray(lonLatArray) - .locationAsGeoHash(geohash.substring(0, 8)) + LocationMarkerEntity location2 = LocationMarkerEntity.builder() // + .id("2").name("Mohsin Husen") // + .locationAsString(geohash.substring(0, 8)) // + .locationAsArray(lonLatArray) // + .locationAsGeoHash(geohash.substring(0, 8)) // .build(); - LocationMarkerEntity location3 = LocationMarkerEntity.builder() - .id("3").name("Rizwan Idrees") - .locationAsString(geohash) - .locationAsArray(lonLatArray) - .locationAsGeoHash(geohash) + LocationMarkerEntity location3 = LocationMarkerEntity.builder() // + .id("3").name("Rizwan Idrees") // + .locationAsString(geohash) // + .locationAsArray(lonLatArray) // + .locationAsGeoHash(geohash) // .build(); indexQueries.add(buildIndex(location1)); indexQueries.add(buildIndex(location2)); @@ -109,197 +116,237 @@ public class ElasticsearchTemplateGeoTests { @Test public void shouldPutMappingForGivenEntityWithGeoLocation() throws Exception { - //given - Class entity = AuthorMarkerEntity.class; + + // given + Class entity = AuthorMarkerEntity.class; elasticsearchTemplate.createIndex(entity); - //when - assertThat(elasticsearchTemplate.putMapping(entity), is(true)); + + // when + assertThat(elasticsearchTemplate.putMapping(entity)).isTrue(); } @Test public void shouldFindAuthorMarkersInRangeForGivenCriteriaQuery() { - //given + + // given loadClassBaseEntities(); CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( new Criteria("location").within(new GeoPoint(45.7806d, 3.0875d), "20km")); - //when - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria.size(), is(1)); - assertEquals("Franck Marchand", geoAuthorsForGeoCriteria.get(0).getName()); + // when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, + AuthorMarkerEntity.class); + + // then + assertThat(geoAuthorsForGeoCriteria).hasSize(1); + assertThat(geoAuthorsForGeoCriteria.get(0).getName()).isEqualTo("Franck Marchand"); } @Test public void shouldFindSelectedAuthorMarkerInRangeForGivenCriteriaQuery() { - //given + + // given loadClassBaseEntities(); CriteriaQuery geoLocationCriteriaQuery2 = new CriteriaQuery( new Criteria("name").is("Mohsin Husen").and("location").within(new GeoPoint(51.5171d, 0.1062d), "20km")); - //when - List geoAuthorsForGeoCriteria2 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery2, AuthorMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria2.size(), is(1)); - assertEquals("Mohsin Husen", geoAuthorsForGeoCriteria2.get(0).getName()); + // when + List geoAuthorsForGeoCriteria2 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery2, + AuthorMarkerEntity.class); + + // then + assertThat(geoAuthorsForGeoCriteria2).hasSize(1); + assertThat(geoAuthorsForGeoCriteria2.get(0).getName()).isEqualTo("Mohsin Husen"); } @Test public void shouldFindStringAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { - //given + + // given loadAnnotationBaseEntities(); CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( new Criteria("locationAsString").within(new GeoPoint(51.000000, 0.100000), "1km")); - //when - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, LocationMarkerEntity.class); + // when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, + LocationMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria.size(), is(1)); + // then + assertThat(geoAuthorsForGeoCriteria).hasSize(1); } @Test public void shouldFindDoubleAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { - //given + + // given loadAnnotationBaseEntities(); CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( new Criteria("locationAsArray").within(new GeoPoint(51.001000, 0.10100), "1km")); - //when - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, LocationMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria.size(), is(3)); + // when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, + LocationMarkerEntity.class); + + // then + assertThat(geoAuthorsForGeoCriteria).hasSize(3); } @Test public void shouldFindAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { - //given + + // given loadAnnotationBaseEntities(); CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( new Criteria("locationAsArray").within("51.001000, 0.10100", "1km")); - //when - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, LocationMarkerEntity.class); + // when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, + LocationMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria.size(), is(3)); + // then + assertThat(geoAuthorsForGeoCriteria).hasSize(3); } @Test public void shouldFindAnnotatedGeoMarkersInRangeForGivenCriteriaQueryUsingGeohashLocation() { - //given - loadAnnotationBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( - new Criteria("locationAsArray").within("u1044", "3km")); - //when - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, LocationMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria.size(), is(3)); + // given + loadAnnotationBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery(new Criteria("locationAsArray").within("u1044", "3km")); + + // when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, + LocationMarkerEntity.class); + + // then + assertThat(geoAuthorsForGeoCriteria).hasSize(3); } @Test public void shouldFindAllMarkersForNativeSearchQuery() { - //Given + + // given loadAnnotationBaseEntities(); - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsArray").setCorners(52, -1, 50, 1)); - //When - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(queryBuilder.build(), LocationMarkerEntity.class); - //Then - assertThat(geoAuthorsForGeoCriteria.size(), is(3)); + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder() + .withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsArray").setCorners(52, -1, 50, 1)); + + // when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(queryBuilder.build(), + LocationMarkerEntity.class); + + // then + assertThat(geoAuthorsForGeoCriteria).hasSize(3); } @Test public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoBox() { - //given + + // given loadClassBaseEntities(); CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( - new Criteria("location").boundedBy( - new GeoBox(new GeoPoint(53.5171d, 0), - new GeoPoint(49.5171d, 0.2062d)) - ) - ); - //when - List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); + new Criteria("location").boundedBy(new GeoBox(new GeoPoint(53.5171d, 0), new GeoPoint(49.5171d, 0.2062d)))); - //then - assertThat(geoAuthorsForGeoCriteria3.size(), is(2)); - assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees")))); + // when + List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, + AuthorMarkerEntity.class); + + // then + assertThat(geoAuthorsForGeoCriteria3).hasSize(2); + assertThat(geoAuthorsForGeoCriteria3.stream().map(AuthorMarkerEntity::getName)) + .containsExactlyInAnyOrder("Mohsin Husen", "Rizwan Idrees"); } @Test public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeohash() { - //given - loadClassBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( - new Criteria("location").boundedBy(GeoHashUtils.stringEncode(0, 53.5171d), GeoHashUtils.stringEncode(0.2062d, 49.5171d))); - //when - List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria3.size(), is(2)); - assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees")))); + // given + loadClassBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery(new Criteria("location") + .boundedBy(GeoHashUtils.stringEncode(0, 53.5171d), GeoHashUtils.stringEncode(0.2062d, 49.5171d))); + + // when + List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, + AuthorMarkerEntity.class); + + // then + assertThat(geoAuthorsForGeoCriteria3).hasSize(2); + assertThat(geoAuthorsForGeoCriteria3.stream().map(AuthorMarkerEntity::getName)) + .containsExactlyInAnyOrder("Mohsin Husen", "Rizwan Idrees"); } @Test public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoPoints() { - //given + + // given loadClassBaseEntities(); CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( - new Criteria("location").boundedBy( - new GeoPoint(53.5171d, 0), - new GeoPoint(49.5171d, 0.2062d)) - ); - //when - List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); + new Criteria("location").boundedBy(new GeoPoint(53.5171d, 0), new GeoPoint(49.5171d, 0.2062d))); - //then - assertThat(geoAuthorsForGeoCriteria3.size(), is(2)); - assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees")))); + // when + List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, + AuthorMarkerEntity.class); + + // then + assertThat(geoAuthorsForGeoCriteria3).hasSize(2); + assertThat(geoAuthorsForGeoCriteria3.stream().map(AuthorMarkerEntity::getName)) + .containsExactlyInAnyOrder("Mohsin Husen", "Rizwan Idrees"); } @Test public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingPoints() { - //given + + // given loadClassBaseEntities(); CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( - new Criteria("location").boundedBy( - new Point(53.5171d, 0), - new Point(49.5171d, 0.2062d )) - ); - //when - List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); + new Criteria("location").boundedBy(new Point(53.5171d, 0), new Point(49.5171d, 0.2062d))); - //then - assertThat(geoAuthorsForGeoCriteria3.size(), is(2)); - assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees")))); + // when + List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, + AuthorMarkerEntity.class); + + // then + assertThat(geoAuthorsForGeoCriteria3).hasSize(2); + assertThat(geoAuthorsForGeoCriteria3.stream().map(AuthorMarkerEntity::getName)) + .containsExactlyInAnyOrder("Mohsin Husen", "Rizwan Idrees"); } @Test public void shouldFindLocationWithGeoHashPrefix() { - //given + // given loadAnnotationBaseEntities(); - NativeSearchQueryBuilder location1 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u")); - NativeSearchQueryBuilder location2 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u1")); - NativeSearchQueryBuilder location3 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10")); - NativeSearchQueryBuilder location4 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j")); - NativeSearchQueryBuilder location5 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j4")); - NativeSearchQueryBuilder location11 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j46mkfek")); + NativeSearchQueryBuilder location1 = new NativeSearchQueryBuilder() + .withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u")); + NativeSearchQueryBuilder location2 = new NativeSearchQueryBuilder() + .withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u1")); + NativeSearchQueryBuilder location3 = new NativeSearchQueryBuilder() + .withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10")); + NativeSearchQueryBuilder location4 = new NativeSearchQueryBuilder() + .withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j")); + NativeSearchQueryBuilder location5 = new NativeSearchQueryBuilder() + .withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j4")); + NativeSearchQueryBuilder location11 = new NativeSearchQueryBuilder() + .withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j46mkfek")); - //when - List result1 = elasticsearchTemplate.queryForList(location1.build(), LocationMarkerEntity.class); - List result2 = elasticsearchTemplate.queryForList(location2.build(), LocationMarkerEntity.class); - List result3 = elasticsearchTemplate.queryForList(location3.build(), LocationMarkerEntity.class); - List result4 = elasticsearchTemplate.queryForList(location4.build(), LocationMarkerEntity.class); - List result5 = elasticsearchTemplate.queryForList(location5.build(), LocationMarkerEntity.class); - List result11 = elasticsearchTemplate.queryForList(location11.build(), LocationMarkerEntity.class); + // when + List result1 = elasticsearchTemplate.queryForList(location1.build(), + LocationMarkerEntity.class); + List result2 = elasticsearchTemplate.queryForList(location2.build(), + LocationMarkerEntity.class); + List result3 = elasticsearchTemplate.queryForList(location3.build(), + LocationMarkerEntity.class); + List result4 = elasticsearchTemplate.queryForList(location4.build(), + LocationMarkerEntity.class); + List result5 = elasticsearchTemplate.queryForList(location5.build(), + LocationMarkerEntity.class); + List result11 = elasticsearchTemplate.queryForList(location11.build(), + LocationMarkerEntity.class); - //then - assertThat(result1.size(), is(3)); - assertThat(result2.size(), is(3)); - assertThat(result3.size(), is(3)); - assertThat(result4.size(), is(3)); - assertThat(result5.size(), is(3)); - assertThat(result11.size(), is(2)); + // then + assertThat(result1).hasSize(3); + assertThat(result2).hasSize(3); + assertThat(result3).hasSize(3); + assertThat(result4).hasSize(3); + assertThat(result5).hasSize(3); + assertThat(result11).hasSize(2); } private IndexQuery buildIndex(LocationMarkerEntity result) { @@ -308,4 +355,106 @@ public class ElasticsearchTemplateGeoTests { indexQuery.setObject(result); return indexQuery; } + + /** + * @author Franck Marchand + * @author Mohsin Husen + */ + @Document(indexName = "test-index-author-marker-core-geo", type = "geo-class-point-type", shards = 1, replicas = 0, + refreshInterval = "-1") + static class AuthorMarkerEntity { + + @Id private String id; + private String name; + + private GeoPoint location; + + private AuthorMarkerEntity() {} + + public AuthorMarkerEntity(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public GeoPoint getLocation() { + return location; + } + + public void setLocation(GeoPoint location) { + this.location = location; + } + } + + /** + * @author Franck Marchand + * @author Mohsin Husen + */ + + static class AuthorMarkerEntityBuilder { + + private AuthorMarkerEntity result; + + public AuthorMarkerEntityBuilder(String id) { + result = new AuthorMarkerEntity(id); + } + + public AuthorMarkerEntityBuilder name(String name) { + result.setName(name); + return this; + } + + public AuthorMarkerEntityBuilder location(double latitude, double longitude) { + result.setLocation(new GeoPoint(latitude, longitude)); + return this; + } + + public AuthorMarkerEntity build() { + return result; + } + + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } + } + + /** + * @author Franck Marchand + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-location-marker-core-geo", type = "geo-annotation-point-type", shards = 1, replicas = 0, + refreshInterval = "-1") + static class LocationMarkerEntity { + + @Id private String id; + private String name; + + @GeoPointField private String locationAsString; + + @GeoPointField private double[] locationAsArray; + + @GeoPointField private String locationAsGeoHash; + + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/geo/LocationMarkerEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/geo/LocationMarkerEntity.java deleted file mode 100644 index 53cc3b67b..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/core/geo/LocationMarkerEntity.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2013-2019 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.geo; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.GeoPointField; - -/** - * @author Franck Marchand - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Builder -@Document(indexName = "test-index-location-marker", type = "geo-annotation-point-type", shards = 1, replicas = 0, refreshInterval = "-1") -public class LocationMarkerEntity { - - @Id - private String id; - private String name; - - @GeoPointField - private String locationAsString; - - @GeoPointField - private double[] locationAsArray; - - @GeoPointField - private String locationAsGeoHash; -} diff --git a/src/test/java/org/springframework/data/elasticsearch/core/query/CriteriaQueryTests.java b/src/test/java/org/springframework/data/elasticsearch/core/query/CriteriaQueryTests.java index e00c4e383..abd9659c2 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/query/CriteriaQueryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/query/CriteriaQueryTests.java @@ -16,37 +16,51 @@ package org.springframework.data.elasticsearch.core.query; import static org.apache.commons.lang.RandomStringUtils.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; import static org.springframework.data.elasticsearch.utils.IndexBuilder.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.lang.Double; +import java.lang.Long; import java.util.ArrayList; import java.util.List; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; import org.springframework.data.domain.Page; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.SampleEntity; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Rizwan Idrees * @author Mohsin Husen + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class CriteriaQueryTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { + elasticsearchTemplate.deleteIndex(SampleEntity.class); elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.putMapping(SampleEntity.class); @@ -55,6 +69,7 @@ public class CriteriaQueryTests { @Test public void shouldPerformAndOperation() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -67,19 +82,23 @@ public class CriteriaQueryTests { indexQuery.setObject(sampleEntity); elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.refresh(SampleEntity.class); - CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("test").and("message") - .contains("some")); + CriteriaQuery criteriaQuery = new CriteriaQuery( + new Criteria("message").contains("test").and("message").contains("some")); + // when SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); + // then - assertThat(sampleEntity1, is(notNullValue())); + assertThat(sampleEntity1).isNotNull(); } - @Ignore("DATAES-30") + // @Ignore("DATAES-30") @Test public void shouldPerformOrOperation() { + // given List indexQueries = new ArrayList<>(); + // first document String documentId = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); @@ -106,19 +125,23 @@ public class CriteriaQueryTests { indexQueries.add(indexQuery2); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); - CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("some").or("message") - .contains("test")); + CriteriaQuery criteriaQuery = new CriteriaQuery( + new Criteria("message").contains("some").or("message").contains("test")); + // when Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldPerformAndOperationWithinCriteria() { + // given List indexQueries = new ArrayList<>(); + // first document String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -134,18 +157,23 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().and(new Criteria("message").contains("some"))); + // when + Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); } - @Ignore("DATAES-30") + // @Ignore("DATAES-30") @Test public void shouldPerformOrOperationWithinCriteria() { + // given List indexQueries = new ArrayList<>(); + // first document String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -161,15 +189,18 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().or(new Criteria("message").contains("some"))); + // when Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldPerformIsOperation() { + // given List indexQueries = new ArrayList<>(); // first document @@ -187,17 +218,21 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message")); + // when Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message"); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldPerformMultipleIsOperations() { + // given List indexQueries = new ArrayList<>(); + // first document String documentId = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); @@ -225,17 +260,21 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message")); + // when Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message"); + assertThat(page.getTotalElements()).isEqualTo(1); } @Test public void shouldPerformEndsWithOperation() { + // given List indexQueries = new ArrayList<>(); + // first document String documentId = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); @@ -264,15 +303,18 @@ public class CriteriaQueryTests { elasticsearchTemplate.refresh(SampleEntity.class); Criteria criteria = new Criteria("message").endsWith("end"); CriteriaQuery criteriaQuery = new CriteriaQuery(criteria); + // when SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); + // then - assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); - assertThat(sampleEntity, is(notNullValue())); + assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message"); + assertThat(sampleEntity).isNotNull(); } @Test public void shouldPerformStartsWithOperation() { + // given List indexQueries = new ArrayList<>(); // first document @@ -303,15 +345,18 @@ public class CriteriaQueryTests { elasticsearchTemplate.refresh(SampleEntity.class); Criteria criteria = new Criteria("message").startsWith("start"); CriteriaQuery criteriaQuery = new CriteriaQuery(criteria); + // when SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); + // then - assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); - assertThat(sampleEntity, is(notNullValue())); + assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message"); + assertThat(sampleEntity).isNotNull(); } @Test public void shouldPerformContainsOperation() { + // given List indexQueries = new ArrayList<>(); // first document @@ -341,15 +386,18 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("contains")); + // when SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); + // then - assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); - assertThat(sampleEntity, is(notNullValue())); + assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message"); + assertThat(sampleEntity).isNotNull(); } @Test public void shouldExecuteExpression() { + // given List indexQueries = new ArrayList<>(); // first document @@ -379,15 +427,18 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").expression("+elasticsearch || test")); + // when SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); + // then - assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); - assertThat(sampleEntity, is(notNullValue())); + assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message"); + assertThat(sampleEntity).isNotNull(); } @Test public void shouldExecuteCriteriaChain() { + // given List indexQueries = new ArrayList<>(); // first document @@ -416,17 +467,20 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); - CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").startsWith("some").endsWith("search") - .contains("message").is("some message search")); + CriteriaQuery criteriaQuery = new CriteriaQuery( + new Criteria("message").startsWith("some").endsWith("search").contains("message").is("some message search")); + // when SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); + // then - assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); - assertThat(sampleEntity, is(notNullValue())); + assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message"); + assertThat(sampleEntity).isNotNull(); } @Test public void shouldPerformIsNotOperation() { + // given List indexQueries = new ArrayList<>(); // first document @@ -456,16 +510,19 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("foo").not()); + // when Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertTrue(criteriaQuery.getCriteria().isNegating()); - assertThat(page, is(notNullValue())); - assertFalse(page.iterator().next().getMessage().contains("foo")); + assertThat(criteriaQuery.getCriteria().isNegating()).isTrue(); + assertThat(page).isNotNull(); + assertThat(page.iterator().next().getMessage()).doesNotContain("foo"); } @Test public void shouldPerformBetweenOperation() { + // given List indexQueries = new ArrayList<>(); // first document @@ -497,14 +554,17 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100, 150)); + // when SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); + // then - assertThat(sampleEntity, is(notNullValue())); + assertThat(sampleEntity).isNotNull(); } @Test public void shouldPerformBetweenOperationWithoutUpperBound() { + // given List indexQueries = new ArrayList<>(); // first document @@ -536,15 +596,18 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(350, null)); + // when Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldPerformBetweenOperationWithoutLowerBound() { + // given List indexQueries = new ArrayList<>(); // first document @@ -576,15 +639,18 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(null, 550)); + // when Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldPerformLessThanEqualOperation() { + // given List indexQueries = new ArrayList<>(); // first document @@ -616,15 +682,18 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").lessThanEqual(750)); + // when Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldPerformGreaterThanEquals() { + // given List indexQueries = new ArrayList<>(); // first document @@ -656,15 +725,18 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").greaterThanEqual(950)); + // when Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldPerformBoostOperation() { + // given List indexQueries = new ArrayList<>(); // first document @@ -696,14 +768,17 @@ public class CriteriaQueryTests { elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(SampleEntity.class); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1)); + // when Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldReturnDocumentAboveMinimalScoreGivenCriteria() { + // given List indexQueries = new ArrayList<>(); @@ -715,11 +790,34 @@ public class CriteriaQueryTests { elasticsearchTemplate.refresh(SampleEntity.class); // when - CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("a").or(new Criteria("message").contains("b"))); + CriteriaQuery criteriaQuery = new CriteriaQuery( + new Criteria("message").contains("a").or(new Criteria("message").contains("b"))); criteriaQuery.setMinScore(2.0F); Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then - assertThat(page.getTotalElements(), is(1L)); - assertThat(page.getContent().get(0).getMessage(), is("ab")); + assertThat(page.getTotalElements()).isEqualTo(1); + assertThat(page.getContent().get(0).getMessage()).isEqualTo("ab"); + } + + @Builder + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Document(indexName = "test-index-sample-core-query", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @org.springframework.data.elasticsearch.annotations.Field(type = Text, store = true, + fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; } } diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/AbstractInheritedEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/AbstractInheritedEntity.java deleted file mode 100644 index 66fd7a408..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/AbstractInheritedEntity.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import java.util.Date; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldType; - -/** - * @author Kevin Letur - */ -public class AbstractInheritedEntity { - - @Id - private String id; - - @Field(type = FieldType.Date, index = false) - private Date createdDate; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/Author.java b/src/test/java/org/springframework/data/elasticsearch/entities/Author.java deleted file mode 100644 index 7c14b46a7..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/Author.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - */ -public class Author { - - private String id; - private String name; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/Book.java b/src/test/java/org/springframework/data/elasticsearch/entities/Book.java deleted file mode 100644 index ee8518432..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/Book.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -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.annotations.InnerField; -import org.springframework.data.elasticsearch.annotations.MultiField; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - * @author Nordine Bittich - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Builder -@Document(indexName = "test-index-book", type = "book", shards = 1, replicas = 0, refreshInterval = "-1") -public class Book { - - @Id - private String id; - private String name; - @Field(type = FieldType.Object) - private Author author; - @Field(type = FieldType.Nested) - private Map> buckets = new HashMap<>(); - @MultiField( - mainField = @Field(type = FieldType.Text, analyzer = "whitespace"), - otherFields = { - @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop", searchAnalyzer = "standard") - } - ) - private String description; -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/Car.java b/src/test/java/org/springframework/data/elasticsearch/entities/Car.java deleted file mode 100644 index 110a1fd26..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/Car.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - * @author Artur Konczak - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Builder -public class Car { - - private String name; - private String model; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getModel() { - return model; - } - - public void setModel(String model) { - this.model = model; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/CopyToEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/CopyToEntity.java deleted file mode 100644 index df99cb0af..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/CopyToEntity.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2018-2019 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.entities; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -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; - -/** - * @author Sascha Woo - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Builder -@Document(indexName = "test-copy-to", type = "test", shards = 1, replicas = 0, refreshInterval = "-1") -public class CopyToEntity { - - @Id private String id; - - @Field(type = FieldType.Keyword, copyTo = "name") private String firstName; - - @Field(type = FieldType.Keyword, copyTo = "name") private String lastName; - - @Field(type = FieldType.Keyword) private String name; -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/DoubleIDEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/DoubleIDEntity.java deleted file mode 100644 index 2022810ae..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/DoubleIDEntity.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Version; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldType; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - */ - -@Document(indexName = "test-index-double-keyed-entity", type = "double-keyed-entity", shards = 1, replicas = 0, refreshInterval = "-1") -public class DoubleIDEntity { - - @Id - private Double id; - private String type; - private String message; - @Version - private Long version; - - public Double getId() { - return id; - } - - public void setId(Double id) { - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Long getVersion() { - return version; - } - - public void setVersion(Long version) { - this.version = version; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/DynamicSettingAndMappingEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/DynamicSettingAndMappingEntity.java deleted file mode 100644 index ab4f8ca1b..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/DynamicSettingAndMappingEntity.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Mapping; -import org.springframework.data.elasticsearch.annotations.Setting; - -/** - * Sample DynamicSettingAndMappingEntity for test out dynamic setting using @Setting Annotation - * - * @author Mohsin Husen - */ -@Document(indexName = "test-index-dynamic-setting-and-mapping", type = "test-setting-type") -@Setting(settingPath = "/settings/test-settings.json") -@Mapping(mappingPath = "/mappings/test-mappings.json") -public class DynamicSettingAndMappingEntity { - - @Id - private String id; - private String name; - private String email; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/FieldDynamicMappingEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/FieldDynamicMappingEntity.java deleted file mode 100644 index af0a8bc66..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/FieldDynamicMappingEntity.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Mapping; - -/** - * Sample FieldDynamicMappingEntity for test dynamic mapping using @Mapping Annotation at field level - * - * @author Ted Liang - */ -@Document(indexName = "test-index-field-dynamic-mapping", type = "test-field-mapping-type") -public class FieldDynamicMappingEntity { - - @Id - private String id; - - @Mapping(mappingPath = "/mappings/test-field-mappings.json") - private byte[] file; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public byte[] getFile() { - return file; - } - - public void setFile(byte[] file) { - this.file = file; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/GTEVersionEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/GTEVersionEntity.java deleted file mode 100644 index d02f0773b..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/GTEVersionEntity.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2018-2019 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.entities; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; -import org.elasticsearch.index.VersionType; -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Version; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * @author Ivan Greene - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@ToString -@Builder -@Document(indexName = "test-index-sample", type = "test-type", shards = 1, replicas = 0, - refreshInterval = "-1", versionType = VersionType.EXTERNAL_GTE) -public class GTEVersionEntity { - - @Version - private Long version; - - @Id - private String id; - - private String name; -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/GeoEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/GeoEntity.java deleted file mode 100644 index cff20a934..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/GeoEntity.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.springframework.data.elasticsearch.entities; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -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.geo.GeoPoint; -import org.springframework.data.geo.Box; -import org.springframework.data.geo.Circle; -import org.springframework.data.geo.Point; -import org.springframework.data.geo.Polygon; - -/** - * @author Artur Konczak - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Builder -@Document(indexName = "test-index-geo", type = "geo-test-index", shards = 1, replicas = 0, refreshInterval = "-1") -public class GeoEntity { - - @Id - private String id; - - //geo shape - Spring Data - private Box box; - private Circle circle; - private Polygon polygon; - - //geo point - Custom implementation + Spring Data - @GeoPointField - private Point pointA; - - private GeoPoint pointB; - - @GeoPointField - private String pointC; - - @GeoPointField - private double[] pointD; -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/GirlFriend.java b/src/test/java/org/springframework/data/elasticsearch/entities/GirlFriend.java deleted file mode 100644 index a75db289c..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/GirlFriend.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import java.util.List; - -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldType; - -/** - * @author Mohsin Husen - */ - -public class GirlFriend { - - private String name; - - private String type; - - @Field(type = FieldType.Nested) - private List cars; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public List getCars() { - return cars; - } - - public void setCars(List cars) { - this.cars = cars; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/Group.java b/src/test/java/org/springframework/data/elasticsearch/entities/Group.java deleted file mode 100644 index 1992166d2..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/Group.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2017-2019 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.entities; - -import java.util.HashSet; -import java.util.Set; - -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; - -/** - * Created by akonczak on 21/08/2016. - */ -@Document(indexName = "test-index-group", type = "group") -public class Group { - - @Id - String id; - - @Field(type = FieldType.Nested, ignoreFields ={"groups"}) - private Set users = new HashSet<>(); -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/HetroEntity1.java b/src/test/java/org/springframework/data/elasticsearch/entities/HetroEntity1.java deleted file mode 100644 index 24d7c3908..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/HetroEntity1.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Version; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * @author Abdul Waheed - * @author Mohsin Husen - */ -@Document(indexName = "test-index-1", type = "hetro", replicas = 0, shards = 1) -public class HetroEntity1 { - - @Id - private String id; - private String firstName; - @Version - private Long version; - - public HetroEntity1(String id, String firstName) { - this.id = id; - this.firstName = firstName; - this.version = System.currentTimeMillis(); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public Long getVersion() { - return version; - } - - public void setVersion(Long version) { - this.version = version; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof SampleEntity)) { - return false; - } - if (this == obj) { - return true; - } - HetroEntity1 rhs = (HetroEntity1) obj; - return new EqualsBuilder().append(this.id, rhs.id).append(this.firstName, rhs.firstName).append(this.version, rhs.version).isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(id).append(firstName).append(version).toHashCode(); - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/HetroEntity2.java b/src/test/java/org/springframework/data/elasticsearch/entities/HetroEntity2.java deleted file mode 100644 index a20065397..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/HetroEntity2.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Version; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * @author Abdul Waheed - * @author Mohsin Husen - */ -@Document(indexName = "test-index-2", type = "hetro", replicas = 0, shards = 1) -public class HetroEntity2 { - - @Id - private String id; - private String lastName; - @Version - private Long version; - - public HetroEntity2(String id, String lastName) { - this.id = id; - this.lastName = lastName; - this.version = System.currentTimeMillis(); - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public Long getVersion() { - return version; - } - - public void setVersion(Long version) { - this.version = version; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof SampleEntity)) { - return false; - } - if (this == obj) { - return true; - } - HetroEntity2 rhs = (HetroEntity2) obj; - return new EqualsBuilder().append(this.id, rhs.id).append(this.lastName, rhs.lastName).append(this.version, rhs.version).isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(id).append(lastName).append(version).toHashCode(); - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/IntegerIDEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/IntegerIDEntity.java deleted file mode 100644 index a17c21eb6..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/IntegerIDEntity.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Version; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldType; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - */ - -@Document(indexName = "test-index-integer-keyed-entity", type = "integer-keyed-entity", shards = 1, replicas = 0, refreshInterval = "-1") -public class IntegerIDEntity { - - @Id - private Integer id; - private String type; - private String message; - @Version - private Long version; - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Long getVersion() { - return version; - } - - public void setVersion(Long version) { - this.version = version; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/MinimalEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/MinimalEntity.java deleted file mode 100644 index 70b541d03..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/MinimalEntity.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * MinimalEntity - * - * @author Philipp Jardas - */ -@Document(indexName = "test-index-minimal", type = "type") -public class MinimalEntity { - - @Id - private String id; -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/NonDocumentEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/NonDocumentEntity.java deleted file mode 100644 index e7d654ed9..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/NonDocumentEntity.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -import org.springframework.data.annotation.Id; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - */ -public class NonDocumentEntity { - - @Id - private String someId; - private String someField1; - private String someField2; - - public String getSomeField1() { - return someField1; - } - - public void setSomeField1(String someField1) { - this.someField1 = someField1; - } - - public String getSomeField2() { - return someField2; - } - - public void setSomeField2(String someField2) { - this.someField2 = someField2; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/NormalizerEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/NormalizerEntity.java deleted file mode 100644 index 0368b9e06..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/NormalizerEntity.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2018-2019 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.entities; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -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.annotations.InnerField; -import org.springframework.data.elasticsearch.annotations.MultiField; -import org.springframework.data.elasticsearch.annotations.Setting; - -/** - * @author Sascha Woo - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Builder -@Document(indexName = "test-index-normalizer", type = "test", shards = 1, replicas = 0, refreshInterval = "-1") -@Setting(settingPath = "/settings/test-normalizer.json") -public class NormalizerEntity { - - @Id private String id; - - @Field(type = FieldType.Keyword, normalizer = "lower_case_normalizer") - private String name; - - @MultiField(mainField = @Field(type = FieldType.Text), otherFields = { @InnerField(suffix = "lower_case", - type = FieldType.Keyword, normalizer = "lower_case_normalizer") }) - private String description; -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/ParentEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/ParentEntity.java deleted file mode 100644 index 6632fa04c..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/ParentEntity.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import org.springframework.core.style.ToStringCreator; -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.annotations.Parent; - -/** - * ParentEntity - * - * @author Philipp Jardas - * @author Mohsin Husen - */ -@Document(indexName = ParentEntity.INDEX, type = ParentEntity.PARENT_TYPE, shards = 1, replicas = 0, refreshInterval = "-1") -public class ParentEntity { - - public static final String INDEX = "parent-child"; - public static final String PARENT_TYPE = "parent-entity"; - public static final String CHILD_TYPE = "child-entity"; - - @Id - private String id; - @Field(type = FieldType.Text, store = true) - private String name; - - public ParentEntity() { - } - - public ParentEntity(String id, String name) { - this.id = id; - this.name = name; - } - - public String getId() { - return id; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - return new ToStringCreator(this).append("id", id).append("name", name).toString(); - } - - @Document(indexName = INDEX, type = CHILD_TYPE, shards = 1, replicas = 0, refreshInterval = "-1") - public static class ChildEntity { - - @Id - private String id; - @Field(type = FieldType.Text, store = true) - @Parent(type = PARENT_TYPE) - private String parentId; - @Field(type = FieldType.Text, store = true) - private String name; - - public ChildEntity() { - } - - public ChildEntity(String id, String parentId, String name) { - this.id = id; - this.parentId = parentId; - this.name = name; - } - - public String getId() { - return id; - } - - public String getParentId() { - return parentId; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - return new ToStringCreator(this).append("id", id).append("parentId", parentId).append("name", name).toString(); - } - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/Person.java b/src/test/java/org/springframework/data/elasticsearch/entities/Person.java deleted file mode 100644 index 5f6a7e80b..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/Person.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - - -import java.util.List; - -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; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - * @author Artur Konczak - */ - -@Document(indexName = "test-index-person", type = "user", shards = 1, replicas = 0, refreshInterval = "-1") -public class Person { - - @Id - private String id; - - private String name; - - @Field(type = FieldType.Nested) - private List car; - - @Field(type = FieldType.Nested, includeInParent = true) - private List books; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getCar() { - return car; - } - - public void setCar(List car) { - this.car = car; - } - - public List getBooks() { - return books; - } - - public void setBooks(List books) { - this.books = books; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/PersonMultipleLevelNested.java b/src/test/java/org/springframework/data/elasticsearch/entities/PersonMultipleLevelNested.java deleted file mode 100644 index 2a3528d7f..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/PersonMultipleLevelNested.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - - -import java.util.List; - -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; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - * @author Artur Konczak - */ - -@Document(indexName = "test-index-person-multiple-level-nested", type = "user", shards = 1, replicas = 0, refreshInterval = "-1") -public class PersonMultipleLevelNested { - - @Id - private String id; - - private String name; - - @Field(type = FieldType.Nested) - private List girlFriends; - - @Field(type = FieldType.Nested) - private List cars; - - @Field(type = FieldType.Nested, includeInParent = true) - private List bestCars; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getGirlFriends() { - return girlFriends; - } - - public void setGirlFriends(List girlFriends) { - this.girlFriends = girlFriends; - } - - public List getCars() { - return cars; - } - - public void setCars(List cars) { - this.cars = cars; - } - - public List getBestCars() { - return bestCars; - } - - public void setBestCars(List bestCars) { - this.bestCars = bestCars; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/Product.java b/src/test/java/org/springframework/data/elasticsearch/entities/Product.java deleted file mode 100644 index bdf22f5ca..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/Product.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.Date; -import java.util.List; - -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; - -/** - * @author Mohsin Husen - * @author Artur Konczak - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Builder -@Document(indexName = "test-index-product", type = "test-product-type", shards = 1, replicas = 0, refreshInterval = "-1") -public class Product { - - @Id - private String id; - - private List title; - - private String name; - - private String description; - - private String text; - - private List categories; - - private Float weight; - - @Field(type = FieldType.Float) - private Float price; - - private Integer popularity; - - private boolean available; - - private String location; - - private Date lastModified; - - - @Override - public int hashCode() { - return id.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Product other = (Product) obj; - if (id == null) { - if (other.id != null) { - return false; - } - } else if (!id.equals(other.id)) { - return false; - } - return true; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SampleDateMappingEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/SampleDateMappingEntity.java deleted file mode 100644 index d0564c192..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SampleDateMappingEntity.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.springframework.data.elasticsearch.entities; - -import static org.springframework.data.elasticsearch.annotations.FieldType.*; -import static org.springframework.data.elasticsearch.annotations.FieldType.Text; - -import java.util.Date; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.DateFormat; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; - -/** - * @author Jakub Vavrik - */ -@Document(indexName = "test-index-date-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1") -public class SampleDateMappingEntity { - - @Id - private String id; - - @Field(type = Text, index = false, store = true, analyzer = "standard") - private String message; - - @Field(type = Date, format = DateFormat.custom, pattern = "dd.MM.yyyy hh:mm") - private Date customFormatDate; - - @Field(type = Date) - private Date defaultFormatDate; - - @Field(type = Date, format = DateFormat.basic_date) - private Date basicFormatDate; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Date getCustomFormatDate() { - return customFormatDate; - } - - public void setCustomFormatDate(Date customFormatDate) { - this.customFormatDate = customFormatDate; - } - - public Date getDefaultFormatDate() { - return defaultFormatDate; - } - - public void setDefaultFormatDate(Date defaultFormatDate) { - this.defaultFormatDate = defaultFormatDate; - } - - public Date getBasicFormatDate() { - return basicFormatDate; - } - - public void setBasicFormatDate(Date basicFormatDate) { - this.basicFormatDate = basicFormatDate; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SampleDynamicTemplatesEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/SampleDynamicTemplatesEntity.java deleted file mode 100644 index 570f4fe68..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SampleDynamicTemplatesEntity.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.springframework.data.elasticsearch.entities; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.DynamicTemplates; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldType; - -/** - * @author Petr Kukral - */ -@Document(indexName = "test-dynamictemplates", type = "test-dynamictemplatestype", indexStoreType = "memory", shards = 1, - replicas = 0, refreshInterval = "-1") -@DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings.json") -public class SampleDynamicTemplatesEntity { - - @Id - private String id; - - @Field(type = FieldType.Object) - private Map names = new HashMap(); -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SampleDynamicTemplatesEntityTwo.java b/src/test/java/org/springframework/data/elasticsearch/entities/SampleDynamicTemplatesEntityTwo.java deleted file mode 100644 index bd3663d04..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SampleDynamicTemplatesEntityTwo.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.springframework.data.elasticsearch.entities; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.DynamicTemplates; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldType; - -/** - * @author Petr Kukral - */ -@Document(indexName = "test-dynamictemplates", type = "test-dynamictemplatestype", indexStoreType = "memory", shards = 1, - replicas = 0, refreshInterval = "-1") -@DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings_two.json") -public class SampleDynamicTemplatesEntityTwo { - - @Id - private String id; - - @Field(type = FieldType.Object) - private Map names = new HashMap(); -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SampleEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/SampleEntity.java deleted file mode 100644 index 31eaca031..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SampleEntity.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -import static org.springframework.data.elasticsearch.annotations.FieldType.*; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import lombok.ToString; - -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Version; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.Score; -import org.springframework.data.elasticsearch.annotations.ScriptedField; -import org.springframework.data.elasticsearch.core.geo.GeoPoint; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - * @author Chris White - * @author Sascha Woo - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@ToString -@Builder -@Document(indexName = "test-index-sample", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") -public class SampleEntity { - - @Id - private String id; - @Field(type = Text, store = true, fielddata = true) - private String type; - @Field(type = Text, store = true, fielddata = true) - private String message; - private int rate; - @ScriptedField - private Double scriptedRate; - private boolean available; - private String highlightedMessage; - private GeoPoint location; - @Version - private Long version; - @Score - private float score; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - SampleEntity that = (SampleEntity) o; - - if (available != that.available) return false; - if (rate != that.rate) return false; - if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) : that.highlightedMessage != null) - return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (location != null ? !location.equals(that.location) : that.location != null) return false; - if (message != null ? !message.equals(that.message) : that.message != null) return false; - if (type != null ? !type.equals(that.type) : that.type != null) return false; - if (version != null ? !version.equals(that.version) : that.version != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (type != null ? type.hashCode() : 0); - result = 31 * result + (message != null ? message.hashCode() : 0); - result = 31 * result + rate; - result = 31 * result + (available ? 1 : 0); - result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0); - result = 31 * result + (location != null ? location.hashCode() : 0); - result = 31 * result + (version != null ? version.hashCode() : 0); - return result; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SampleEntityUUIDKeyed.java b/src/test/java/org/springframework/data/elasticsearch/entities/SampleEntityUUIDKeyed.java deleted file mode 100644 index 71ed286f1..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SampleEntityUUIDKeyed.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.util.UUID; - -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Version; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldType; -import org.springframework.data.elasticsearch.annotations.ScriptedField; -import org.springframework.data.elasticsearch.core.geo.GeoPoint; - -/** - * @author Gad Akuka - * @author Rizwan Idrees - * @author Mohsin Husen - */ - -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Builder -@Document(indexName = "test-index-uuid-keyed", type = "test-type-uuid-keyed", shards = 1, replicas = 0, refreshInterval = "-1") -public class SampleEntityUUIDKeyed { - - @Id - private UUID id; - private String type; - @Field(type = FieldType.Text, fielddata = true) - private String message; - private int rate; - @ScriptedField - private Long scriptedRate; - private boolean available; - private String highlightedMessage; - - private GeoPoint location; - - @Version - private Long version; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - SampleEntityUUIDKeyed that = (SampleEntityUUIDKeyed) o; - - if (available != that.available) return false; - if (rate != that.rate) return false; - if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) : that.highlightedMessage != null) - return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (location != null ? !location.equals(that.location) : that.location != null) return false; - if (message != null ? !message.equals(that.message) : that.message != null) return false; - if (type != null ? !type.equals(that.type) : that.type != null) return false; - if (version != null ? !version.equals(that.version) : that.version != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (type != null ? type.hashCode() : 0); - result = 31 * result + (message != null ? message.hashCode() : 0); - result = 31 * result + rate; - result = 31 * result + (available ? 1 : 0); - result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0); - result = 31 * result + (location != null ? location.hashCode() : 0); - result = 31 * result + (version != null ? version.hashCode() : 0); - return result; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SampleInheritedEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/SampleInheritedEntity.java deleted file mode 100644 index d866f80d6..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SampleInheritedEntity.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import static org.springframework.data.elasticsearch.annotations.FieldType.Text; - -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; - -/** - * @author Kevin Leturc - */ -@Document(indexName = "test-index-sample-inherited", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1") -public class SampleInheritedEntity extends AbstractInheritedEntity { - - @Field(type = Text, index = false, store = true, analyzer = "standard") - private String message; - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SampleMappingEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/SampleMappingEntity.java deleted file mode 100644 index 6e67179f4..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SampleMappingEntity.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -import static org.springframework.data.elasticsearch.annotations.FieldType.Text; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - */ -@Document(indexName = "test-index-sample-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1") -public class SampleMappingEntity { - - @Id - private String id; - - @Field(type = Text, index = false, store = true, analyzer = "standard") - private String message; - - private NestedEntity nested; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - static class NestedEntity { - - @Field(type = Text) - private String someField; - - public String getSomeField() { - return someField; - } - - public void setSomeField(String someField) { - this.someField = someField; - } - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SampleTransientEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/SampleTransientEntity.java deleted file mode 100644 index 13fa32c0e..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SampleTransientEntity.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -import static org.springframework.data.elasticsearch.annotations.FieldType.Text; - -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.Transient; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Field; - -/** - * @author Jakub Vavrik - */ -@Document(indexName = "test-index-recursive-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1") -public class SampleTransientEntity { - - @Id - private String id; - - @Field(type = Text, index = false, store = true, analyzer = "standard") - private String message; - - @Transient - private NestedEntity nested; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - static class NestedEntity { - - @Field - private static NestedEntity someField = new NestedEntity(); - @Field - private Boolean something; - - public NestedEntity getSomeField() { - return someField; - } - - public void setSomeField(NestedEntity someField) { - this.someField = someField; - } - - public Boolean getSomething() { - return something; - } - - public void setSomething(Boolean something) { - this.something = something; - } - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SimpleRecursiveEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/SimpleRecursiveEntity.java deleted file mode 100644 index d4326d6da..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SimpleRecursiveEntity.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -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; - -/** - * @author Stuart Stevenson - * @author Mohsin Husen - */ -@Document(indexName = "test-index-simple-recursive", type = "circular-object", shards = 1, replicas = 0, refreshInterval = "-1") -public class SimpleRecursiveEntity { - - @Id - private String id; - @Field(type = FieldType.Object, ignoreFields = {"circularObject"}) - private SimpleRecursiveEntity circularObject; -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SpELEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/SpELEntity.java deleted file mode 100644 index d92229ed9..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SpELEntity.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * SpELEntity - * - * @author Artur Konczak - */ -@Document(indexName = "#{'test-index-abz'+'-'+'entity'}", type = "#{'my'+'Type'}", shards = 1, - replicas = 0, refreshInterval = "-1") -public class SpELEntity { - - @Id private String id; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/StockPrice.java b/src/test/java/org/springframework/data/elasticsearch/entities/StockPrice.java deleted file mode 100644 index 9f658f7b4..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/StockPrice.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2013-2019 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.entities; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import java.math.BigDecimal; - -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; - -/** - * @author Artur Konczak - * @author Mohsin Husen - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Builder -@Document(indexName = "test-index-stock", type = "price", shards = 1, replicas = 0, refreshInterval = "-1") -public class StockPrice { - - @Id - private String id; - - private String symbol; - - @Field(type = FieldType.Double) - private BigDecimal price; -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/SynonymEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/SynonymEntity.java deleted file mode 100644 index 23850f67e..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/SynonymEntity.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2014-2019 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.entities; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; -import org.springframework.data.elasticsearch.annotations.Mapping; -import org.springframework.data.elasticsearch.annotations.Setting; - -/** - * Sample DynamicSettingAndMappingEntity for test out dynamic setting using @Setting Annotation - * - * @author Mohsin Husen - */ -@Document(indexName = "test-index-synonym", type = "synonym-type") -@Setting(settingPath = "/synonyms/settings.json") -@Mapping(mappingPath = "/synonyms/mappings.json") -public class SynonymEntity { - - @Id - private String id; - private String text; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getText() { - return text; - } - - public void setText(String text) { - this.text = text; - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/UseServerConfigurationEntity.java b/src/test/java/org/springframework/data/elasticsearch/entities/UseServerConfigurationEntity.java deleted file mode 100644 index 2a291b1d7..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/UseServerConfigurationEntity.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.springframework.data.elasticsearch.entities; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * Created by akonczak on 12/12/2015. - */ -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Builder -@Document(indexName = "test-index-server-configuration", type = "test-type", useServerConfiguration = true, shards = 10, replicas = 10, refreshInterval = "-1") -public class UseServerConfigurationEntity { - - @Id - private String id; - - private String val; - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/entities/User.java b/src/test/java/org/springframework/data/elasticsearch/entities/User.java deleted file mode 100644 index 881397a21..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/entities/User.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2017-2019 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.entities; - -import java.util.HashSet; -import java.util.Set; - -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; - -/** - * Created by akonczak on 21/08/2016. - */ -@Document(indexName = "test-index-user", type = "user") -public class User { - @Id - private String id; - - @Field(type= FieldType.Nested,ignoreFields={"users"}) - private Set groups = new HashSet<>(); -} diff --git a/src/test/java/org/springframework/data/elasticsearch/immutable/ImmutableElasticsearchRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/immutable/ImmutableElasticsearchRepositoryTests.java index e78b2bac7..e3b394ea3 100644 --- a/src/test/java/org/springframework/data/elasticsearch/immutable/ImmutableElasticsearchRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/immutable/ImmutableElasticsearchRepositoryTests.java @@ -15,17 +15,20 @@ */ package org.springframework.data.elasticsearch.immutable; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; + +import lombok.Getter; +import lombok.NoArgsConstructor; import java.util.Optional; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; +import org.springframework.data.repository.CrudRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -34,6 +37,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Oliver Gierke * @author Mark Paluch * @author Christoph Strobl + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:immutable-repository-test.xml") @@ -50,27 +54,46 @@ public class ImmutableElasticsearchRepositoryTests { operations.refresh(ImmutableEntity.class); } - /** - * @see DATAES-281 - */ - @Test - @Ignore("fix me - UnsupportedOperation") + @Test // DATAES-281 public void shouldSaveAndFindImmutableDocument() { // when ImmutableEntity entity = repository.save(new ImmutableEntity("test name")); - assertThat(entity.getId(), is(notNullValue())); + assertThat(entity.getId()).isNotNull(); // then Optional entityFromElasticSearch = repository.findById(entity.getId()); - assertThat(entityFromElasticSearch.isPresent(), is(true)); + assertThat(entityFromElasticSearch).isPresent(); entityFromElasticSearch.ifPresent(immutableEntity -> { - assertThat(immutableEntity.getName(), is("test name")); - assertThat(immutableEntity.getId(), is(entity.getId())); + assertThat(immutableEntity.getName()).isEqualTo("test name"); + assertThat(immutableEntity.getId()).isEqualTo(entity.getId()); }); - } + + /** + * @author Young Gu + * @author Oliver Gierke + */ + @Document(indexName = "test-index-immutable") + @NoArgsConstructor(force = true) + @Getter + static class ImmutableEntity { + private final String id, name; + + public ImmutableEntity(String name) { + + this.id = null; + this.name = name; + } + } + + /** + * @author Young Gu + * @author Oliver Gierke + */ + public interface ImmutableElasticsearchRepository extends CrudRepository {} + } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/book/SampleElasticSearchBookRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/book/SampleElasticSearchBookRepository.java deleted file mode 100644 index 667fce736..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/book/SampleElasticSearchBookRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2013-2019 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.repositories.book; - -import org.springframework.data.elasticsearch.entities.Book; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - */ -public interface SampleElasticSearchBookRepository extends ElasticsearchRepository { - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiProductRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiProductRepository.java index f31409761..1bce2df2c 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiProductRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiProductRepository.java @@ -17,7 +17,6 @@ package org.springframework.data.elasticsearch.repositories.cdi; import java.util.Optional; -import org.springframework.data.elasticsearch.entities.Product; import org.springframework.data.repository.CrudRepository; /** @@ -26,7 +25,7 @@ import org.springframework.data.repository.CrudRepository; * @author Mark Paluch * @author Christoph Strobl */ -public interface CdiProductRepository extends CrudRepository { +public interface CdiProductRepository extends CrudRepository { - Optional findById(String id); + Optional findById(String id); } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryTests.java index c2887f175..8765d38ee 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryTests.java @@ -15,9 +15,19 @@ */ package org.springframework.data.elasticsearch.repositories.cdi; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Optional; import org.apache.webbeans.cditest.CdiTestContainer; @@ -26,12 +36,18 @@ import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.springframework.data.elasticsearch.entities.Product; +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.annotations.InnerField; +import org.springframework.data.elasticsearch.annotations.MultiField; /** * @author Mohsin Husen * @author Mark Paluch * @author Christoph Strobl + * @author Peter-Josef Meisch */ public class CdiRepositoryTests { @@ -63,12 +79,13 @@ public class CdiRepositoryTests { personRepository = client.getSamplePersonRepository(); repository.deleteAll(); qualifiedProductRepository = client.getQualifiedProductRepository(); + qualifiedProductRepository.deleteAll(); } @Test public void testCdiRepository() { - assertNotNull(repository); + assertThat(repository).isNotNull(); Product bean = new Product(); bean.setId("id-1"); @@ -76,33 +93,30 @@ public class CdiRepositoryTests { repository.save(bean); - assertTrue(repository.existsById(bean.getId())); + assertThat(repository.existsById(bean.getId())).isTrue(); Optional retrieved = repository.findById(bean.getId()); - assertTrue(retrieved.isPresent()); + assertThat(retrieved).isPresent(); retrieved.ifPresent(product -> { - assertEquals(bean.getId(), product.getId()); - assertEquals(bean.getName(), product.getName()); + assertThat(bean.getId()).isEqualTo(product.getId()); + assertThat(bean.getName()).isEqualTo(product.getName()); }); - assertEquals(1, repository.count()); + assertThat(repository.count()).isEqualTo(1); - assertTrue(repository.existsById(bean.getId())); + assertThat(repository.existsById(bean.getId())).isTrue(); repository.delete(bean); - assertEquals(0, repository.count()); + assertThat(repository.count()).isEqualTo(0); retrieved = repository.findById(bean.getId()); - assertFalse(retrieved.isPresent()); + assertThat(retrieved).isNotPresent(); } - /** - * @see DATAES-234 - */ - @Test + @Test // DATAES-234 public void testQualifiedCdiRepository() { - assertNotNull(qualifiedProductRepository); + assertThat(qualifiedProductRepository).isNotNull(); Product bean = new Product(); bean.setId("id-1"); @@ -110,32 +124,226 @@ public class CdiRepositoryTests { qualifiedProductRepository.save(bean); - assertTrue(qualifiedProductRepository.existsById(bean.getId())); + assertThat(qualifiedProductRepository.existsById(bean.getId())).isTrue(); Optional retrieved = qualifiedProductRepository.findById(bean.getId()); - assertTrue(retrieved.isPresent()); + assertThat(retrieved).isPresent(); retrieved.ifPresent(product -> { - assertEquals(bean.getId(), product.getId()); - assertEquals(bean.getName(), product.getName()); + assertThat(bean.getId()).isEqualTo(product.getId()); + assertThat(bean.getName()).isEqualTo(product.getName()); }); - assertEquals(1, qualifiedProductRepository.count()); + assertThat(qualifiedProductRepository.count()).isEqualTo(1); - assertTrue(qualifiedProductRepository.existsById(bean.getId())); + assertThat(qualifiedProductRepository.existsById(bean.getId())).isTrue(); qualifiedProductRepository.delete(bean); - assertEquals(0, qualifiedProductRepository.count()); + assertThat(qualifiedProductRepository.count()).isEqualTo(0); retrieved = qualifiedProductRepository.findById(bean.getId()); - assertFalse(retrieved.isPresent()); + assertThat(retrieved).isNotPresent(); + } + + @Test // DATAES-113 + public void returnOneFromCustomImpl() { + + assertThat(personRepository.returnOne()).isEqualTo(1); } /** - * @see DATAES-113 + * @author Mohsin Husen + * @author Artur Konczak */ - @Test - public void returnOneFromCustomImpl() { - assertThat(personRepository.returnOne(), is(1)); + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-product-cdi-repository", type = "test-product-type", shards = 1, replicas = 0, + refreshInterval = "-1") + static class Product { + + @Id private String id; + + private List title; + + private String name; + + private String description; + + private String text; + + private List categories; + + private Float weight; + + @Field(type = FieldType.Float) private Float price; + + private Integer popularity; + + private boolean available; + + private String location; + + private Date lastModified; + + @Override + public int hashCode() { + return id.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Product other = (Product) obj; + if (id == null) { + if (other.id != null) { + return false; + } + } else if (!id.equals(other.id)) { + return false; + } + return true; + } } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + + @Document(indexName = "test-index-person-cdi-repository", type = "user", shards = 1, replicas = 0, refreshInterval = "-1") + static class Person { + + @Id private String id; + + private String name; + + @Field(type = FieldType.Nested) private List car; + + @Field(type = FieldType.Nested, includeInParent = true) private List books; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCar() { + return car; + } + + public void setCar(List car) { + this.car = car; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Nordine Bittich + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-book-cdi-repository", type = "book", shards = 1, replicas = 0, refreshInterval = "-1") + static class Book { + + @Id private String id; + private String name; + @Field(type = FieldType.Object) private Author author; + @Field(type = FieldType.Nested) private Map> buckets = new HashMap<>(); + @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"), + otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop", + searchAnalyzer = "standard") }) private String description; + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + static class Car { + + private String name; + private String model; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class Author { + + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/QualifiedProductRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/QualifiedProductRepository.java index af4a0706b..8f29926cc 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/QualifiedProductRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/QualifiedProductRepository.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.repositories.cdi; -import org.springframework.data.elasticsearch.entities.Product; import org.springframework.data.repository.CrudRepository; /** @@ -24,6 +23,6 @@ import org.springframework.data.repository.CrudRepository; */ @PersonDB @OtherQualifier -public interface QualifiedProductRepository extends CrudRepository { +public interface QualifiedProductRepository extends CrudRepository { } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/SamplePersonRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/SamplePersonRepository.java index 2d81e28ee..98c464e10 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/SamplePersonRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/SamplePersonRepository.java @@ -15,13 +15,12 @@ */ package org.springframework.data.elasticsearch.repositories.cdi; -import org.springframework.data.elasticsearch.entities.Person; import org.springframework.data.repository.Repository; /** * @author Mark Paluch * @see DATAES-113 */ -public interface SamplePersonRepository extends Repository, SamplePersonRepositoryCustom { +public interface SamplePersonRepository extends Repository, SamplePersonRepositoryCustom { } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexCustomMethodRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexCustomMethodRepositoryTests.java new file mode 100644 index 000000000..69f4f4193 --- /dev/null +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexCustomMethodRepositoryTests.java @@ -0,0 +1,105 @@ +/* + * Copyright 2013-2019 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.repositories.complex.custommethod.autowiring; + +import static org.assertj.core.api.Assertions.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.lang.Double; +import java.lang.Long; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; +import org.springframework.data.elasticsearch.utils.IndexInitializer; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Artur Konczak + * @author Mohsin Husen + * @author Peter-Josef Meisch + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:complex-custom-method-repository-test.xml") +public class ComplexCustomMethodRepositoryTests { + + @Autowired private ComplexElasticsearchRepository complexRepository; + + @Autowired private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + + IndexInitializer.init(elasticsearchTemplate, SampleEntity.class); + } + + @Test + public void shouldExecuteComplexCustomMethod() { + + // given + + // when + String result = complexRepository.doSomethingSpecial(); + + // then + assertThat(result).isEqualTo("2+2=4"); + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-repositories-complex-custommethod-autowiring", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + } + +} diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexElasticsearchRepository.java similarity index 79% rename from src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepository.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexElasticsearchRepository.java index 73adf0f1a..4ee361b0d 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexElasticsearchRepository.java @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repository.complex; +package org.springframework.data.elasticsearch.repositories.complex.custommethod.autowiring; -import org.springframework.data.elasticsearch.entities.SampleEntity; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * @author Artur Konczak */ -public interface ComplexElasticsearchRepository extends ElasticsearchRepository, ComplexElasticsearchRepositoryCustom { +public interface ComplexElasticsearchRepository extends ElasticsearchRepository, ComplexElasticsearchRepositoryCustom { } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryCustom.java b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexElasticsearchRepositoryCustom.java similarity index 89% rename from src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryCustom.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexElasticsearchRepositoryCustom.java index 91c38d763..ce9e0fafd 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryCustom.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexElasticsearchRepositoryCustom.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repository.complex; +package org.springframework.data.elasticsearch.repositories.complex.custommethod.autowiring; /** * @author Artur Konczak diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryImpl.java b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexElasticsearchRepositoryImpl.java similarity index 82% rename from src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryImpl.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexElasticsearchRepositoryImpl.java index d51e41a0a..9cfe37880 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryImpl.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/autowiring/ComplexElasticsearchRepositoryImpl.java @@ -1,4 +1,4 @@ -package org.springframework.data.elasticsearch.repository.complex; +package org.springframework.data.elasticsearch.repositories.complex.custommethod.autowiring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexCustomMethodRepositoryManualWiringTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexCustomMethodRepositoryManualWiringTests.java new file mode 100644 index 000000000..439068956 --- /dev/null +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexCustomMethodRepositoryManualWiringTests.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013-2019 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.repositories.complex.custommethod.manualwiring; + +import static org.assertj.core.api.Assertions.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.lang.Double; +import java.lang.Long; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; +import org.springframework.data.elasticsearch.utils.IndexInitializer; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Artur Konczak + * @author Peter-Josef Meisch + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:complex-custom-method-repository-manual-wiring-test.xml") +public class ComplexCustomMethodRepositoryManualWiringTests { + + @Autowired private ComplexElasticsearchRepositoryManualWiring complexRepository; + + @Autowired private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + + IndexInitializer.init(elasticsearchTemplate,SampleEntity.class); + } + + @Test + public void shouldExecuteComplexCustomMethod() { + + // given + + // when + String result = complexRepository.doSomethingSpecial(); + + // then + assertThat(result).isEqualTo("3+3=6"); + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-repository-manual-wiring", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + + } +} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexElasticsearchRepositoryCustom.java b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexElasticsearchRepositoryCustom.java new file mode 100644 index 000000000..8ad46c637 --- /dev/null +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexElasticsearchRepositoryCustom.java @@ -0,0 +1,10 @@ +package org.springframework.data.elasticsearch.repositories.complex.custommethod.manualwiring; + +/** + * @author Artur Konczak + * @author Mohsin Husen + */ +interface ComplexElasticsearchRepositoryCustom { + + String doSomethingSpecial(); +} diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryManualWiring.java b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexElasticsearchRepositoryManualWiring.java similarity index 69% rename from src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryManualWiring.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexElasticsearchRepositoryManualWiring.java index 1dbb1ebd4..5a16b76b2 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryManualWiring.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexElasticsearchRepositoryManualWiring.java @@ -13,14 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repository.complex; +package org.springframework.data.elasticsearch.repositories.complex.custommethod.manualwiring; -import org.springframework.data.elasticsearch.entities.SampleEntity; +import org.springframework.data.elasticsearch.repositories.complex.custommethod.autowiring.ComplexElasticsearchRepositoryCustom; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * @author Artur Konczak */ -public interface ComplexElasticsearchRepositoryManualWiring extends ElasticsearchRepository, ComplexElasticsearchRepositoryCustom { +public interface ComplexElasticsearchRepositoryManualWiring extends ElasticsearchRepository, ComplexElasticsearchRepositoryCustom { } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryManualWiringImpl.java b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexElasticsearchRepositoryManualWiringImpl.java similarity index 83% rename from src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryManualWiringImpl.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexElasticsearchRepositoryManualWiringImpl.java index 50bac71f6..8a327393c 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryManualWiringImpl.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/complex/custommethod/manualwiring/ComplexElasticsearchRepositoryManualWiringImpl.java @@ -13,9 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repository.complex; +package org.springframework.data.elasticsearch.repositories.complex.custommethod.manualwiring; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.repositories.complex.custommethod.autowiring.ComplexElasticsearchRepositoryCustom; /** * @author Artur Konczak diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/custom/SampleCustomMethodRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/custom/SampleCustomMethodRepository.java deleted file mode 100644 index 01b32c502..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/custom/SampleCustomMethodRepository.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2013-2019 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.repositories.custom; - -import java.util.List; -import java.util.stream.Stream; - -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.elasticsearch.annotations.Query; -import org.springframework.data.elasticsearch.core.geo.GeoBox; -import org.springframework.data.elasticsearch.core.geo.GeoPoint; -import org.springframework.data.elasticsearch.entities.SampleEntity; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; -import org.springframework.data.geo.Box; -import org.springframework.data.geo.Distance; -import org.springframework.data.geo.Point; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - * @author Kevin Leturc - */ -public interface SampleCustomMethodRepository extends ElasticsearchRepository { - - Page findByType(String type, Pageable pageable); - - Page findByTypeNot(String type, Pageable pageable); - - @Query("{\"bool\" : {\"must\" : {\"term\" : {\"message\" : \"?0\"}}}}") - Page findByMessage(String message, Pageable pageable); - - @Query("{\"bool\" : {\"must\" : {\"term\" : {\"message\" : \"?0\"}}}}") - List findByMessage(String message); - - Page findByAvailable(boolean available, Pageable pageable); - - Page findByRateLessThan(int rate, Pageable pageable); - - Page findByRateBefore(int rate, Pageable pageable); - - Page findByRateAfter(int rate, Pageable pageable); - - Page findByMessageLike(String message, Pageable pageable); - - Page findByMessageStartingWith(String message, Pageable pageable); - - Page findByMessageEndingWith(String message, Pageable pageable); - - Page findByMessageContaining(String message, Pageable pageable); - - Page findByIdIn(List ids, Pageable pageable); - - Page findByIdNotIn(List ids, Pageable pageable); - - Page findByAvailableTrue(Pageable pageable); - - Page findByAvailableFalse(Pageable pageable); - - Page findByMessageOrderByTypeAsc(String message, Pageable pageable); - - Page findByLocation(GeoPoint point, Pageable pageable); - - Page findByLocationAndMessage(GeoPoint point, String msg, Pageable pageable); - - Page findByLocationWithin(GeoPoint point, String distance, Pageable pageable); - - Page findByLocationWithin(Point point, Distance distance, Pageable pageable); - - Page findByLocationNear(GeoBox box, Pageable pageable); - - Page findByLocationNear(Box box, Pageable pageable); - - Page findByLocationNear(Point point, Distance distance, Pageable pageable); - - Page findByLocationNear(GeoPoint point, String distance, Pageable pageable); - - Stream findByType(String type); - - long countByType(String type); - - long countByTypeNot(String type); - - long countByAvailable(boolean available); - - long countByRateLessThan(int rate); - - long countByRateBefore(int rate); - - long countByRateAfter(int rate); - - long countByMessageLike(String message); - - long countByMessageStartingWith(String message); - - long countByMessageEndingWith(String message); - - long countByMessageContaining(String message); - - long countByIdIn(List ids); - - long countByIdNotIn(List ids); - - long countByAvailableTrue(); - - long countByAvailableFalse(); - - long countByLocationWithin(GeoPoint point, String distance); - - long countByLocationWithin(Point point, Distance distance); - - long countByLocationNear(GeoBox box); - - long countByLocationNear(Box box); - - long countByLocationNear(Point point, Distance distance); - - long countByLocationNear(GeoPoint point, String distance); -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryBaseTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryBaseTests.java similarity index 77% rename from src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryBaseTests.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryBaseTests.java index a7cc7876e..a35853fa6 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryBaseTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryBaseTests.java @@ -13,27 +13,44 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repositories; +package org.springframework.data.elasticsearch.repositories.custommethod; import static org.apache.commons.lang.RandomStringUtils.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.lang.Double; +import java.lang.Long; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.stream.Stream; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Order; -import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Query; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.geo.GeoBox; import org.springframework.data.elasticsearch.core.geo.GeoPoint; -import org.springframework.data.elasticsearch.entities.SampleEntity; -import org.springframework.data.elasticsearch.repositories.custom.SampleCustomMethodRepository; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.geo.Box; import org.springframework.data.geo.Distance; import org.springframework.data.geo.Metrics; @@ -46,6 +63,7 @@ import org.springframework.data.geo.Point; * @author Kevin Leturc * @author Christoph Strobl * @author Don Wellington + * @author Peter-Josef Meisch */ public abstract class CustomMethodRepositoryBaseTests { @@ -53,6 +71,7 @@ public abstract class CustomMethodRepositoryBaseTests { @Test public void shouldExecuteCustomMethod() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -60,15 +79,18 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity.setType("test"); sampleEntity.setMessage("some message"); repository.save(sampleEntity); + // when Page page = repository.findByType("test", PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldExecuteCustomMethodForNot() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -76,15 +98,17 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity.setType("some"); sampleEntity.setMessage("some message"); repository.save(sampleEntity); + // when Page page = repository.findByTypeNot("test", PageRequest.of(0, 10)); // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -93,15 +117,18 @@ public abstract class CustomMethodRepositoryBaseTests { String searchTerm = "customQuery"; sampleEntity.setMessage(searchTerm); repository.save(sampleEntity); + // when Page page = repository.findByMessage(searchTerm.toLowerCase(), PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithLessThan() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -121,13 +148,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByRateLessThan(10, PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithBefore() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -139,13 +168,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByRateBefore(10, PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithAfter() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -157,13 +188,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByRateAfter(10, PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithLike() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -175,13 +208,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByMessageLike("fo", PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodForStartingWith() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -193,13 +228,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByMessageStartingWith("fo", PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodForEndingWith() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -211,13 +248,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByMessageEndingWith("o", PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodForContains() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -229,13 +268,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByMessageContaining("fo", PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodForIn() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -256,13 +297,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByIdIn(ids, PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(2L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(2L); } @Test public void shouldExecuteCustomMethodForNotIn() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -279,18 +322,19 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity2.setMessage("bar"); repository.save(sampleEntity2); - List ids = Arrays.asList(documentId); + List ids = Collections.singletonList(documentId); // when Page page = repository.findByIdNotIn(ids, PageRequest.of(0, 10)); // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - assertThat(page.getContent().get(0).getId(), is(documentId2)); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); + assertThat(page.getContent().get(0).getId()).isEqualTo(documentId2); } @Test public void shouldExecuteCustomMethodForTrue() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -310,13 +354,15 @@ public abstract class CustomMethodRepositoryBaseTests { repository.save(sampleEntity2); // when Page page = repository.findByAvailableTrue(PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodForFalse() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -334,15 +380,18 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity2.setMessage("bar"); sampleEntity2.setAvailable(false); repository.save(sampleEntity2); + // when Page page = repository.findByAvailableFalse(PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodForOrderBy() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -372,13 +421,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByMessageOrderByTypeAsc("foo", PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithBooleanParameter() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -396,15 +447,18 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity2.setMessage("bar"); sampleEntity2.setAvailable(false); repository.save(sampleEntity2); + // when Page page = repository.findByAvailable(false, PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldReturnPageableResultsWithQueryAnnotationExpectedPageSize() { + // given for (int i = 0; i < 30; i++) { String documentId = String.valueOf(i); @@ -414,15 +468,18 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity); } + // when Page pageResult = repository.findByMessage("message", PageRequest.of(0, 23)); + // then - assertThat(pageResult.getTotalElements(), is(equalTo(30L))); - assertThat(pageResult.getContent().size(), is(equalTo(23))); + assertThat(pageResult.getTotalElements()).isEqualTo(30L); + assertThat(pageResult.getContent().size()).isEqualTo(23); } @Test public void shouldReturnPageableResultsWithGivenSortingOrder() { + // given String documentId = random(5); SampleEntity sampleEntity = new SampleEntity(); @@ -444,16 +501,19 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity3.setMessage("abe"); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity3); + // when Page pageResult = repository.findByMessageContaining("a", PageRequest.of(0, 23, Sort.by(Order.desc("message")))); + // then - assertThat(pageResult.getContent().isEmpty(), is(false)); - assertThat(pageResult.getContent().get(0).getMessage(), is(sampleEntity3.getMessage())); + assertThat(pageResult.getContent()).isNotEmpty(); + assertThat(pageResult.getContent().get(0).getMessage()).isEqualTo(sampleEntity3.getMessage()); } @Test public void shouldReturnListForMessage() { + // given String documentId = random(5); SampleEntity sampleEntity = new SampleEntity(); @@ -475,15 +535,17 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity3.setMessage("abe"); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity3); + // when List sampleEntities = repository.findByMessage("abc"); + // then - assertThat(sampleEntities.isEmpty(), is(false)); - assertThat(sampleEntities.size(), is(1)); + assertThat(sampleEntities).hasSize(1); } @Test public void shouldExecuteCustomMethodWithGeoPoint() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -497,13 +559,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByLocation(new GeoPoint(45.7806d, 3.0875d), PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithGeoPointAndString() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -528,13 +592,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByLocationAndMessage(new GeoPoint(45.7806d, 3.0875d), "foo", PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithWithinGeoPoint() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -549,13 +615,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByLocationWithin(new GeoPoint(45.7806d, 3.0875d), "2km", PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithWithinPoint() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -570,13 +638,15 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByLocationWithin(new Point(45.7806d, 3.0875d), new Distance(2, Metrics.KILOMETERS), PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithNearBox() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -600,20 +670,23 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page pageAll = repository.findAll(PageRequest.of(0, 10)); + // then - assertThat(pageAll, is(notNullValue())); - assertThat(pageAll.getTotalElements(), is(equalTo(2L))); + assertThat(pageAll).isNotNull(); + assertThat(pageAll.getTotalElements()).isEqualTo(2L); // when Page page = repository.findByLocationNear(new Box(new Point(46d, 3d), new Point(45d, 4d)), PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } @Test public void shouldExecuteCustomMethodWithNearPointAndDistance() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -628,32 +701,30 @@ public abstract class CustomMethodRepositoryBaseTests { // when Page page = repository.findByLocationNear(new Point(45.7806d, 3.0875d), new Distance(2, Metrics.KILOMETERS), PageRequest.of(0, 10)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page).isNotNull(); + assertThat(page.getTotalElements()).isEqualTo(1L); } - /* - DATAES-165 - */ - @Test + @Test // DATAES-165 public void shouldAllowReturningJava8StreamInCustomQuery() { + // given List entities = createSampleEntities("abc", 30); repository.saveAll(entities); // when Stream stream = repository.findByType("abc"); + // then - assertThat(stream, is(notNullValue())); - assertThat(stream.count(), is(equalTo(30L))); + assertThat(stream).isNotNull(); + assertThat(stream.count()).isEqualTo(30L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethod() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -673,15 +744,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByType("test"); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodForNot() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -701,15 +771,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByTypeNot("test"); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodWithBooleanParameter() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -727,17 +796,17 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity2.setMessage("bar"); sampleEntity2.setAvailable(false); repository.save(sampleEntity2); + // when long count = repository.countByAvailable(false); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodWithLessThan() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -757,15 +826,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByRateLessThan(10); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodWithBefore() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -786,16 +854,15 @@ public abstract class CustomMethodRepositoryBaseTests { repository.save(sampleEntity2); // when + long count = repository.countByRateBefore(10); // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodWithAfter() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -817,15 +884,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByRateAfter(10); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodWithLike() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -847,15 +913,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByMessageLike("fo"); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodForStartingWith() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -877,15 +942,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByMessageStartingWith("fo"); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodForEndingWith() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -907,15 +971,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByMessageEndingWith("o"); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodForContains() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -937,15 +1000,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByMessageContaining("fo"); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodForIn() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -966,15 +1028,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByIdIn(ids); + // then - assertThat(count, is(equalTo(2L))); + assertThat(count).isEqualTo(2L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodForNotIn() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -991,19 +1052,18 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity2.setMessage("bar"); repository.save(sampleEntity2); - List ids = Arrays.asList(documentId); + List ids = Collections.singletonList(documentId); // when long count = repository.countByIdNotIn(ids); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodForTrue() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -1023,15 +1083,14 @@ public abstract class CustomMethodRepositoryBaseTests { repository.save(sampleEntity2); // when long count = repository.countByAvailableTrue(); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodForFalse() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -1049,17 +1108,17 @@ public abstract class CustomMethodRepositoryBaseTests { sampleEntity2.setMessage("bar"); sampleEntity2.setAvailable(false); repository.save(sampleEntity2); + // when long count = repository.countByAvailableFalse(); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodWithWithinGeoPoint() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -1083,15 +1142,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByLocationWithin(new GeoPoint(45.7806d, 3.0875d), "2km"); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodWithWithinPoint() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -1115,15 +1173,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByLocationWithin(new Point(45.7806d, 3.0875d), new Distance(2, Metrics.KILOMETERS)); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodWithNearBox() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -1147,15 +1204,14 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByLocationNear(new Box(new Point(46d, 3d), new Point(45d, 4d))); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } - /* - DATAES-106 - */ - @Test + @Test // DATAES-106 public void shouldCountCustomMethodWithNearPointAndDistance() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -1179,13 +1235,16 @@ public abstract class CustomMethodRepositoryBaseTests { // when long count = repository.countByLocationNear(new Point(45.7806d, 3.0875d), new Distance(2, Metrics.KILOMETERS)); + // then - assertThat(count, is(equalTo(1L))); + assertThat(count).isEqualTo(1L); } private List createSampleEntities(String type, int numberOfEntities) { + List entities = new ArrayList<>(); for (int i = 0; i < numberOfEntities; i++) { + SampleEntity entity = new SampleEntity(); entity.setId(randomNumeric(numberOfEntities)); entity.setAvailable(true); @@ -1193,6 +1252,137 @@ public abstract class CustomMethodRepositoryBaseTests { entity.setType(type); entities.add(entity); } + return entities; } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-repositories-custo-method", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Kevin Leturc + */ + public interface SampleCustomMethodRepository extends ElasticsearchRepository { + + Page findByType(String type, Pageable pageable); + + Page findByTypeNot(String type, Pageable pageable); + + @Query("{\"bool\" : {\"must\" : {\"term\" : {\"message\" : \"?0\"}}}}") + Page findByMessage(String message, Pageable pageable); + + @Query("{\"bool\" : {\"must\" : {\"term\" : {\"message\" : \"?0\"}}}}") + List findByMessage(String message); + + Page findByAvailable(boolean available, Pageable pageable); + + Page findByRateLessThan(int rate, Pageable pageable); + + Page findByRateBefore(int rate, Pageable pageable); + + Page findByRateAfter(int rate, Pageable pageable); + + Page findByMessageLike(String message, Pageable pageable); + + Page findByMessageStartingWith(String message, Pageable pageable); + + Page findByMessageEndingWith(String message, Pageable pageable); + + Page findByMessageContaining(String message, Pageable pageable); + + Page findByIdIn(List ids, Pageable pageable); + + Page findByIdNotIn(List ids, Pageable pageable); + + Page findByAvailableTrue(Pageable pageable); + + Page findByAvailableFalse(Pageable pageable); + + Page findByMessageOrderByTypeAsc(String message, Pageable pageable); + + Page findByLocation(GeoPoint point, Pageable pageable); + + Page findByLocationAndMessage(GeoPoint point, String msg, Pageable pageable); + + Page findByLocationWithin(GeoPoint point, String distance, Pageable pageable); + + Page findByLocationWithin(Point point, Distance distance, Pageable pageable); + + Page findByLocationNear(GeoBox box, Pageable pageable); + + Page findByLocationNear(Box box, Pageable pageable); + + Page findByLocationNear(Point point, Distance distance, Pageable pageable); + + Page findByLocationNear(GeoPoint point, String distance, Pageable pageable); + + Stream findByType(String type); + + long countByType(String type); + + long countByTypeNot(String type); + + long countByAvailable(boolean available); + + long countByRateLessThan(int rate); + + long countByRateBefore(int rate); + + long countByRateAfter(int rate); + + long countByMessageLike(String message); + + long countByMessageStartingWith(String message); + + long countByMessageEndingWith(String message); + + long countByMessageContaining(String message); + + long countByIdIn(List ids); + + long countByIdNotIn(List ids); + + long countByAvailableTrue(); + + long countByAvailableFalse(); + + long countByLocationWithin(GeoPoint point, String distance); + + long countByLocationWithin(Point point, Distance distance); + + long countByLocationNear(GeoBox box); + + long countByLocationNear(Box box); + + long countByLocationNear(Point point, Distance distance); + + long countByLocationNear(GeoPoint point, String distance); + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryRestTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryRestTests.java similarity index 57% rename from src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryRestTests.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryRestTests.java index c969ba8fb..205fcf74c 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryRestTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryRestTests.java @@ -13,21 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repositories; +package org.springframework.data.elasticsearch.repositories.custommethod; -import org.elasticsearch.client.RestHighLevelClient; import org.junit.Before; import org.junit.runner.RunWith; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; -import org.springframework.data.elasticsearch.entities.SampleEntity; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; /** * @author Don Wellington * @author Mark Paluch + * @author Peter-Josef Meisch */ @RunWith(SpringRunner.class) @ContextConfiguration("classpath:custom-method-repository-rest-test.xml") @@ -37,23 +36,7 @@ public class CustomMethodRepositoryRestTests extends CustomMethodRepositoryBaseT @Before public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); - elasticsearchTemplate.createIndex(SampleEntity.class); - elasticsearchTemplate.putMapping(SampleEntity.class); - elasticsearchTemplate.refresh(SampleEntity.class); - } - /** - * Workaround because {@link SampleEntity} is used like everywhere and there's little chance to find the place where - * the mapping is altered so that it becomes incompatible with the one created on repository startup. - *

- * TODO: Remove me once the cause is fixed! See: https://jira.spring.io/browse/DATAES-576 - */ - public static class CleanupOnStartElasticsearchTemplate extends ElasticsearchRestTemplate { - - public CleanupOnStartElasticsearchTemplate(RestHighLevelClient client) { - super(client); - deleteIndex(SampleEntity.class); - } + IndexInitializer.init(elasticsearchTemplate, SampleEntity.class); } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryTests.java similarity index 58% rename from src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryTests.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryTests.java index 17d10a8dc..ca1c5053f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/custommethod/CustomMethodRepositoryTests.java @@ -13,21 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repositories; +package org.springframework.data.elasticsearch.repositories.custommethod; -import org.elasticsearch.client.Client; import org.junit.Before; import org.junit.runner.RunWith; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.SampleEntity; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; /** * @author Don Wellington * @author Mark Paluch + * @author Peter-Josef Meisch */ @RunWith(SpringRunner.class) @ContextConfiguration("classpath:custom-method-repository-test.xml") @@ -37,23 +36,7 @@ public class CustomMethodRepositoryTests extends CustomMethodRepositoryBaseTests @Before public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); - elasticsearchTemplate.createIndex(SampleEntity.class); - elasticsearchTemplate.putMapping(SampleEntity.class); - elasticsearchTemplate.refresh(SampleEntity.class); - } - /** - * Workaround because {@link SampleEntity} is used like everywhere and there's little chance to find the place where - * the mapping is altered so that it becomes incompatible with the one created on repository startup. - *

- * TODO: Remove me once the cause is fixed! See: https://jira.spring.io/browse/DATAES-576 - */ - static class CleanupOnStartElasticsearchTemplate extends ElasticsearchTemplate { - - public CleanupOnStartElasticsearchTemplate(Client client) { - super(client); - deleteIndex(SampleEntity.class); - } + IndexInitializer.init(elasticsearchTemplate, SampleEntity.class); } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepository.java deleted file mode 100644 index 3e0c15d7a..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepository.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2013-2019 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.repositories.doubleid; - -import org.springframework.data.elasticsearch.entities.DoubleIDEntity; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; - -/** - * @author Ryan Henszey - * @author Mohsin Husen - */ - -public interface DoubleIDRepository extends ElasticsearchRepository { - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/DoubleIDRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepositoryTests.java similarity index 61% rename from src/test/java/org/springframework/data/elasticsearch/repository/support/DoubleIDRepositoryTests.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepositoryTests.java index 00d3e9773..1585ff806 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/DoubleIDRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/doubleid/DoubleIDRepositoryTests.java @@ -13,22 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repository.support; +package org.springframework.data.elasticsearch.repositories.doubleid; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Arrays; import java.util.Optional; import org.apache.commons.lang.math.RandomUtils; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +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.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.DoubleIDEntity; -import org.springframework.data.elasticsearch.repositories.doubleid.DoubleIDRepository; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -37,6 +40,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Mohsin Husen * @author Mark Paluch * @author Christoph Strobl + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/double-id-repository-test.xml") @@ -48,14 +52,19 @@ public class DoubleIDRepositoryTests { @Before public void before() { + + IndexInitializer.init(elasticsearchTemplate, DoubleIDEntity.class); + } + + @After + public void after() { + elasticsearchTemplate.deleteIndex(DoubleIDEntity.class); - elasticsearchTemplate.createIndex(DoubleIDEntity.class); - elasticsearchTemplate.putMapping(DoubleIDEntity.class); - elasticsearchTemplate.refresh(DoubleIDEntity.class); } @Test public void shouldDoBulkIndexDocument() { + // given Double documentId1 = RandomUtils.nextDouble(); DoubleIDEntity sampleEntity1 = new DoubleIDEntity(); @@ -71,26 +80,83 @@ public class DoubleIDRepositoryTests { // when repository.saveAll(Arrays.asList(sampleEntity1, sampleEntity2)); + // then Optional entity1FromElasticSearch = repository.findById(documentId1); - assertThat(entity1FromElasticSearch.isPresent(), is(true)); + assertThat(entity1FromElasticSearch).isPresent(); Optional entity2FromElasticSearch = repository.findById(documentId2); - assertThat(entity2FromElasticSearch.isPresent(), is(true)); + assertThat(entity2FromElasticSearch).isPresent(); } @Test public void shouldSaveDocument() { + // given Double documentId = RandomUtils.nextDouble(); DoubleIDEntity sampleEntity = new DoubleIDEntity(); sampleEntity.setId(documentId); sampleEntity.setMessage("some message"); sampleEntity.setVersion(System.currentTimeMillis()); + // when repository.save(sampleEntity); + // then Optional entityFromElasticSearch = repository.findById(documentId); - assertThat(entityFromElasticSearch.isPresent(), is(true)); + assertThat(entityFromElasticSearch).isPresent(); } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + + @Document(indexName = "test-index-double-keyed-entity", type = "double-keyed-entity", shards = 1, replicas = 0, + refreshInterval = "-1") + static class DoubleIDEntity { + + @Id private Double id; + private String type; + private String message; + @Version private Long version; + + public Double getId() { + return id; + } + + public void setId(Double id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Long getVersion() { + return version; + } + + public void setVersion(Long version) { + this.version = version; + } + } + + /** + * @author Ryan Henszey + * @author Mohsin Husen + */ + interface DoubleIDRepository extends ElasticsearchRepository {} } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseEntity.java b/src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseEntity.java deleted file mode 100644 index e31a58049..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseEntity.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.springframework.data.elasticsearch.repositories.existing.index; - -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; - -/** - * CreateIndexFalseEntity - * - * @author Mason Chan - */ - -@Document(indexName = "test-index-not-create", type = "test-type", createIndex = false) -public class CreateIndexFalseEntity { - @Id - private String id; - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseRepository.java deleted file mode 100644 index 035ad20e8..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseRepository.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.springframework.data.elasticsearch.repositories.existing.index; - -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; - -/** - * Created by akonczak on 16/12/2015. - */ -public interface CreateIndexFalseRepository extends ElasticsearchRepository { - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseRepositoryTests.java deleted file mode 100644 index c5bcb7e67..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/existing/index/CreateIndexFalseRepositoryTests.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.springframework.data.elasticsearch.repositories.existing.index; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:/existing-index-repository-test.xml") -public class CreateIndexFalseRepositoryTests { - - @Autowired - private CreateIndexFalseRepository repository; - - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - - - /* - DATAES-143 - */ - @Test - public void shouldNotCreateIndex() { - //given - - //when - //then - assertFalse(elasticsearchTemplate.indexExists(CreateIndexFalseEntity.class)); - } -} \ No newline at end of file diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepository.java deleted file mode 100644 index 4581ed030..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepository.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.springframework.data.elasticsearch.repositories.geo; - -import org.springframework.data.elasticsearch.entities.GeoEntity; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; - -/** - * Created by akonczak on 22/11/2015. - */ -public interface SpringDataGeoRepository extends ElasticsearchRepository { - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepositoryTests.java index 2a0e49dd8..5d4e25524 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/geo/SpringDataGeoRepositoryTests.java @@ -15,8 +15,13 @@ */ package org.springframework.data.elasticsearch.repositories.geo; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import java.util.Locale; import java.util.Optional; @@ -25,16 +30,24 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +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.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.geo.GeoPoint; -import org.springframework.data.elasticsearch.entities.GeoEntity; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.data.elasticsearch.utils.IndexInitializer; +import org.springframework.data.geo.Box; +import org.springframework.data.geo.Circle; import org.springframework.data.geo.Point; +import org.springframework.data.geo.Polygon; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Mark Paluch * @author Christoph Strobl + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/repository-spring-data-geo-support.xml") @@ -46,32 +59,32 @@ public class SpringDataGeoRepositoryTests { @Before public void init() { - template.deleteIndex(GeoEntity.class); - template.createIndex(GeoEntity.class); - template.putMapping(GeoEntity.class); - template.refresh(GeoEntity.class); + + IndexInitializer.init(template, GeoEntity.class); } @Test public void shouldSaveAndLoadGeoPoints() { + // given final Point point = new Point(15, 25); GeoEntity entity = GeoEntity.builder().pointA(point).pointB(new GeoPoint(point.getX(), point.getY())) .pointC(toGeoString(point)).pointD(toGeoArray(point)).build(); + // when GeoEntity saved = repository.save(entity); Optional result = repository.findById(entity.getId()); - // then - assertThat(result.isPresent(), is(true)); + // then + assertThat(result).isPresent(); result.ifPresent(geoEntity -> { - assertThat(saved.getPointA().getX(), is(geoEntity.getPointA().getX())); - assertThat(saved.getPointA().getY(), is(geoEntity.getPointA().getY())); - assertThat(saved.getPointB().getLat(), is(geoEntity.getPointB().getLat())); - assertThat(saved.getPointB().getLon(), is(geoEntity.getPointB().getLon())); - assertThat(saved.getPointC(), is(geoEntity.getPointC())); - assertThat(saved.getPointD(), is(geoEntity.getPointD())); + assertThat(saved.getPointA().getX()).isEqualTo(geoEntity.getPointA().getX()); + assertThat(saved.getPointA().getY()).isEqualTo(geoEntity.getPointA().getY()); + assertThat(saved.getPointB().getLat()).isEqualTo(geoEntity.getPointB().getLat()); + assertThat(saved.getPointB().getLon()).isEqualTo(geoEntity.getPointB().getLon()); + assertThat(saved.getPointC()).isEqualTo(geoEntity.getPointC()); + assertThat(saved.getPointD()).isEqualTo(geoEntity.getPointD()); }); } @@ -82,4 +95,37 @@ public class SpringDataGeoRepositoryTests { private double[] toGeoArray(Point point) { return new double[] { point.getX(), point.getY() }; } + + /** + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-geo-repository", type = "geo-test-index", shards = 1, replicas = 0, refreshInterval = "-1") + static class GeoEntity { + + @Id private String id; + + // geo shape - Spring Data + private Box box; + private Circle circle; + private Polygon polygon; + + // geo point - Custom implementation + Spring Data + @GeoPointField private Point pointA; + + private GeoPoint pointB; + + @GeoPointField private String pointC; + + @GeoPointField private double[] pointD; + } + + /** + * Created by akonczak on 22/11/2015. + */ + interface SpringDataGeoRepository extends ElasticsearchRepository {} } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepository.java deleted file mode 100644 index 0f6b77db2..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepository.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2013-2019 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.repositories.integer; - -import org.springframework.data.elasticsearch.entities.IntegerIDEntity; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; - -/** - * @author Ryan Henszey - * @author Mohsin Husen - */ - -public interface IntegerIDRepository extends ElasticsearchRepository { - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/IntegerIDRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepositoryTests.java similarity index 62% rename from src/test/java/org/springframework/data/elasticsearch/repository/support/IntegerIDRepositoryTests.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepositoryTests.java index 5048cfc83..6f84389c8 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/IntegerIDRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/integer/IntegerIDRepositoryTests.java @@ -13,10 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repository.support; +package org.springframework.data.elasticsearch.repositories.integer; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.Arrays; import java.util.Optional; @@ -26,9 +25,12 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +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.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.IntegerIDEntity; -import org.springframework.data.elasticsearch.repositories.integer.IntegerIDRepository; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -37,6 +39,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Mohsin Husen * @author Mark Paluch * @author Christoph Strobl + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/integer-id-repository-test.xml") @@ -48,14 +51,13 @@ public class IntegerIDRepositoryTests { @Before public void before() { - elasticsearchTemplate.deleteIndex(IntegerIDEntity.class); - elasticsearchTemplate.createIndex(IntegerIDEntity.class); - elasticsearchTemplate.putMapping(IntegerIDEntity.class); - elasticsearchTemplate.refresh(IntegerIDEntity.class); + + IndexInitializer.init(elasticsearchTemplate, IntegerIDEntity.class); } @Test public void shouldDoBulkIndexDocument() { + // given Integer documentId1 = RandomUtils.nextInt(); IntegerIDEntity sampleEntity1 = new IntegerIDEntity(); @@ -71,26 +73,84 @@ public class IntegerIDRepositoryTests { // when repository.saveAll(Arrays.asList(sampleEntity1, sampleEntity2)); + // then Optional entity1FromElasticSearch = repository.findById(documentId1); - assertThat(entity1FromElasticSearch.isPresent(), is(true)); + assertThat(entity1FromElasticSearch).isPresent(); Optional entity2FromElasticSearch = repository.findById(documentId2); - assertThat(entity2FromElasticSearch.isPresent(), is(true)); + assertThat(entity2FromElasticSearch).isPresent(); } @Test public void shouldSaveDocument() { + // given Integer documentId = RandomUtils.nextInt(); IntegerIDEntity sampleEntity = new IntegerIDEntity(); sampleEntity.setId(documentId); sampleEntity.setMessage("some message"); sampleEntity.setVersion(System.currentTimeMillis()); + // when repository.save(sampleEntity); + // then Optional entityFromElasticSearch = repository.findById(documentId); - assertThat(entityFromElasticSearch.isPresent(), is(true)); + assertThat(entityFromElasticSearch).isPresent(); } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + + @Document(indexName = "test-index-integer-keyed-entity", type = "integer-keyed-entity", shards = 1, replicas = 0, + refreshInterval = "-1") + static class IntegerIDEntity { + + @Id private Integer id; + private String type; + private String message; + @Version private Long version; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Long getVersion() { + return version; + } + + public void setVersion(Long version) { + this.version = version; + } + } + + /** + * @author Ryan Henszey + * @author Mohsin Husen + */ + + interface IntegerIDRepository extends ElasticsearchRepository {} } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/nestedobject/InnerObjectTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/nestedobject/InnerObjectTests.java new file mode 100644 index 000000000..2f5f2a9fc --- /dev/null +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/nestedobject/InnerObjectTests.java @@ -0,0 +1,137 @@ +/* + * Copyright 2014-2019 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.repositories.nestedobject; + +import static org.apache.commons.lang.RandomStringUtils.*; +import static org.assertj.core.api.Assertions.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +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.annotations.InnerField; +import org.springframework.data.elasticsearch.annotations.MultiField; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.data.elasticsearch.utils.IndexInitializer; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Mohsin Husen + * @author Christoph Strobl + * @author Peter-Josef Meisch + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:/repository-test-nested-object-books.xml") +public class InnerObjectTests { + + @Autowired private SampleElasticSearchBookRepository bookRepository; + + @Autowired private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + + IndexInitializer.init(elasticsearchTemplate, Book.class); + } + + @Test + public void shouldIndexInnerObject() { + + // given + String id = randomAlphanumeric(5); + Book book = new Book(); + book.setId(id); + book.setName("xyz"); + Author author = new Author(); + author.setId("1"); + author.setName("ABC"); + book.setAuthor(author); + + // when + bookRepository.save(book); + + // then + assertThat(bookRepository.findById(id)).isNotNull(); + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Nordine Bittich + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-book", type = "book", shards = 1, replicas = 0, refreshInterval = "-1") + static class Book { + + @Id private String id; + private String name; + @Field(type = FieldType.Object) private Author author; + @Field(type = FieldType.Nested) private Map> buckets = new HashMap<>(); + @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"), + otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop", + searchAnalyzer = "standard") }) private String description; + } + + public interface SampleElasticSearchBookRepository extends ElasticsearchRepository {} + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class Author { + + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + +} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/nondocument/NonDocumentEntityRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/nondocument/NonDocumentEntityRepository.java deleted file mode 100644 index b426ed7ed..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/nondocument/NonDocumentEntityRepository.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2013-2019 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.repositories.nondocument; - -import org.springframework.context.annotation.Lazy; -import org.springframework.data.elasticsearch.entities.NonDocumentEntity; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; - -/** - * @author Rizwan Idrees - * @author Mohsin Husen - * @author Oliver Gierke - */ -@Lazy -public interface NonDocumentEntityRepository extends ElasticsearchRepository { - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/NonDocumentEntityTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/nondocument/NonDocumentEntityTests.java similarity index 54% rename from src/test/java/org/springframework/data/elasticsearch/NonDocumentEntityTests.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/nondocument/NonDocumentEntityTests.java index 0699cedd0..8486731e1 100644 --- a/src/test/java/org/springframework/data/elasticsearch/NonDocumentEntityTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/nondocument/NonDocumentEntityTests.java @@ -13,16 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch; +package org.springframework.data.elasticsearch.repositories.nondocument; import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; +import org.springframework.context.annotation.Lazy; import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.data.elasticsearch.repositories.nondocument.NonDocumentEntityRepository; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * @author Rizwan Idrees * @author Mohsin Husen + * @author Peter-Josef Meisch */ public class NonDocumentEntityTests { @@ -32,4 +35,40 @@ public class NonDocumentEntityTests { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/repository-non-document-entity.xml"); ctx.getBean(NonDocumentEntityRepository.class); } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class NonDocumentEntity { + + @Id private String someId; + private String someField1; + private String someField2; + + public String getSomeField1() { + return someField1; + } + + public void setSomeField1(String someField1) { + this.someField1 = someField1; + } + + public String getSomeField2() { + return someField2; + } + + public void setSomeField2(String someField2) { + this.someField2 = someField2; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Oliver Gierke + */ + @Lazy + interface NonDocumentEntityRepository extends ElasticsearchRepository {} + } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/query/ProductRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/query/ProductRepository.java deleted file mode 100644 index 57c07b67e..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/query/ProductRepository.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.springframework.data.elasticsearch.repositories.query; - -import java.util.List; - -import org.springframework.data.elasticsearch.entities.Product; -import org.springframework.data.repository.PagingAndSortingRepository; - -/** - * Created by akonczak on 04/09/15. - */ -public interface ProductRepository extends PagingAndSortingRepository { - - public List findByNameAndText(String name, String text); - - public List findByNameAndPrice(String name, Float price); - - public List findByNameOrText(String name, String text); - - public List findByNameOrPrice(String name, Float price); - - - public List findByAvailableTrue(); - - public List findByAvailableFalse(); - - public List findByPriceIn(List floats); - - public List findByPriceNotIn(List floats); - - public List findByPriceNot(float v); - - public List findByPriceBetween(float v, float v1); - - public List findByPriceLessThan(float v); - - public List findByPriceLessThanEqual(float v); - - public List findByPriceGreaterThan(float v); - - public List findByPriceGreaterThanEqual(float v); - - public List findByIdNotIn(List strings); -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/DynamicSettingAndMappingEntityRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/DynamicSettingAndMappingEntityRepository.java deleted file mode 100644 index 955f8af2e..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/DynamicSettingAndMappingEntityRepository.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2014-2019 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.repositories.setting; - -import org.springframework.data.elasticsearch.entities.DynamicSettingAndMappingEntity; -import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; - -/** - * DynamicSettingAndMappingEntityRepository - * - * @author Mohsin Husen - */ -public interface DynamicSettingAndMappingEntityRepository extends ElasticsearchCrudRepository { - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/DynamicSettingAndMappingEntityRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/DynamicSettingAndMappingEntityRepositoryTests.java deleted file mode 100644 index b99e258ab..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/DynamicSettingAndMappingEntityRepositoryTests.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright 2014-2019 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.repositories.setting; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang.RandomStringUtils; -import org.elasticsearch.index.query.QueryBuilders; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; -import org.springframework.data.elasticsearch.core.query.SearchQuery; -import org.springframework.data.elasticsearch.entities.DynamicSettingAndMappingEntity; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * DynamicSettingAndMappingEntityRepositoryTests - * - * @author Mohsin Husen - * @author Ilkang Na - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:dynamic-settings-test.xml") -public class DynamicSettingAndMappingEntityRepositoryTests { - - @Autowired - private DynamicSettingAndMappingEntityRepository repository; - - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before() { - elasticsearchTemplate.deleteIndex(DynamicSettingAndMappingEntity.class); - elasticsearchTemplate.createIndex(DynamicSettingAndMappingEntity.class); - elasticsearchTemplate.putMapping(DynamicSettingAndMappingEntity.class); - elasticsearchTemplate.refresh(DynamicSettingAndMappingEntity.class); - } - - /* - DATAES-64 - */ - @Test - public void shouldCreateGivenDynamicSettingsForGivenIndex() { - //given - //delete , create and apply mapping in before method - - // then - assertThat(elasticsearchTemplate.indexExists(DynamicSettingAndMappingEntity.class), is(true)); - Map map = elasticsearchTemplate.getSetting(DynamicSettingAndMappingEntity.class); - assertThat(map.containsKey("index.number_of_replicas"), is(true)); - assertThat(map.containsKey("index.number_of_shards"), is(true)); - assertThat(map.containsKey("index.analysis.analyzer.emailAnalyzer.tokenizer"), is(true)); - assertThat((String) map.get("index.number_of_replicas"), is("0")); - assertThat((String) map.get("index.number_of_shards"), is("1")); - assertThat((String) map.get("index.analysis.analyzer.emailAnalyzer.tokenizer"), is("uax_url_email")); - } - - /* - DATAES-64 - */ - @Test - public void shouldSearchOnGivenTokenizerUsingGivenDynamicSettingsForGivenIndex() { - //given - DynamicSettingAndMappingEntity dynamicSettingAndMappingEntity1 = new DynamicSettingAndMappingEntity(); - dynamicSettingAndMappingEntity1.setId(RandomStringUtils.randomNumeric(5)); - dynamicSettingAndMappingEntity1.setName("test-setting1"); - dynamicSettingAndMappingEntity1.setEmail("test_setting1@test.com"); - - repository.save(dynamicSettingAndMappingEntity1); - - DynamicSettingAndMappingEntity dynamicSettingAndMappingEntity2 = new DynamicSettingAndMappingEntity(); - dynamicSettingAndMappingEntity2.setId(RandomStringUtils.randomNumeric(5)); - dynamicSettingAndMappingEntity2.setName("test-setting2"); - dynamicSettingAndMappingEntity2.setEmail("test_setting2@test.com"); - - repository.save(dynamicSettingAndMappingEntity2); - - //when - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(QueryBuilders.termQuery("email", dynamicSettingAndMappingEntity1.getEmail())).build(); - - long count = elasticsearchTemplate.count(searchQuery, DynamicSettingAndMappingEntity.class); - List entityList = elasticsearchTemplate.queryForList(searchQuery, DynamicSettingAndMappingEntity.class); - - //then - assertThat(count, is(1L)); - assertThat(entityList, is(notNullValue())); - assertThat(entityList.size(), is(1)); - assertThat(entityList.get(0).getEmail(), is(dynamicSettingAndMappingEntity1.getEmail())); - } - - @Test - public void shouldGetMappingForGivenIndexAndType() { - //given - //delete , create and apply mapping in before method - //when - Map mapping = elasticsearchTemplate.getMapping(DynamicSettingAndMappingEntity.class); - //then - Map properties = (Map) mapping.get("properties"); - assertThat(mapping, is(notNullValue())); - assertThat(properties, is(notNullValue())); - assertThat(((String) ((Map) properties.get("email")).get("type")), is("text")); - assertThat((String) ((Map) properties.get("email")).get("analyzer"), is("emailAnalyzer")); - } - - @Test - public void shouldCreateMappingWithSpecifiedMappings() { - //given - elasticsearchTemplate.deleteIndex(DynamicSettingAndMappingEntity.class); - elasticsearchTemplate.createIndex(DynamicSettingAndMappingEntity.class); - elasticsearchTemplate.refresh(DynamicSettingAndMappingEntity.class); - //when - String mappings = "{\n" + - " \"test-setting-type\" : {\n" + - " \"properties\" : {\n" + - " \"email\" : {\"type\" : \"text\", \"analyzer\" : \"emailAnalyzer\" }\n" + - " }\n" + - " }\n" + - "}"; - elasticsearchTemplate.putMapping(DynamicSettingAndMappingEntity.class, mappings); - elasticsearchTemplate.refresh(DynamicSettingAndMappingEntity.class); - //then - Map mapping = elasticsearchTemplate.getMapping(DynamicSettingAndMappingEntity.class); - Map properties = (Map) mapping.get("properties"); - assertThat(mapping, is(notNullValue())); - assertThat(properties, is(notNullValue())); - assertThat(((String) ((Map) properties.get("email")).get("type")), is("text")); - assertThat((String) ((Map) properties.get("email")).get("analyzer"), is("emailAnalyzer")); - } - - /* - DATAES-86 - */ - @Test - public void shouldCreateMappingWithUsingMappingAnnotation() { - //given - - //then - Map mapping = elasticsearchTemplate.getMapping(DynamicSettingAndMappingEntity.class); - Map properties = (Map) mapping.get("properties"); - assertThat(mapping, is(notNullValue())); - assertThat(properties, is(notNullValue())); - assertThat(((String) ((Map) properties.get("email")).get("type")), is("text")); - assertThat((String) ((Map) properties.get("email")).get("analyzer"), is("emailAnalyzer")); - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/FieldDynamicMappingEntityRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/FieldDynamicMappingEntityRepository.java deleted file mode 100644 index 65aa70b47..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/FieldDynamicMappingEntityRepository.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2014-2019 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.repositories.setting; - -import org.springframework.data.elasticsearch.entities.FieldDynamicMappingEntity; -import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; - -/** - * FieldDynamicMappingEntityRepository - * - * @author Ted Liang - */ -public interface FieldDynamicMappingEntityRepository extends ElasticsearchCrudRepository { - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/FieldDynamicMappingEntityRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/FieldDynamicMappingEntityRepositoryTests.java deleted file mode 100644 index 8553025f6..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/FieldDynamicMappingEntityRepositoryTests.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2014-2019 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.repositories.setting; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.FieldDynamicMappingEntity; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * FieldDynamicMappingEntityRepositoryTests - * - * @author Ted Liang - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:dynamic-settings-test.xml") -public class FieldDynamicMappingEntityRepositoryTests { - - @Autowired - private FieldDynamicMappingEntityRepository repository; - - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before() { - elasticsearchTemplate.deleteIndex(FieldDynamicMappingEntity.class); - elasticsearchTemplate.createIndex(FieldDynamicMappingEntity.class); - elasticsearchTemplate.putMapping(FieldDynamicMappingEntity.class); - elasticsearchTemplate.refresh(FieldDynamicMappingEntity.class); - } - - /* - DATAES-209 - */ - @Test - public void shouldCreateMappingWithMappingAnnotationAtFieldLevel() { - //given - - //then - Map mapping = elasticsearchTemplate.getMapping(FieldDynamicMappingEntity.class); - assertThat(mapping, is(notNullValue())); - - Map properties = (Map) mapping.get("properties"); - assertThat(properties, is(notNullValue())); - - assertThat(properties.containsKey("file"), is(true)); - Map file = (Map) properties.get("file"); - assertThat(file, is(notNullValue())); - assertThat(((String) file.get("type")), is("text")); - - assertThat(file.containsKey("fields"), is(true)); - Map fields = (Map) file.get("fields"); - assertThat(fields, is(notNullValue())); - - assertThat(fields.containsKey("content"), is(true)); - Map content = (Map) fields.get("content"); - assertThat(content, is(notNullValue())); - - assertThat((String)content.get("type"), is("text")); - assertThat((String)content.get("term_vector"), is("with_positions_offsets")); - assertThat((Boolean)content.get("store"), is(Boolean.TRUE)); - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/dynamic/DynamicSettingAndMappingEntityRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/dynamic/DynamicSettingAndMappingEntityRepositoryTests.java new file mode 100644 index 000000000..7333e0075 --- /dev/null +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/dynamic/DynamicSettingAndMappingEntityRepositoryTests.java @@ -0,0 +1,216 @@ +/* + * Copyright 2014-2019 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.repositories.setting.dynamic; + +import static org.assertj.core.api.Assertions.*; + +import java.util.List; +import java.util.Map; + +import org.apache.commons.lang.RandomStringUtils; +import org.elasticsearch.index.query.QueryBuilders; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Mapping; +import org.springframework.data.elasticsearch.annotations.Setting; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; +import org.springframework.data.elasticsearch.core.query.SearchQuery; +import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; +import org.springframework.data.elasticsearch.utils.IndexInitializer; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * DynamicSettingAndMappingEntityRepositoryTests + * + * @author Mohsin Husen + * @author Ilkang Na + * @author Peter-Josef Meisch + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:dynamic-settings-test.xml") +public class DynamicSettingAndMappingEntityRepositoryTests { + + @Autowired private DynamicSettingAndMappingEntityRepository repository; + + @Autowired private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + + IndexInitializer.init(elasticsearchTemplate, DynamicSettingAndMappingEntity.class); + } + + @Test // DATAES-64 + public void shouldCreateGivenDynamicSettingsForGivenIndex() { + + // given + // delete , create and apply mapping in before method + + // then + assertThat(elasticsearchTemplate.indexExists(DynamicSettingAndMappingEntity.class)).isTrue(); + Map map = elasticsearchTemplate.getSetting(DynamicSettingAndMappingEntity.class); + 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(); + assertThat(map.get("index.number_of_replicas")).isEqualTo("0"); + assertThat(map.get("index.number_of_shards")).isEqualTo("1"); + assertThat(map.get("index.analysis.analyzer.emailAnalyzer.tokenizer")).isEqualTo("uax_url_email"); + } + + @Test // DATAES-64 + public void shouldSearchOnGivenTokenizerUsingGivenDynamicSettingsForGivenIndex() { + + // given + DynamicSettingAndMappingEntity dynamicSettingAndMappingEntity1 = new DynamicSettingAndMappingEntity(); + dynamicSettingAndMappingEntity1.setId(RandomStringUtils.randomNumeric(5)); + dynamicSettingAndMappingEntity1.setName("test-setting1"); + dynamicSettingAndMappingEntity1.setEmail("test_setting1@Test.com"); + + repository.save(dynamicSettingAndMappingEntity1); + + DynamicSettingAndMappingEntity dynamicSettingAndMappingEntity2 = new DynamicSettingAndMappingEntity(); + dynamicSettingAndMappingEntity2.setId(RandomStringUtils.randomNumeric(5)); + dynamicSettingAndMappingEntity2.setName("test-setting2"); + dynamicSettingAndMappingEntity2.setEmail("test_setting2@Test.com"); + + repository.save(dynamicSettingAndMappingEntity2); + + // when + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(QueryBuilders.termQuery("email", dynamicSettingAndMappingEntity1.getEmail())).build(); + + long count = elasticsearchTemplate.count(searchQuery, DynamicSettingAndMappingEntity.class); + List entityList = elasticsearchTemplate.queryForList(searchQuery, + DynamicSettingAndMappingEntity.class); + + // then + assertThat(count).isEqualTo(1L); + assertThat(entityList).isNotNull().hasSize(1); + assertThat(entityList.get(0).getEmail()).isEqualTo(dynamicSettingAndMappingEntity1.getEmail()); + } + + @Test + public void shouldGetMappingForGivenIndexAndType() { + + // given + // delete , create and apply mapping in before method + + // when + Map mapping = elasticsearchTemplate.getMapping(DynamicSettingAndMappingEntity.class); + + // then + Map properties = (Map) mapping.get("properties"); + assertThat(mapping).isNotNull(); + assertThat(properties).isNotNull(); + Map emailProperties = (Map) properties.get("email"); + assertThat(emailProperties.get("type")).isEqualTo("text"); + assertThat(emailProperties.get("analyzer")).isEqualTo("emailAnalyzer"); + } + + @Test + public void shouldCreateMappingWithSpecifiedMappings() { + + // given + elasticsearchTemplate.deleteIndex(DynamicSettingAndMappingEntity.class); + elasticsearchTemplate.createIndex(DynamicSettingAndMappingEntity.class); + elasticsearchTemplate.refresh(DynamicSettingAndMappingEntity.class); + + // when + String mappings = "{\n" + // + " \"test-setting-type\" : {\n" + // + " \"properties\" : {\n" + // + " \"email\" : {\"type\" : \"text\", \"analyzer\" : \"emailAnalyzer\" }\n" + // + " }\n" + // + " }\n" + // + "}"; + elasticsearchTemplate.putMapping(DynamicSettingAndMappingEntity.class, mappings); + elasticsearchTemplate.refresh(DynamicSettingAndMappingEntity.class); + + // then + Map mapping = elasticsearchTemplate.getMapping(DynamicSettingAndMappingEntity.class); + Map properties = (Map) mapping.get("properties"); + assertThat(mapping).isNotNull(); + assertThat(properties).isNotNull(); + Map emailProperties = (Map) properties.get("email"); + assertThat(emailProperties.get("type")).isEqualTo("text"); + assertThat(emailProperties.get("analyzer")).isEqualTo("emailAnalyzer"); + } + + @Test // DATAES-86 + public void shouldCreateMappingWithUsingMappingAnnotation() { + + // given + + // then + Map mapping = elasticsearchTemplate.getMapping(DynamicSettingAndMappingEntity.class); + Map properties = (Map) mapping.get("properties"); + assertThat(mapping).isNotNull(); + assertThat(properties).isNotNull(); + Map emailProperties = (Map) properties.get("email"); + assertThat(emailProperties.get("type")).isEqualTo("text"); + assertThat(emailProperties.get("analyzer")).isEqualTo("emailAnalyzer"); + } + + /** + * @author Mohsin Husen + */ + @Document(indexName = "test-index-dynamic-setting-and-mapping", type = "test-setting-type") + @Setting(settingPath = "/settings/test-settings.json") + @Mapping(mappingPath = "/mappings/test-mappings.json") + static class DynamicSettingAndMappingEntity { + + @Id private String id; + private String name; + private String email; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + } + + /** + * @author Mohsin Husen + */ + public interface DynamicSettingAndMappingEntityRepository + extends ElasticsearchCrudRepository {} + +} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/setting/fielddynamic/FieldDynamicMappingEntityRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/fielddynamic/FieldDynamicMappingEntityRepositoryTests.java new file mode 100644 index 000000000..ba140d08c --- /dev/null +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/setting/fielddynamic/FieldDynamicMappingEntityRepositoryTests.java @@ -0,0 +1,119 @@ +/* + * Copyright 2014-2019 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.repositories.setting.fielddynamic; + +import static org.assertj.core.api.Assertions.*; + +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.data.annotation.Id; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Mapping; +import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; +import org.springframework.data.elasticsearch.utils.IndexInitializer; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * FieldDynamicMappingEntityRepositoryTests + * + * @author Ted Liang + * @author Peter-Josef Meisch + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:field-dynamic-settings-test.xml") +public class FieldDynamicMappingEntityRepositoryTests { + + @Autowired private FieldDynamicMappingEntityRepository repository; + + @Autowired private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + + IndexInitializer.init(elasticsearchTemplate, FieldDynamicMappingEntity.class); + } + + @Test // DATAES-209 + public void shouldCreateMappingWithMappingAnnotationAtFieldLevel() { + + // given + + // then + Map mapping = elasticsearchTemplate.getMapping(FieldDynamicMappingEntity.class); + assertThat(mapping).isNotNull(); + + Map properties = (Map) mapping.get("properties"); + assertThat(properties).isNotNull(); + + assertThat(properties.containsKey("file")).isTrue(); + Map file = (Map) properties.get("file"); + assertThat(file).isNotNull(); + assertThat(file.get("type")).isEqualTo("text"); + + assertThat(file.containsKey("fields")).isTrue(); + Map fields = (Map) file.get("fields"); + assertThat(fields).isNotNull(); + + assertThat(fields.containsKey("content")).isTrue(); + Map content = (Map) fields.get("content"); + assertThat(content).isNotNull(); + + assertThat(content.get("type")).isEqualTo("text"); + assertThat(content.get("term_vector")).isEqualTo("with_positions_offsets"); + assertThat((Boolean) content.get("store")).isTrue(); + } + + /** + * @author Ted Liang + */ + @Document(indexName = "test-index-field-dynamic-mapping", type = "test-field-mapping-type") + static class FieldDynamicMappingEntity { + + @Id + private String id; + + @Mapping(mappingPath = "/mappings/test-field-mappings.json") + private byte[] file; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public byte[] getFile() { + return file; + } + + public void setFile(byte[] file) { + this.file = file; + } + } + + /** + * @author Ted Liang + */ + public interface FieldDynamicMappingEntityRepository extends ElasticsearchCrudRepository { } + +} diff --git a/src/test/java/org/springframework/data/elasticsearch/SpELEntityTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELEntityTests.java similarity index 62% rename from src/test/java/org/springframework/data/elasticsearch/SpELEntityTests.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELEntityTests.java index 69f0ea710..fe2d7f081 100644 --- a/src/test/java/org/springframework/data/elasticsearch/SpELEntityTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELEntityTests.java @@ -13,21 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch; +package org.springframework.data.elasticsearch.repositories.spel; -import static org.hamcrest.core.Is.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import org.elasticsearch.index.query.QueryBuilders; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; -import org.springframework.data.elasticsearch.entities.SpELEntity; -import org.springframework.data.elasticsearch.repositories.spel.SpELRepository; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -35,6 +35,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * SpELEntityTest * * @author Artur Konczak + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @@ -46,39 +47,63 @@ public class SpELEntityTests { @Autowired private ElasticsearchTemplate template; @Before - public void init() { - repository.deleteAll(); + public void before() { + + IndexInitializer.init(template, SpELEntity.class); } - @Ignore("DATAES-211") @Test public void shouldDo() { - // Given - repository.save(new SpELEntity()); - repository.save(new SpELEntity()); - // When - // Then + // given + repository.save(new SpELEntity()); + repository.save(new SpELEntity()); + + // when + + // then NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(QueryBuilders.matchAllQuery()); - nativeSearchQuery.addIndices("abz-entity"); + nativeSearchQuery.addIndices("test-index-abz-entity"); long count = template.count(nativeSearchQuery); - assertThat(count, is(2L)); + assertThat(count).isEqualTo(2); } - @Ignore("DATAES-211") @Test public void shouldSupportSpelInType() { - // Given + + // given SpELEntity spELEntity = new SpELEntity(); repository.save(spELEntity); - // When + // when - // Then + // then NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(QueryBuilders.matchAllQuery()); - nativeSearchQuery.addIndices("abz-entity"); + nativeSearchQuery.addIndices("test-index-abz-entity"); nativeSearchQuery.addTypes("myType"); long count = template.count(nativeSearchQuery); - assertThat(count, is(1L)); + assertThat(count).isEqualTo(1); } + + /** + * SpELEntity + * + * @author Artur Konczak + */ + @Document(indexName = "#{'test-index-abz'+'-'+'entity'}", type = "#{'my'+'Type'}", shards = 1, replicas = 0, + refreshInterval = "-1") + static class SpELEntity { + + @Id private String id; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + } + + interface SpELRepository extends ElasticsearchRepository {} } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELRepository.java deleted file mode 100644 index 6db05cee4..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/spel/SpELRepository.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2014-2019 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.repositories.spel; - -import org.springframework.data.elasticsearch.entities.SpELEntity; -import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; - -/** - * SpELRepository - * - * @author Artur Konczak - * - */ -public interface SpELRepository extends ElasticsearchRepository { - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepository.java deleted file mode 100644 index ddd52845a..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepository.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2014-2019 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.repositories.synonym; - -import org.springframework.data.elasticsearch.entities.SynonymEntity; -import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; - -/** - * SynonymRepository - * - * @author Artur Konczak - */ -public interface SynonymRepository extends ElasticsearchCrudRepository { - -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepositoryTests.java index 4fcd1da4a..bbc14f703 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/synonym/SynonymRepositoryTests.java @@ -15,8 +15,7 @@ */ package org.springframework.data.elasticsearch.repositories.synonym; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.*; import java.util.List; @@ -25,9 +24,14 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Mapping; +import org.springframework.data.elasticsearch.annotations.Setting; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; -import org.springframework.data.elasticsearch.entities.SynonymEntity; +import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -35,29 +39,26 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * SynonymRepositoryTests * * @author Artur Konczak + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:synonym-test.xml") public class SynonymRepositoryTests { - @Autowired - private SynonymRepository repository; + @Autowired private SynonymRepository repository; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { - elasticsearchTemplate.deleteIndex(SynonymEntity.class); - elasticsearchTemplate.createIndex(SynonymEntity.class); - elasticsearchTemplate.putMapping(SynonymEntity.class); - elasticsearchTemplate.refresh(SynonymEntity.class); - } + IndexInitializer.init(elasticsearchTemplate, SynonymEntity.class); + } @Test public void shouldDo() { - //given + + // given SynonymEntity entry1 = new SynonymEntity(); entry1.setText("Elizabeth is the english queen"); SynonymEntity entry2 = new SynonymEntity(); @@ -65,13 +66,50 @@ public class SynonymRepositoryTests { repository.save(entry1); repository.save(entry2); - //when - //then - assertThat(repository.count(),is(2L)); + // when - List synonymEntities = elasticsearchTemplate.queryForList(new NativeSearchQueryBuilder().withQuery(QueryBuilders.termQuery("text", "british")).build(), SynonymEntity.class); - assertThat(synonymEntities.size(), is(1)); + // then + assertThat(repository.count()).isEqualTo(2L); + + List synonymEntities = elasticsearchTemplate.queryForList( + new NativeSearchQueryBuilder().withQuery(QueryBuilders.termQuery("text", "british")).build(), + SynonymEntity.class); + assertThat(synonymEntities).hasSize(1); } + /** + * @author Mohsin Husen + */ + @Document(indexName = "test-index-synonym", type = "synonym-type") + @Setting(settingPath = "/synonyms/settings.json") + @Mapping(mappingPath = "/synonyms/mappings.json") + static class SynonymEntity { + + @Id private String id; + private String text; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + } + + /** + * SynonymRepository + * + * @author Artur Konczak + */ + interface SynonymRepository extends ElasticsearchCrudRepository {} } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/UUIDElasticsearchRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/uuidkeyed/UUIDElasticsearchRepositoryTests.java similarity index 77% rename from src/test/java/org/springframework/data/elasticsearch/repository/support/UUIDElasticsearchRepositoryTests.java rename to src/test/java/org/springframework/data/elasticsearch/repositories/uuidkeyed/UUIDElasticsearchRepositoryTests.java index 6e7a52dee..b75e41122 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/UUIDElasticsearchRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/uuidkeyed/UUIDElasticsearchRepositoryTests.java @@ -13,11 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repository.support; +package org.springframework.data.elasticsearch.repositories.uuidkeyed; +import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import java.util.ArrayList; import java.util.Arrays; @@ -30,15 +35,22 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Order; +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.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; -import org.springframework.data.elasticsearch.entities.SampleEntityUUIDKeyed; -import org.springframework.data.elasticsearch.repositories.sample.SampleUUIDKeyedElasticsearchRepository; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -49,9 +61,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Mark Paluch * @author Christoph Strobl * @author Michael Wirth + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:/simple-repository-test.xml") +@ContextConfiguration("classpath:/uuidkeyed-repository-test.xml") public class UUIDElasticsearchRepositoryTests { @Autowired private SampleUUIDKeyedElasticsearchRepository repository; @@ -60,14 +73,13 @@ public class UUIDElasticsearchRepositoryTests { @Before public void before() { - elasticsearchTemplate.deleteIndex(SampleEntityUUIDKeyed.class); - elasticsearchTemplate.createIndex(SampleEntityUUIDKeyed.class); - elasticsearchTemplate.putMapping(SampleEntityUUIDKeyed.class); - elasticsearchTemplate.refresh(SampleEntityUUIDKeyed.class); + + IndexInitializer.init(elasticsearchTemplate, SampleEntityUUIDKeyed.class); } @Test public void shouldDoBulkIndexDocument() { + // given UUID documentId1 = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed(); @@ -83,31 +95,36 @@ public class UUIDElasticsearchRepositoryTests { // when repository.saveAll(Arrays.asList(sampleEntityUUIDKeyed1, sampleEntityUUIDKeyed2)); + // then Optional entity1FromElasticSearch = repository.findById(documentId1); - assertThat(entity1FromElasticSearch.isPresent(), is(true)); + assertThat(entity1FromElasticSearch).isPresent(); Optional entity2FromElasticSearch = repository.findById(documentId2); - assertThat(entity2FromElasticSearch.isPresent(), is(true)); + assertThat(entity2FromElasticSearch).isPresent(); } @Test public void shouldSaveDocument() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); sampleEntityUUIDKeyed.setId(documentId); sampleEntityUUIDKeyed.setMessage("some message"); sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis()); + // when repository.save(sampleEntityUUIDKeyed); + // then Optional entityFromElasticSearch = repository.findById(documentId); - assertThat(entityFromElasticSearch.isPresent(), is(true)); + assertThat(entityFromElasticSearch).isPresent(); } @Test public void shouldFindDocumentById() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); @@ -115,15 +132,18 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed.setMessage("some message"); sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis()); repository.save(sampleEntityUUIDKeyed); + // when Optional entityFromElasticSearch = repository.findById(documentId); + // then - assertThat(entityFromElasticSearch.isPresent(), is(true)); - assertThat(sampleEntityUUIDKeyed, is(equalTo(sampleEntityUUIDKeyed))); + assertThat(entityFromElasticSearch).isPresent(); + assertThat(entityFromElasticSearch.get()).isEqualTo(sampleEntityUUIDKeyed); } @Test public void shouldReturnCountOfDocuments() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); @@ -131,22 +151,27 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed.setMessage("some message"); sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis()); repository.save(sampleEntityUUIDKeyed); + // when Long count = repository.count(); + // then - assertThat(count, is(greaterThanOrEqualTo(1L))); + assertThat(count).isGreaterThanOrEqualTo(1L); } @Test public void shouldFindAllDocuments() { + // when Iterable results = repository.findAll(); + // then - assertThat(results, is(notNullValue())); + assertThat(results).isNotNull(); } @Test public void shouldDeleteDocument() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); @@ -154,15 +179,18 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed.setMessage("some message"); sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis()); repository.save(sampleEntityUUIDKeyed); + // when repository.deleteById(documentId); + // then Optional entityFromElasticSearch = repository.findById(documentId); - assertThat(entityFromElasticSearch.isPresent(), is(false)); + assertThat(entityFromElasticSearch).isNotPresent(); } @Test public void shouldSearchDocumentsGivenSearchQuery() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); @@ -174,13 +202,15 @@ public class UUIDElasticsearchRepositoryTests { SearchQuery query = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test")).build(); // when Page page = repository.search(query); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1))); + assertThat(page).isNotNull(); + assertThat(page.getNumberOfElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldSearchDocumentsGivenElasticsearchQuery() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); @@ -188,18 +218,18 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed.setMessage("hello world."); sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis()); repository.save(sampleEntityUUIDKeyed); + // when Page page = repository.search(termQuery("message", "world"), PageRequest.of(0, 50)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1))); + assertThat(page).isNotNull(); + assertThat(page.getNumberOfElements()).isGreaterThanOrEqualTo(1); } - /* - DATAES-82 - */ - @Test + @Test // DATAES-82 public void shouldFindAllByIdQuery() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); @@ -216,18 +246,19 @@ public class UUIDElasticsearchRepositoryTests { repository.save(sampleEntityUUIDKeyed2); // when + final List docIds = Arrays.asList(documentId, documentId2); LinkedList sampleEntities = (LinkedList) repository - .findAllById(Arrays.asList(documentId, documentId2)); + .findAllById(docIds); // then - assertNotNull("sample entities cant be null..", sampleEntities); - assertThat(sampleEntities.size(), is(2)); - assertThat(sampleEntities.get(0).getId(), isIn(Arrays.asList(documentId, documentId2))); - assertThat(sampleEntities.get(1).getId(), isIn(Arrays.asList(documentId, documentId2))); + assertThat(sampleEntities).isNotNull().hasSize(2); + assertThat(sampleEntities.get(0).getId()).isIn(docIds); + assertThat(sampleEntities.get(1).getId()).isIn(docIds); } @Test public void shouldSaveIterableEntities() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed(); @@ -242,16 +273,19 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed2.setVersion(System.currentTimeMillis()); Iterable sampleEntities = Arrays.asList(sampleEntityUUIDKeyed1, sampleEntityUUIDKeyed2); + // when repository.saveAll(sampleEntities); + // then Page entities = repository.search(termQuery("id", documentId.toString()), PageRequest.of(0, 50)); - assertNotNull(entities); + assertThat(entities).isNotNull(); } @Test public void shouldReturnTrueGivenDocumentWithIdExists() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); @@ -264,7 +298,7 @@ public class UUIDElasticsearchRepositoryTests { boolean exist = repository.existsById(documentId); // then - assertEquals(exist, true); + assertThat(exist).isTrue(); } @Test // DATAES-363 @@ -277,21 +311,24 @@ public class UUIDElasticsearchRepositoryTests { boolean exist = repository.existsById(documentId); // then - assertThat(exist, is(false)); + assertThat(exist).isFalse(); } @Test public void shouldDeleteAll() { + // when repository.deleteAll(); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(0L); } @Test public void shouldDeleteById() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); @@ -299,17 +336,20 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed.setMessage("hello world."); sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis()); repository.save(sampleEntityUUIDKeyed); + // when long result = repository.deleteSampleEntityUUIDKeyedById(documentId); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId.toString())).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); - assertThat(result, equalTo(1L)); + assertThat(sampleEntities.getTotalElements()).isGreaterThanOrEqualTo(0); + assertThat(result).isEqualTo(1L); } @Test public void shouldDeleteByMessageAndReturnList() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed(); @@ -332,18 +372,21 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed3.setAvailable(false); sampleEntityUUIDKeyed3.setVersion(System.currentTimeMillis()); repository.saveAll(Arrays.asList(sampleEntityUUIDKeyed1, sampleEntityUUIDKeyed2, sampleEntityUUIDKeyed3)); + // when List result = repository.deleteByAvailable(true); repository.refresh(); + // then - assertThat(result.size(), equalTo(2)); + assertThat(result).hasSize(2); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(1); } @Test public void shouldDeleteByListForMessage() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed(); @@ -363,18 +406,21 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed3.setMessage("hello world 3"); sampleEntityUUIDKeyed3.setVersion(System.currentTimeMillis()); repository.saveAll(Arrays.asList(sampleEntityUUIDKeyed1, sampleEntityUUIDKeyed2, sampleEntityUUIDKeyed3)); + // when List result = repository.deleteByMessage("hello world 3"); repository.refresh(); + // then - assertThat(result.size(), equalTo(1)); + assertThat(result).hasSize(1); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(2L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(2); } @Test public void shouldDeleteByType() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed(); @@ -394,17 +440,20 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed3.setType("image"); sampleEntityUUIDKeyed3.setVersion(System.currentTimeMillis()); repository.saveAll(Arrays.asList(sampleEntityUUIDKeyed1, sampleEntityUUIDKeyed2, sampleEntityUUIDKeyed3)); + // when repository.deleteByType("article"); repository.refresh(); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(2L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(2); } @Test public void shouldDeleteEntity() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); @@ -412,17 +461,20 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed.setMessage("hello world."); sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis()); repository.save(sampleEntityUUIDKeyed); + // when repository.delete(sampleEntityUUIDKeyed); repository.refresh(); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId.toString())).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(0); } @Test public void shouldReturnIterableEntities() { + // given UUID documentId1 = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed(); @@ -440,12 +492,14 @@ public class UUIDElasticsearchRepositoryTests { // when Iterable sampleEntities = repository.search(termQuery("id", documentId1.toString())); + // then - assertNotNull("sample entities cant be null..", sampleEntities); + assertThat(sampleEntities).isNotNull(); } @Test public void shouldDeleteIterableEntities() { + // given UUID documentId1 = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed(); @@ -461,15 +515,18 @@ public class UUIDElasticsearchRepositoryTests { repository.save(sampleEntityUUIDKeyed2); Iterable sampleEntities = Arrays.asList(sampleEntityUUIDKeyed2, sampleEntityUUIDKeyed2); + // when repository.deleteAll(sampleEntities); + // then - assertThat(repository.findById(documentId1).isPresent(), is(false)); - assertThat(repository.findById(documentId2).isPresent(), is(false)); + assertThat(repository.findById(documentId1)).isNotPresent(); + assertThat(repository.findById(documentId2)).isNotPresent(); } @Test public void shouldSortByGivenField() { + // given UUID documentId = UUID.randomUUID(); SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed(); @@ -482,14 +539,17 @@ public class UUIDElasticsearchRepositoryTests { sampleEntityUUIDKeyed2.setId(documentId2); sampleEntityUUIDKeyed2.setMessage("hello"); repository.save(sampleEntityUUIDKeyed2); + // when Iterable sampleEntities = repository.findAll(Sort.by(Order.asc("message"))); + // then - assertThat(sampleEntities, is(notNullValue())); + assertThat(sampleEntities).isNotNull(); } @Test public void shouldReturnSimilarEntities() { + // given String sampleMessage = "So we build a web site or an application and want to add search to it, " + "and then it hits us: getting search working is hard. We want our search solution to be fast," @@ -505,7 +565,7 @@ public class UUIDElasticsearchRepositoryTests { PageRequest.of(0, 5)); // then - assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(results.getTotalElements()).isGreaterThanOrEqualTo(1); } private static List createSampleEntitiesWithMessage(String message, int numberOfEntities) { @@ -521,4 +581,91 @@ public class UUIDElasticsearchRepositoryTests { } return sampleEntities; } + + /** + * @author Gad Akuka + * @author Rizwan Idrees + * @author Mohsin Husen + */ + + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-uuid-keyed", type = "test-type-uuid-keyed", shards = 1, replicas = 0, + refreshInterval = "-1") + static class SampleEntityUUIDKeyed { + + @Id private UUID id; + private String type; + @Field(type = FieldType.Text, fielddata = true) private String message; + private int rate; + @ScriptedField private Long scriptedRate; + private boolean available; + private String highlightedMessage; + + private GeoPoint location; + + @Version private Long version; + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + SampleEntityUUIDKeyed that = (SampleEntityUUIDKeyed) o; + + if (available != that.available) + return false; + if (rate != that.rate) + return false; + if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) + : that.highlightedMessage != null) + return false; + if (id != null ? !id.equals(that.id) : that.id != null) + return false; + if (location != null ? !location.equals(that.location) : that.location != null) + return false; + if (message != null ? !message.equals(that.message) : that.message != null) + return false; + if (type != null ? !type.equals(that.type) : that.type != null) + return false; + if (version != null ? !version.equals(that.version) : that.version != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + result = 31 * result + (message != null ? message.hashCode() : 0); + result = 31 * result + rate; + result = 31 * result + (available ? 1 : 0); + result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0); + result = 31 * result + (location != null ? location.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } + } + + /** + * @author Gad Akuka + * @author Christoph Strobl + */ + interface SampleUUIDKeyedElasticsearchRepository extends ElasticsearchRepository { + + long deleteSampleEntityUUIDKeyedById(UUID id); + + List deleteByAvailable(boolean available); + + List deleteByMessage(String message); + + void deleteByType(String type); + + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryManualWiringTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryManualWiringTests.java deleted file mode 100644 index 1c6679d34..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryManualWiringTests.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2013-2019 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.repository.complex; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.SampleEntity; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author Artur Konczak - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:complex-custom-method-repository-manual-wiring-test.xml") -public class ComplexCustomMethodRepositoryManualWiringTests { - - @Autowired - private ComplexElasticsearchRepositoryManualWiring complexRepository; - - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); - elasticsearchTemplate.createIndex(SampleEntity.class); - elasticsearchTemplate.putMapping(SampleEntity.class); - elasticsearchTemplate.refresh(SampleEntity.class); - } - - @Test - public void shouldExecuteComplexCustomMethod() { - //Given - - //When - String result = complexRepository.doSomethingSpecial(); - //Then - assertThat(result, is("3+3=6")); - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryTests.java deleted file mode 100644 index 912d145fd..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryTests.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2013-2019 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.repository.complex; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.SampleEntity; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author Artur Konczak - * @author Mohsin Husen - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:complex-custom-method-repository-test.xml") -public class ComplexCustomMethodRepositoryTests { - - @Autowired - private ComplexElasticsearchRepository complexRepository; - - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); - elasticsearchTemplate.createIndex(SampleEntity.class); - elasticsearchTemplate.refresh(SampleEntity.class); - } - - @Test - public void shouldExecuteComplexCustomMethod() { - //Given - - //When - String result = complexRepository.doSomethingSpecial(); - //Then - assertThat(result, is("2+2=4")); - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/config/ReactiveElasticsearchRepositoriesRegistrarTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/config/ReactiveElasticsearchRepositoriesRegistrarTests.java index ab2c0cc97..67e97bb32 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/config/ReactiveElasticsearchRepositoriesRegistrarTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/config/ReactiveElasticsearchRepositoriesRegistrarTests.java @@ -15,6 +15,18 @@ */ package org.springframework.data.elasticsearch.repository.config; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.lang.Double; +import java.lang.Long; + import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; @@ -22,9 +34,15 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; import org.springframework.data.elasticsearch.TestUtils; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; import org.springframework.data.elasticsearch.core.ReactiveElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.SampleEntity; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.repository.ReactiveElasticsearchRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -32,6 +50,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * @author Christoph Strobl * @currentRead Fool's Fate - Robin Hobb + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration @@ -60,4 +79,30 @@ public class ReactiveElasticsearchRepositoriesRegistrarTests { interface ReactiveSampleEntityRepository extends ReactiveElasticsearchRepository {} + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-reactive-repositories-registrar", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchStringQueryUnitTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchStringQueryUnitTests.java index 05047524d..1274411ea 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchStringQueryUnitTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchStringQueryUnitTests.java @@ -17,27 +17,43 @@ package org.springframework.data.elasticsearch.repository.query; import static org.assertj.core.api.Assertions.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + import java.lang.reflect.Method; import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +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.annotations.InnerField; +import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; import org.springframework.data.elasticsearch.core.query.StringQuery; -import org.springframework.data.elasticsearch.entities.Person; import org.springframework.data.projection.SpelAwareProxyProjectionFactory; import org.springframework.data.repository.Repository; import org.springframework.data.repository.core.support.DefaultRepositoryMetadata; /** * @author Christoph Strobl + * @author Peter-Josef Meisch */ @RunWith(MockitoJUnitRunner.class) public class ElasticsearchStringQueryUnitTests { @@ -91,6 +107,56 @@ public class ElasticsearchStringQueryUnitTests { new SpelAwareProxyProjectionFactory(), converter.getMappingContext()); } + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + + @Document(indexName = "test-index-person-query-unittest", type = "user", shards = 1, replicas = 0, refreshInterval = "-1") + static class Person { + + @Id private String id; + + private String name; + + @Field(type = FieldType.Nested) private List car; + + @Field(type = FieldType.Nested, includeInParent = true) private List books; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCar() { + return car; + } + + public void setCar(List car) { + this.car = car; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + } + private interface SampleRepository extends Repository { @Query("{ 'bool' : { 'must' : { 'term' : { 'name' : '?0' } } } }") @@ -100,4 +166,85 @@ public class ElasticsearchStringQueryUnitTests { Person findWithRepeatedPlaceholder(String arg0, String arg1, String arg2, String arg3, String arg4, String arg5, String arg6, String arg7, String arg8, String arg9, String arg10, String arg11); } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Nordine Bittich + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-book-query-unittest", type = "book", shards = 1, replicas = 0, refreshInterval = "-1") + static class Book { + + @Id private String id; + private String name; + @Field(type = FieldType.Object) private Author author; + @Field(type = FieldType.Nested) private Map> buckets = new HashMap<>(); + @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"), + otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop", + searchAnalyzer = "standard") }) private String description; + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + static class Car { + + private String name; + private String model; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class Author { + + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/query/ReactiveElasticsearchQueryMethodUnitTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/query/ReactiveElasticsearchQueryMethodUnitTests.java index bb1ce9290..971de4912 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/query/ReactiveElasticsearchQueryMethodUnitTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/query/ReactiveElasticsearchQueryMethodUnitTests.java @@ -17,20 +17,33 @@ package org.springframework.data.elasticsearch.repository.query; import static org.assertj.core.api.Assertions.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.junit.Before; import org.junit.Test; import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.data.annotation.Id; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; +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.InnerField; +import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; -import org.springframework.data.elasticsearch.entities.Person; import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.projection.SpelAwareProxyProjectionFactory; import org.springframework.data.repository.Repository; @@ -42,6 +55,7 @@ import org.springframework.data.repository.core.support.DefaultRepositoryMetadat */ public class ReactiveElasticsearchQueryMethodUnitTests { + public static final String INDEX_NAME = "test-index-person-reactive-repository-query"; SimpleElasticsearchMappingContext mappingContext; @Before @@ -56,7 +70,7 @@ public class ReactiveElasticsearchQueryMethodUnitTests { ElasticsearchEntityMetadata metadata = queryMethod.getEntityInformation(); assertThat(metadata.getJavaType()).isAssignableFrom(Person.class); - assertThat(metadata.getIndexName()).isEqualTo("test-index-person"); + assertThat(metadata.getIndexName()).isEqualTo(INDEX_NAME); assertThat(metadata.getIndexTypeName()).isEqualTo("user"); } @@ -126,4 +140,136 @@ public class ReactiveElasticsearchQueryMethodUnitTests { List method(); } + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + + @Document(indexName = INDEX_NAME, type = "user", shards = 1, replicas = 0, + refreshInterval = "-1") + static class Person { + + @Id private String id; + + private String name; + + @Field(type = FieldType.Nested) private List car; + + @Field(type = FieldType.Nested, includeInParent = true) private List books; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCar() { + return car; + } + + public void setCar(List car) { + this.car = car; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Nordine Bittich + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-book-reactive-repository-query", type = "book", shards = 1, replicas = 0, + refreshInterval = "-1") + static class Book { + + @Id private String id; + private String name; + @Field(type = FieldType.Object) private Author author; + @Field(type = FieldType.Nested) private Map> buckets = new HashMap<>(); + @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"), + otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop", + searchAnalyzer = "standard") }) private String description; + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + static class Car { + + private String name; + private String model; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class Author { + + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/query/ReactiveElasticsearchStringQueryUnitTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/query/ReactiveElasticsearchStringQueryUnitTests.java index ef842a43a..351df0a9a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/query/ReactiveElasticsearchStringQueryUnitTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/query/ReactiveElasticsearchStringQueryUnitTests.java @@ -17,11 +17,20 @@ package org.springframework.data.elasticsearch.repository.query; import static org.assertj.core.api.Assertions.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.lang.reflect.Method; import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.junit.Before; import org.junit.Ignore; @@ -29,13 +38,18 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +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.annotations.InnerField; +import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.core.ReactiveElasticsearchOperations; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; import org.springframework.data.elasticsearch.core.query.StringQuery; -import org.springframework.data.elasticsearch.entities.Person; import org.springframework.data.projection.SpelAwareProxyProjectionFactory; import org.springframework.data.repository.Repository; import org.springframework.data.repository.core.support.DefaultRepositoryMetadata; @@ -45,6 +59,7 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; /** * @author Christoph Strobl * @currentRead Fool's Fate - Robin Hobb + * @author Peter-Josef Meisch */ @RunWith(MockitoJUnitRunner.class) public class ReactiveElasticsearchStringQueryUnitTests { @@ -115,7 +130,7 @@ public class ReactiveElasticsearchStringQueryUnitTests { Class[] argTypes = Arrays.stream(args).map(Object::getClass).toArray(size -> new Class[size]); ReactiveElasticsearchQueryMethod queryMethod = getQueryMethod(methodName, argTypes); ReactiveElasticsearchStringQuery elasticsearchStringQuery = queryForMethod(queryMethod); - + return elasticsearchStringQuery.createQuery(new ElasticsearchParametersParameterAccessor(queryMethod, args)); } @@ -154,4 +169,136 @@ public class ReactiveElasticsearchStringQueryUnitTests { Person findWithRepeatedPlaceholder(String arg0, String arg1, String arg2, String arg3, String arg4, String arg5, String arg6, String arg7, String arg8, String arg9, String arg10, String arg11); } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + + @Document(indexName = "test-index-person-reactive-repository-string-query", type = "user", shards = 1, replicas = 0, + refreshInterval = "-1") + public class Person { + + @Id private String id; + + private String name; + + @Field(type = FieldType.Nested) private List car; + + @Field(type = FieldType.Nested, includeInParent = true) private List books; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public List getCar() { + return car; + } + + public void setCar(List car) { + this.car = car; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Nordine Bittich + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-book-reactive-repository-string-query", type = "book", shards = 1, replicas = 0, + refreshInterval = "-1") + static class Book { + + @Id private String id; + private String name; + @Field(type = FieldType.Object) private Author author; + @Field(type = FieldType.Nested) private Map> buckets = new HashMap<>(); + @MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"), + otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop", + searchAnalyzer = "standard") }) private String description; + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + static class Car { + + private String name; + private String model; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + */ + static class Author { + + private String id; + private String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/query/keywords/QueryKeywordsTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/query/keywords/QueryKeywordsTests.java new file mode 100644 index 000000000..e33241411 --- /dev/null +++ b/src/test/java/org/springframework/data/elasticsearch/repository/query/keywords/QueryKeywordsTests.java @@ -0,0 +1,232 @@ +/* + * Copyright 2016-2019 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.repository.query.keywords; + +import static org.assertj.core.api.Assertions.*; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +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.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.utils.IndexInitializer; +import org.springframework.data.repository.PagingAndSortingRepository; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * @author Artur Konczak + * @author Christoph Strobl + * @author Peter-Josef Meisch + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:/repository-query-keywords.xml") +public class QueryKeywordsTests { + + @Autowired private ProductRepository repository; + + @Autowired private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + + IndexInitializer.init(elasticsearchTemplate, Product.class); + + repository.saveAll( + Arrays.asList(Product.builder().id("1").name("Sugar").text("Cane sugar").price(1.0f).available(false).build(), + Product.builder().id("2").name("Sugar").text("Cane sugar").price(1.2f).available(true).build(), + Product.builder().id("3").name("Sugar").text("Beet sugar").price(1.1f).available(true).build(), + Product.builder().id("4").name("Salt").text("Rock salt").price(1.9f).available(true).build(), + Product.builder().id("5").name("Salt").text("Sea salt").price(2.1f).available(false).build())); + + elasticsearchTemplate.refresh(Product.class); + } + + @Test + public void shouldSupportAND() { + + // given + + // when + + // then + assertThat(repository.findByNameAndText("Sugar", "Cane sugar")).hasSize(2); + assertThat(repository.findByNameAndPrice("Sugar", 1.1f)).hasSize(1); + } + + @Test + public void shouldSupportOR() { + + // given + + // when + + // then + assertThat(repository.findByNameOrPrice("Sugar", 1.9f)).hasSize(4); + assertThat(repository.findByNameOrText("Salt", "Beet sugar")).hasSize(3); + } + + @Test + public void shouldSupportTrueAndFalse() { + + // given + + // when + + // then + assertThat(repository.findByAvailableTrue()).hasSize(3); + assertThat(repository.findByAvailableFalse()).hasSize(2); + } + + @Test + public void shouldSupportInAndNotInAndNot() { + + // given + + // when + + // then + assertThat(repository.findByPriceIn(Arrays.asList(1.2f, 1.1f))).hasSize(2); + assertThat(repository.findByPriceNotIn(Arrays.asList(1.2f, 1.1f))).hasSize(3); + assertThat(repository.findByPriceNot(1.2f)).hasSize(4); + } + + @Test // DATAES-171 + public void shouldWorkWithNotIn() { + + // given + + // when + + // then + assertThat(repository.findByIdNotIn(Arrays.asList("2", "3"))).hasSize(3); + } + + @Test + public void shouldSupportBetween() { + + // given + + // when + + // then + assertThat(repository.findByPriceBetween(1.0f, 2.0f)).hasSize(4); + } + + @Test + public void shouldSupportLessThanAndGreaterThan() { + + // given + + // when + + // then + assertThat(repository.findByPriceLessThan(1.1f)).hasSize(1); + assertThat(repository.findByPriceLessThanEqual(1.1f)).hasSize(2); + + assertThat(repository.findByPriceGreaterThan(1.9f)).hasSize(1); + assertThat(repository.findByPriceGreaterThanEqual(1.9f)).hasSize(2); + } + + /** + * @author Mohsin Husen + * @author Artur Konczak + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @Builder + @Document(indexName = "test-index-product-query-keywords", type = "test-product-type", shards = 1, replicas = 0, + refreshInterval = "-1") + static class Product { + + @Id private String id; + + private List title; + + private String name; + + private String description; + + private String text; + + private List categories; + + private Float weight; + + @Field(type = FieldType.Float) private Float price; + + private Integer popularity; + + private boolean available; + + private String location; + + private Date lastModified; + } + + /** + * Created by akonczak on 04/09/15. + */ + interface ProductRepository extends PagingAndSortingRepository { + + List findByNameAndText(String name, String text); + + List findByNameAndPrice(String name, Float price); + + List findByNameOrText(String name, String text); + + List findByNameOrPrice(String name, Float price); + + List findByAvailableTrue(); + + List findByAvailableFalse(); + + List findByPriceIn(List floats); + + List findByPriceNotIn(List floats); + + List findByPriceNot(float v); + + List findByPriceBetween(float v, float v1); + + List findByPriceLessThan(float v); + + List findByPriceLessThanEqual(float v); + + List findByPriceGreaterThan(float v); + + List findByPriceGreaterThanEqual(float v); + + List findByIdNotIn(List strings); + } + +} diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactoryTests.java index b6abbdf47..ef98d7257 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactoryTests.java @@ -41,14 +41,14 @@ import org.springframework.data.repository.core.support.DefaultRepositoryMetadat @RunWith(MockitoJUnitRunner.class) public class ElasticsearchRepositoryFactoryTests { - @Mock - private ElasticsearchOperations operations; + @Mock private ElasticsearchOperations operations; private ElasticsearchConverter converter; private ElasticsearchRepositoryFactory factory; MappingContext, ElasticsearchPersistentProperty> mappingContext = new SimpleElasticsearchMappingContext(); @Before public void before() { + converter = new MappingElasticsearchConverter(mappingContext); when(operations.getElasticsearchConverter()).thenReturn(converter); factory = new ElasticsearchRepositoryFactory(operations); @@ -56,6 +56,7 @@ public class ElasticsearchRepositoryFactoryTests { @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionGivenQueryDslRepository() { + // given RepositoryMetadata metadata = new DefaultRepositoryMetadata(QuerydslPredicateExecutor.class); // when diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/QueryKeywordsTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/support/QueryKeywordsTests.java deleted file mode 100644 index e7a154dfc..000000000 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/QueryKeywordsTests.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2016-2019 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.repository.support; - -import static org.hamcrest.core.Is.*; -import static org.junit.Assert.*; - -import java.util.Arrays; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; -import org.springframework.data.elasticsearch.entities.Product; -import org.springframework.data.elasticsearch.repositories.query.ProductRepository; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author Artur Konczak - * @author Christoph Strobl - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:/repository-query-support.xml") -public class QueryKeywordsTests { - - @Autowired - private ProductRepository repository; - - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before() { - elasticsearchTemplate.deleteIndex(Product.class); - elasticsearchTemplate.createIndex(Product.class); - elasticsearchTemplate.putMapping(Product.class); - elasticsearchTemplate.refresh(Product.class); - - repository.saveAll(Arrays.asList( - Product.builder().id("1").name("Sugar").text("Cane sugar").price(1.0f).available(false).build() - , Product.builder().id("2").name("Sugar").text("Cane sugar").price(1.2f).available(true).build() - , Product.builder().id("3").name("Sugar").text("Beet sugar").price(1.1f).available(true).build() - , Product.builder().id("4").name("Salt").text("Rock salt").price(1.9f).available(true).build() - , Product.builder().id("5").name("Salt").text("Sea salt").price(2.1f).available(false).build())); - - elasticsearchTemplate.refresh(Product.class); - } - - @Test - public void shouldSupportAND() { - //given - - //when - - //then - assertThat(repository.findByNameAndText("Sugar", "Cane sugar").size(), is(2)); - assertThat(repository.findByNameAndPrice("Sugar", 1.1f).size(), is(1)); - } - - @Test - public void shouldSupportOR() { - //given - - //when - - //then - assertThat(repository.findByNameOrPrice("Sugar", 1.9f).size(), is(4)); - assertThat(repository.findByNameOrText("Salt", "Beet sugar").size(), is(3)); - } - - @Test - public void shouldSupportTrueAndFalse() { - //given - - //when - - //then - assertThat(repository.findByAvailableTrue().size(), is(3)); - assertThat(repository.findByAvailableFalse().size(), is(2)); - } - - @Test - public void shouldSupportInAndNotInAndNot() { - //given - - //when - - //then - assertThat(repository.findByPriceIn(Arrays.asList(1.2f, 1.1f)).size(), is(2)); - assertThat(repository.findByPriceNotIn(Arrays.asList(1.2f, 1.1f)).size(), is(3)); - assertThat(repository.findByPriceNot(1.2f).size(), is(4)); - } - - /* - DATAES-171 - */ - @Test - public void shouldWorkWithNotIn() { - //given - - //when - - //then - assertThat(repository.findByIdNotIn(Arrays.asList("2", "3")).size(), is(3)); - } - - @Test - public void shouldSupportBetween() { - //given - - //when - - //then - assertThat(repository.findByPriceBetween(1.0f, 2.0f).size(), is(4)); - } - - @Test - public void shouldSupportLessThanAndGreaterThan() { - //given - - //when - - //then - assertThat(repository.findByPriceLessThan(1.1f).size(), is(1)); - assertThat(repository.findByPriceLessThanEqual(1.1f).size(), is(2)); - - assertThat(repository.findByPriceGreaterThan(1.9f).size(), is(1)); - assertThat(repository.findByPriceGreaterThanEqual(1.9f).size(), is(2)); - } -} diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleReactiveElasticsearchRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleReactiveElasticsearchRepositoryTests.java index b8d131603..5edde06c5 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleReactiveElasticsearchRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleReactiveElasticsearchRepositoryTests.java @@ -16,7 +16,22 @@ package org.springframework.data.elasticsearch.repository.support; import static org.assertj.core.api.Assertions.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.junit.Test; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @@ -32,7 +47,6 @@ import org.elasticsearch.action.support.WriteRequest.RefreshPolicy; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.junit.Before; -import org.junit.Test; import org.junit.runner.RunWith; import org.reactivestreams.Publisher; import org.springframework.beans.factory.annotation.Autowired; @@ -45,7 +59,6 @@ import org.springframework.data.elasticsearch.TestUtils; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient; import org.springframework.data.elasticsearch.config.AbstractReactiveElasticsearchConfiguration; -import org.springframework.data.elasticsearch.entities.SampleEntity; import org.springframework.data.elasticsearch.repository.config.EnableReactiveElasticsearchRepositories; import org.springframework.data.repository.reactive.ReactiveCrudRepository; import org.springframework.test.context.ContextConfiguration; @@ -70,7 +83,7 @@ public class SimpleReactiveElasticsearchRepositoryTests { } } - static final String INDEX = "test-index-sample"; + static final String INDEX = "test-index-sample-simple-reactive"; static final String TYPE = "test-type"; @Autowired ReactiveSampleEntityRepository repository; @@ -489,4 +502,38 @@ public class SimpleReactiveElasticsearchRepositoryTests { Mono deleteAllByMessage(String message); } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = INDEX, type = TYPE, shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id + private String id; + @Field(type = Text, store = true, fielddata = true) + private String type; + @Field(type = Text, store = true, fielddata = true) + private String message; + private int rate; + @ScriptedField + private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version + private Long version; + @Score + private float score; + + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/support/simple/SimpleElasticsearchRepositoryTests.java similarity index 75% rename from src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepositoryTests.java rename to src/test/java/org/springframework/data/elasticsearch/repository/support/simple/SimpleElasticsearchRepositoryTests.java index 92d93733a..2aa531c52 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/support/simple/SimpleElasticsearchRepositoryTests.java @@ -13,33 +13,49 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.springframework.data.elasticsearch.repository.support; +package org.springframework.data.elasticsearch.repository.support.simple; import static org.apache.commons.lang.RandomStringUtils.*; +import static org.assertj.core.api.Assertions.*; import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; + +import java.lang.Double; +import java.lang.Long; +import java.lang.Object; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.elasticsearch.action.ActionRequestValidationException; -import org.elasticsearch.common.util.CollectionUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.Version; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Order; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.Score; +import org.springframework.data.elasticsearch.annotations.ScriptedField; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; -import org.springframework.data.elasticsearch.entities.SampleEntity; -import org.springframework.data.elasticsearch.repositories.sample.SampleElasticsearchRepository; +import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; +import org.springframework.data.elasticsearch.utils.IndexInitializer; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -49,6 +65,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Mark Paluch * @author Christoph Strobl * @author Michael Wirth + * @author Peter-Josef Meisch */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/simple-repository-test.xml") @@ -60,14 +77,13 @@ public class SimpleElasticsearchRepositoryTests { @Before public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); - elasticsearchTemplate.createIndex(SampleEntity.class); - elasticsearchTemplate.putMapping(SampleEntity.class); - elasticsearchTemplate.refresh(SampleEntity.class); + + IndexInitializer.init(elasticsearchTemplate, SampleEntity.class); } @Test public void shouldDoBulkIndexDocument() { + // given String documentId1 = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); @@ -83,43 +99,51 @@ public class SimpleElasticsearchRepositoryTests { // when repository.saveAll(Arrays.asList(sampleEntity1, sampleEntity2)); + // then Optional entity1FromElasticSearch = repository.findById(documentId1); - assertThat(entity1FromElasticSearch.isPresent(), is(true)); + assertThat(entity1FromElasticSearch.isPresent()).isTrue(); Optional entity2FromElasticSearch = repository.findById(documentId2); - assertThat(entity2FromElasticSearch.isPresent(), is(true)); + assertThat(entity2FromElasticSearch.isPresent()).isTrue(); } @Test public void shouldSaveDocument() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); sampleEntity.setId(documentId); sampleEntity.setMessage("some message"); sampleEntity.setVersion(System.currentTimeMillis()); + // when repository.save(sampleEntity); + // then Optional entityFromElasticSearch = repository.findById(documentId); - assertThat(entityFromElasticSearch.isPresent(), is(true)); + assertThat(entityFromElasticSearch).isPresent(); } @Test(expected = ActionRequestValidationException.class) public void throwExceptionWhenTryingToInsertWithVersionButWithoutId() { + // given SampleEntity sampleEntity = new SampleEntity(); sampleEntity.setMessage("some message"); sampleEntity.setVersion(System.currentTimeMillis()); + // when repository.save(sampleEntity); + // then - assertThat(sampleEntity.getId(), is(notNullValue())); + assertThat(sampleEntity.getId()).isNotNull(); } @Test public void shouldFindDocumentById() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -127,15 +151,18 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity.setMessage("some message"); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity); + // when Optional entityFromElasticSearch = repository.findById(documentId); + // then - assertThat(entityFromElasticSearch.isPresent(), is(true)); - assertThat(sampleEntity, is(equalTo(sampleEntity))); + assertThat(entityFromElasticSearch).isPresent(); + assertThat(entityFromElasticSearch.get()).isEqualTo(sampleEntity); } @Test public void shouldReturnCountOfDocuments() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -143,22 +170,27 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity.setMessage("some message"); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity); + // when Long count = repository.count(); + // then - assertThat(count, is(greaterThanOrEqualTo(1L))); + assertThat(count).isGreaterThanOrEqualTo(1L); } @Test public void shouldFindAllDocuments() { + // when Iterable results = repository.findAll(); + // then - assertThat(results, is(notNullValue())); + assertThat(results).isNotNull(); } @Test public void shouldDeleteDocument() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -166,15 +198,18 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity.setMessage("some message"); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity); + // when repository.deleteById(documentId); + // then Optional entityFromElasticSearch = repository.findById(documentId); - assertThat(entityFromElasticSearch.isPresent(), is(false)); + assertThat(entityFromElasticSearch).isNotPresent(); } @Test public void shouldSearchDocumentsGivenSearchQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -184,15 +219,18 @@ public class SimpleElasticsearchRepositoryTests { repository.save(sampleEntity); SearchQuery query = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test")).build(); + // when Page page = repository.search(query); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1))); + assertThat(page).isNotNull(); + assertThat(page.getNumberOfElements()).isGreaterThanOrEqualTo(1); } @Test public void shouldSearchDocumentsGivenElasticsearchQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -200,18 +238,18 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity.setMessage("hello world."); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity); + // when Page page = repository.search(termQuery("message", "world"), PageRequest.of(0, 50)); + // then - assertThat(page, is(notNullValue())); - assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1))); + assertThat(page).isNotNull(); + assertThat(page.getNumberOfElements()).isGreaterThanOrEqualTo(1); } - /* - DATAES-82 - */ - @Test + @Test // DATAES-82 public void shouldFindAllByIdQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -231,13 +269,12 @@ public class SimpleElasticsearchRepositoryTests { Iterable sampleEntities = repository.findAllById(Arrays.asList(documentId, documentId2)); // then - assertNotNull("sample entities cant be null..", sampleEntities); - List entities = CollectionUtils.iterableAsArrayList(sampleEntities); - assertThat(entities.size(), is(2)); + assertThat(sampleEntities).isNotNull().hasSize(2); } @Test public void shouldSaveIterableEntities() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); @@ -252,15 +289,18 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity2.setVersion(System.currentTimeMillis()); Iterable sampleEntities = Arrays.asList(sampleEntity1, sampleEntity2); + // when repository.saveAll(sampleEntities); + // then Page entities = repository.search(termQuery("id", documentId), PageRequest.of(0, 50)); - assertNotNull(entities); + assertThat(entities).isNotNull(); } @Test public void shouldReturnTrueGivenDocumentWithIdExists() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -273,7 +313,7 @@ public class SimpleElasticsearchRepositoryTests { boolean exist = repository.existsById(documentId); // then - assertEquals(exist, true); + assertThat(exist).isTrue(); } @Test // DATAES-363 @@ -286,11 +326,12 @@ public class SimpleElasticsearchRepositoryTests { boolean exist = repository.existsById(documentId); // then - assertThat(exist, is(false)); + assertThat(exist).isFalse(); } @Test public void shouldReturnResultsForGivenSearchQuery() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -298,25 +339,30 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity.setMessage("hello world."); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity); + // when SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); Page sampleEntities = repository.search(searchQuery); + // then - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(1L); } @Test public void shouldDeleteAll() { + // when repository.deleteAll(); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(0L); } @Test public void shouldDeleteById() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -324,6 +370,7 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity.setMessage("hello world."); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity); + // when long result = repository.deleteSampleEntityById(documentId); repository.refresh(); @@ -331,12 +378,13 @@ public class SimpleElasticsearchRepositoryTests { // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); - assertThat(result, equalTo(1L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(0L); + assertThat(result).isEqualTo(1L); } @Test public void shouldDeleteByMessageAndReturnList() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); @@ -359,18 +407,21 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity3.setAvailable(false); sampleEntity3.setVersion(System.currentTimeMillis()); repository.saveAll(Arrays.asList(sampleEntity1, sampleEntity2, sampleEntity3)); + // when List result = repository.deleteByAvailable(true); repository.refresh(); + // then - assertThat(result.size(), equalTo(2)); + assertThat(result).hasSize(2); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(1L); } @Test public void shouldDeleteByListForMessage() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); @@ -390,18 +441,21 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity3.setMessage("hello world 3"); sampleEntity3.setVersion(System.currentTimeMillis()); repository.saveAll(Arrays.asList(sampleEntity1, sampleEntity2, sampleEntity3)); + // when List result = repository.deleteByMessage("hello world 3"); repository.refresh(); + // then - assertThat(result.size(), equalTo(1)); + assertThat(result).hasSize(1); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(2L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(2L); } @Test public void shouldDeleteByType() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); @@ -421,17 +475,20 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity3.setType("image"); sampleEntity3.setVersion(System.currentTimeMillis()); repository.saveAll(Arrays.asList(sampleEntity1, sampleEntity2, sampleEntity3)); + // when repository.deleteByType("article"); repository.refresh(); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(2L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(2L); } @Test public void shouldDeleteEntity() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -439,16 +496,19 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity.setMessage("hello world."); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity); + // when repository.delete(sampleEntity); + // then SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build(); Page sampleEntities = repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + assertThat(sampleEntities.getTotalElements()).isEqualTo(0L); } @Test public void shouldReturnIterableEntities() { + // given String documentId1 = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); @@ -466,12 +526,14 @@ public class SimpleElasticsearchRepositoryTests { // when Iterable sampleEntities = repository.search(termQuery("id", documentId1)); + // then - assertNotNull("sample entities cant be null..", sampleEntities); + assertThat(sampleEntities).isNotNull(); } @Test public void shouldDeleteIterableEntities() { + // given String documentId1 = randomNumeric(5); SampleEntity sampleEntity1 = new SampleEntity(); @@ -487,30 +549,36 @@ public class SimpleElasticsearchRepositoryTests { repository.save(sampleEntity2); Iterable sampleEntities = Arrays.asList(sampleEntity2, sampleEntity2); + // when repository.deleteAll(sampleEntities); + // then - assertThat(repository.findById(documentId1).isPresent(), is(false)); - assertThat(repository.findById(documentId2).isPresent(), is(false)); + assertThat(repository.findById(documentId1)).isNotPresent(); + assertThat(repository.findById(documentId2)).isNotPresent(); } @Test public void shouldIndexEntity() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); sampleEntity.setId(documentId); sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setMessage("some message"); + // when repository.index(sampleEntity); + // then Page entities = repository.search(termQuery("id", documentId), PageRequest.of(0, 50)); - assertThat(entities.getTotalElements(), equalTo(1L)); + assertThat(entities.getTotalElements()).isEqualTo(1L); } @Test public void shouldSortByGivenField() { + // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); @@ -523,14 +591,17 @@ public class SimpleElasticsearchRepositoryTests { sampleEntity2.setId(documentId2); sampleEntity2.setMessage("hello"); repository.save(sampleEntity2); + // when Iterable sampleEntities = repository.findAll(Sort.by(Order.asc("message"))); + // then - assertThat(sampleEntities, is(notNullValue())); + assertThat(sampleEntities).isNotNull(); } @Test public void shouldReturnSimilarEntities() { + // given String sampleMessage = "So we build a web site or an application and want to add search to it, " + "and then it hits us: getting search working is hard. We want our search solution to be fast," @@ -546,7 +617,7 @@ public class SimpleElasticsearchRepositoryTests { PageRequest.of(0, 5)); // then - assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L))); + assertThat(results.getTotalElements()).isGreaterThanOrEqualTo(1L); } private static List createSampleEntitiesWithMessage(String message, int numberOfEntities) { @@ -562,4 +633,92 @@ public class SimpleElasticsearchRepositoryTests { } return sampleEntities; } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Chris White + * @author Sascha Woo + */ + @Setter + @Getter + @NoArgsConstructor + @AllArgsConstructor + @ToString + @Builder + @Document(indexName = "test-index-sample-simple-repository", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1") + static class SampleEntity { + + @Id private String id; + @Field(type = Text, store = true, fielddata = true) private String type; + @Field(type = Text, store = true, fielddata = true) private String message; + private int rate; + @ScriptedField private Double scriptedRate; + private boolean available; + private String highlightedMessage; + private GeoPoint location; + @Version private Long version; + @Score private float score; + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + + SampleEntity that = (SampleEntity) o; + + if (available != that.available) + return false; + if (rate != that.rate) + return false; + if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) + : that.highlightedMessage != null) + return false; + if (id != null ? !id.equals(that.id) : that.id != null) + return false; + if (location != null ? !location.equals(that.location) : that.location != null) + return false; + if (message != null ? !message.equals(that.message) : that.message != null) + return false; + if (type != null ? !type.equals(that.type) : that.type != null) + return false; + if (version != null ? !version.equals(that.version) : that.version != null) + return false; + + return true; + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + result = 31 * result + (message != null ? message.hashCode() : 0); + result = 31 * result + rate; + result = 31 * result + (available ? 1 : 0); + result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0); + result = 31 * result + (location != null ? location.hashCode() : 0); + result = 31 * result + (version != null ? version.hashCode() : 0); + return result; + } + } + + /** + * @author Rizwan Idrees + * @author Mohsin Husen + * @author Christoph Strobl + */ + interface SampleElasticsearchRepository extends ElasticsearchRepository { + + long deleteSampleEntityById(String id); + + List deleteByAvailable(boolean available); + + List deleteByMessage(String message); + + void deleteByType(String type); + + } + } diff --git a/src/test/java/org/springframework/data/elasticsearch/utils/IndexInitializer.java b/src/test/java/org/springframework/data/elasticsearch/utils/IndexInitializer.java new file mode 100644 index 000000000..8f59d1683 --- /dev/null +++ b/src/test/java/org/springframework/data/elasticsearch/utils/IndexInitializer.java @@ -0,0 +1,21 @@ +/* + * (c) Copyright 2019 codecentric AG + */ +package org.springframework.data.elasticsearch.utils; + +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; + +/** + * @author Peter-Josef Meisch + */ +final public class IndexInitializer { + + private IndexInitializer() {} + + public static void init(ElasticsearchOperations operations, Class clazz) { + operations.deleteIndex(clazz); + operations.createIndex(clazz); + operations.putMapping(clazz); + operations.refresh(clazz); + } +} diff --git a/src/test/resources/complex-custom-method-repository-manual-wiring-test.xml b/src/test/resources/complex-custom-method-repository-manual-wiring-test.xml index 77ad6f8f0..5fd597009 100644 --- a/src/test/resources/complex-custom-method-repository-manual-wiring-test.xml +++ b/src/test/resources/complex-custom-method-repository-manual-wiring-test.xml @@ -13,10 +13,10 @@ + base-package="org.springframework.data.elasticsearch.repositories.complex.custommethod.manualwiring"/> + class="org.springframework.data.elasticsearch.repositories.complex.custommethod.manualwiring.ComplexElasticsearchRepositoryManualWiringImpl"> diff --git a/src/test/resources/complex-custom-method-repository-test.xml b/src/test/resources/complex-custom-method-repository-test.xml index bc3b3c6b4..14d470471 100644 --- a/src/test/resources/complex-custom-method-repository-test.xml +++ b/src/test/resources/complex-custom-method-repository-test.xml @@ -13,6 +13,6 @@ + base-package="org.springframework.data.elasticsearch.repositories.complex.custommethod.autowiring"/> diff --git a/src/test/resources/custom-method-repository-rest-test.xml b/src/test/resources/custom-method-repository-rest-test.xml index fd47615c7..76544a06f 100644 --- a/src/test/resources/custom-method-repository-rest-test.xml +++ b/src/test/resources/custom-method-repository-rest-test.xml @@ -8,13 +8,14 @@ + class="org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate"> + base-package="org.springframework.data.elasticsearch.repositories.custommethod" + consider-nested-repositories="true"/> diff --git a/src/test/resources/custom-method-repository-test.xml b/src/test/resources/custom-method-repository-test.xml index 59c49ace0..a1384b753 100644 --- a/src/test/resources/custom-method-repository-test.xml +++ b/src/test/resources/custom-method-repository-test.xml @@ -8,11 +8,12 @@ + class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> + base-package="org.springframework.data.elasticsearch.repositories.custommethod" + consider-nested-repositories="true"/> diff --git a/src/test/resources/double-id-repository-test.xml b/src/test/resources/double-id-repository-test.xml index 6ab169615..ff65787d5 100644 --- a/src/test/resources/double-id-repository-test.xml +++ b/src/test/resources/double-id-repository-test.xml @@ -1,19 +1,20 @@ - + - - - + + + - + diff --git a/src/test/resources/dynamic-settings-test.xml b/src/test/resources/dynamic-settings-test.xml index 81ff36fa5..c042b3e98 100644 --- a/src/test/resources/dynamic-settings-test.xml +++ b/src/test/resources/dynamic-settings-test.xml @@ -13,6 +13,7 @@ + base-package="org.springframework.data.elasticsearch.repositories.setting.dynamic" + consider-nested-repositories="true"/> diff --git a/src/test/resources/existing-index-repository-test.xml b/src/test/resources/existing-index-repository-test.xml index 55f9605c8..600a1a509 100644 --- a/src/test/resources/existing-index-repository-test.xml +++ b/src/test/resources/existing-index-repository-test.xml @@ -14,6 +14,7 @@ + base-package="org.springframework.data.elasticsearch.repositories.existing.index" + consider-nested-repositories="true" /> diff --git a/src/test/resources/repository-query-support.xml b/src/test/resources/field-dynamic-settings-test.xml similarity index 80% rename from src/test/resources/repository-query-support.xml rename to src/test/resources/field-dynamic-settings-test.xml index 3f86b7af3..ac9da11b7 100644 --- a/src/test/resources/repository-query-support.xml +++ b/src/test/resources/field-dynamic-settings-test.xml @@ -12,7 +12,8 @@ - - + diff --git a/src/test/resources/immutable-repository-test.xml b/src/test/resources/immutable-repository-test.xml index 60fd99dd9..343dde55c 100644 --- a/src/test/resources/immutable-repository-test.xml +++ b/src/test/resources/immutable-repository-test.xml @@ -14,6 +14,7 @@ + base-package="org.springframework.data.elasticsearch.immutable" + consider-nested-repositories="true"/> diff --git a/src/test/resources/integer-id-repository-test.xml b/src/test/resources/integer-id-repository-test.xml index 645be3c29..d969124bd 100644 --- a/src/test/resources/integer-id-repository-test.xml +++ b/src/test/resources/integer-id-repository-test.xml @@ -14,6 +14,7 @@ + base-package="org.springframework.data.elasticsearch.repositories.integer" + consider-nested-repositories="true" /> diff --git a/src/test/resources/org/springframework/data/elasticsearch/config/namespace.xml b/src/test/resources/org/springframework/data/elasticsearch/config/namespace/namespace.xml similarity index 94% rename from src/test/resources/org/springframework/data/elasticsearch/config/namespace.xml rename to src/test/resources/org/springframework/data/elasticsearch/config/namespace/namespace.xml index 940e2109e..16c1968be 100644 --- a/src/test/resources/org/springframework/data/elasticsearch/config/namespace.xml +++ b/src/test/resources/org/springframework/data/elasticsearch/config/namespace/namespace.xml @@ -17,7 +17,8 @@ + base-package="org.springframework.data.elasticsearch.config.namespace" + consider-nested-repositories="true" /> diff --git a/src/test/resources/repository-non-document-entity.xml b/src/test/resources/repository-non-document-entity.xml index 148a9f2d9..64b7fb1a7 100644 --- a/src/test/resources/repository-non-document-entity.xml +++ b/src/test/resources/repository-non-document-entity.xml @@ -12,6 +12,8 @@ - + diff --git a/src/test/resources/repository-query-keywords.xml b/src/test/resources/repository-query-keywords.xml new file mode 100644 index 000000000..ed7535919 --- /dev/null +++ b/src/test/resources/repository-query-keywords.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + diff --git a/src/test/resources/repository-spring-data-geo-support.xml b/src/test/resources/repository-spring-data-geo-support.xml index e8698a6af..5dafbab32 100644 --- a/src/test/resources/repository-spring-data-geo-support.xml +++ b/src/test/resources/repository-spring-data-geo-support.xml @@ -1,17 +1,18 @@ - + - - - + + + - + diff --git a/src/test/resources/repository-test-nested-object-books.xml b/src/test/resources/repository-test-nested-object-books.xml index 410b8646d..d4b40ddb5 100644 --- a/src/test/resources/repository-test-nested-object-books.xml +++ b/src/test/resources/repository-test-nested-object-books.xml @@ -1,17 +1,18 @@ - + - - - + + + - + diff --git a/src/test/resources/simple-repository-test.xml b/src/test/resources/simple-repository-test.xml index 0f63eeb53..17ee39aba 100644 --- a/src/test/resources/simple-repository-test.xml +++ b/src/test/resources/simple-repository-test.xml @@ -14,6 +14,7 @@ + base-package="org.springframework.data.elasticsearch.repository.support.simple" + consider-nested-repositories="true"/> diff --git a/src/test/resources/spel-repository-test.xml b/src/test/resources/spel-repository-test.xml index bab415650..430c1fa48 100644 --- a/src/test/resources/spel-repository-test.xml +++ b/src/test/resources/spel-repository-test.xml @@ -14,6 +14,7 @@ + base-package="org.springframework.data.elasticsearch.repositories.spel" + consider-nested-repositories="true" /> diff --git a/src/test/resources/synonym-test.xml b/src/test/resources/synonym-test.xml index 6e4105bba..f36931f1f 100644 --- a/src/test/resources/synonym-test.xml +++ b/src/test/resources/synonym-test.xml @@ -1,18 +1,19 @@ - + - - - + + + - + diff --git a/src/test/resources/uuidkeyed-repository-test.xml b/src/test/resources/uuidkeyed-repository-test.xml new file mode 100644 index 000000000..13dd6e2da --- /dev/null +++ b/src/test/resources/uuidkeyed-repository-test.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + +