From 7df712a3b6b962fce2ad34b44ae66e2cd3e38059 Mon Sep 17 00:00:00 2001 From: akonczak Date: Sun, 12 May 2013 19:37:25 +0100 Subject: [PATCH] DATAES-2 Applied spring-data formatting to all sources --- formatting.xml | 820 ++++++++ pom.xml | 272 +-- src/docbkx/index.xml | 16 +- src/docbkx/preface.xml | 21 +- src/docbkx/reference/data-elasticsearch.xml | 98 +- src/docbkx/reference/elasticsearch-misc.xml | 36 +- src/docbkx/reference/repositories.xml | 1692 ++++++++++------- src/docbkx/resources/css/highlight.css | 21 +- src/docbkx/resources/css/html.css | 109 +- src/docbkx/resources/xsl/fopdf.xsl | 759 ++++---- src/docbkx/resources/xsl/highlight-fo.xsl | 48 +- src/docbkx/resources/xsl/highlight.xsl | 45 +- src/docbkx/resources/xsl/html.xsl | 192 +- src/docbkx/resources/xsl/html_chunk.xsl | 433 +++-- src/main/assembly/distribution.xml | 29 +- .../jar-with-dependencies.descriptor.xml | 35 +- .../elasticsearch/ElasticsearchException.java | 41 +- .../elasticsearch/annotations/Document.java | 20 +- .../data/elasticsearch/annotations/Field.java | 15 +- .../data/elasticsearch/annotations/Query.java | 26 +- .../client/NodeClientFactoryBean.java | 102 +- .../client/TransportClientFactoryBean.java | 119 +- .../config/ElasticsearchNamespaceHandler.java | 14 +- .../NodeClientBeanDefinitionParser.java | 37 +- .../TransportClientBeanDefinitionParser.java | 37 +- .../core/CriteriaQueryProcessor.java | 173 +- .../core/ElasticsearchOperations.java | 404 ++-- .../core/ElasticsearchTemplate.java | 754 ++++---- .../elasticsearch/core/MappingBuilder.java | 146 +- .../elasticsearch/core/ResultsMapper.java | 7 +- .../core/convert/DateTimeConverters.java | 6 +- .../core/convert/ElasticsearchConverter.java | 30 +- .../MappingElasticsearchConverter.java | 13 +- .../ElasticsearchPersistentEntity.java | 21 +- .../ElasticsearchPersistentProperty.java | 21 +- .../SimpleElasticsearchMappingContext.java | 2 +- .../SimpleElasticsearchPersistentEntity.java | 127 +- ...SimpleElasticsearchPersistentProperty.java | 12 +- .../core/query/AbstractQuery.java | 114 +- .../elasticsearch/core/query/Criteria.java | 24 +- .../core/query/CriteriaQuery.java | 90 +- .../elasticsearch/core/query/DeleteQuery.java | 20 +- .../data/elasticsearch/core/query/Field.java | 2 +- .../elasticsearch/core/query/GetQuery.java | 20 +- .../elasticsearch/core/query/IndexQuery.java | 74 +- .../core/query/MoreLikeThisQuery.java | 240 +-- .../core/query/NativeSearchQuery.java | 38 +- .../core/query/NativeSearchQueryBuilder.java | 104 +- .../data/elasticsearch/core/query/Query.java | 142 +- .../elasticsearch/core/query/SearchQuery.java | 11 +- .../elasticsearch/core/query/SimpleField.java | 2 +- .../elasticsearch/core/query/StringQuery.java | 38 +- .../ElasticsearchCrudRepository.java | 4 +- .../repository/ElasticsearchRepository.java | 14 +- .../cdi/ElasticsearchRepositoryBean.java | 9 +- .../cdi/ElasticsearchRepositoryExtension.java | 13 +- .../ElasticsearchRepositoriesRegistrar.java | 6 +- ...lasticsearchRepositoryConfigExtension.java | 9 +- .../EnableElasticsearchRepositories.java | 22 +- .../AbstractElasticsearchRepositoryQuery.java | 23 +- .../query/ElasticsearchPartQuery.java | 58 +- .../query/ElasticsearchQueryMethod.java | 40 +- .../query/ElasticsearchStringQuery.java | 123 +- .../parser/ElasticsearchQueryCreator.java | 177 +- .../AbstractElasticsearchRepository.java | 468 +++-- .../ElasticsearchEntityInformation.java | 11 +- ...ElasticsearchEntityInformationCreator.java | 4 +- ...ticsearchEntityInformationCreatorImpl.java | 6 +- .../ElasticsearchRepositoryFactory.java | 135 +- .../ElasticsearchRepositoryFactoryBean.java | 18 +- ...MappingElasticsearchEntityInformation.java | 123 +- .../support/NumberKeyedRepository.java | 42 +- .../SimpleElasticsearchRepository.java | 38 +- .../data/elasticsearch/Author.java | 29 +- .../data/elasticsearch/Book.java | 47 +- .../data/elasticsearch/DoubleIDEntity.java | 78 +- .../data/elasticsearch/IntegerIDEntity.java | 77 +- .../data/elasticsearch/NestedObjectTests.java | 43 +- .../data/elasticsearch/NonDocumentEntity.java | 34 +- .../elasticsearch/NonDocumentEntityTests.java | 16 +- .../data/elasticsearch/SampleEntity.java | 135 +- .../elasticsearch/SampleMappingEntity.java | 61 +- .../ElasticsearchNamespaceHandlerTests.java | 35 +- .../EnableElasticsearchRepositoriesTests.java | 29 +- .../core/ElasticsearchTemplateTests.java | 1351 +++++++------ .../core/convert/DateTimeConvertersTests.java | 68 +- .../MappingElasticsearchConverterTests.java | 48 +- ...pleElasticsearchPersistentEntityTests.java | 122 +- .../core/query/CriteriaQueryTests.java | 1317 ++++++------- .../CustomMethodRepositoryTests.java | 806 ++++---- .../repositories/DoubleIDRepository.java | 4 +- .../repositories/IntegerIDRepository.java | 2 +- .../NonDocumentEntityRepository.java | 2 +- .../SampleCustomMethodRepository.java | 42 +- .../SampleElasticSearchBookRepository.java | 2 +- .../SampleElasticsearchRepository.java | 3 +- .../support/DoubleIDRepositoryTests.java | 82 +- .../ElasticsearchRepositoryFactoryTests.java | 40 +- .../support/IntegerIDRepositoryTests.java | 82 +- .../SimpleElasticsearchRepositoryTests.java | 660 ++++--- .../custom-method-repository-test.xml | 18 +- .../resources/elasticsearch-template-test.xml | 15 +- src/test/resources/infrastructure.xml | 9 +- .../data/elasticsearch/config/namespace.xml | 15 +- .../repository-non-document-entity.xml | 17 +- .../repository-test-nested-object.xml | 17 +- src/test/resources/simple-repository-test.xml | 18 +- 107 files changed, 7804 insertions(+), 6535 deletions(-) diff --git a/formatting.xml b/formatting.xml index e69de29bb..b60c70a4e 100644 --- a/formatting.xml +++ b/formatting.xml @@ -0,0 +1,820 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 8078f6f96..51d100828 100644 --- a/pom.xml +++ b/pom.xml @@ -1,131 +1,132 @@ - - 4.0.0 - - org.springframework.data - spring-data-elasticsearch - 1.0.0.BUILD-SNAPSHOT - - + + 4.0.0 + + org.springframework.data + spring-data-elasticsearch + 1.0.0.BUILD-SNAPSHOT + + org.springframework.data.build spring-data-parent 1.1.0.BUILD-SNAPSHOT ../spring-data-build/parent/pom.xml - - Spring Data Elasticsearch - Spring Data Implementation for Elasticsearch - https://github.com/SpringSource/spring-data-elasticsearch - - - DATAES - - 3.2.1 - 2.6 - 0.90.0 - 1.9.2 - 1.6.0.BUILD-SNAPSHOT - - + Spring Data Elasticsearch + Spring Data Implementation for Elasticsearch + https://github.com/SpringSource/spring-data-elasticsearch - - - - - org.springframework - spring-context - ${spring} - - - commons-logging - commons-logging - - - - - - org.springframework - spring-tx - ${spring} - + - - - cglib - cglib - 2.2.2 - test - + DATAES - - - org.springframework.data - spring-data-commons - ${springdata.commons} - + 3.2.1 + 2.6 + 0.90.0 + 1.9.2 + 1.6.0.BUILD-SNAPSHOT - - - commons-lang - commons-lang - ${commonslang} - - - commons-collections - commons-collections - ${commonscollections} - + - - - joda-time - joda-time - ${jodatime} - + - - - org.elasticsearch - elasticsearch - ${elasticsearch} - + + + org.springframework + spring-context + ${spring} + + + commons-logging + commons-logging + + + - - - org.codehaus.jackson - jackson-mapper-asl - ${jackson} - + + org.springframework + spring-tx + ${spring} + - - - javax.enterprise - cdi-api - ${cdi} - provided - true - + + + cglib + cglib + 2.2.2 + test + - - - org.springframework - spring-test - ${spring} - test - - - org.apache.openwebbeans.test - cditest-owb - ${webbeans} - test - + + + org.springframework.data + spring-data-commons + ${springdata.commons} + - + + + commons-lang + commons-lang + ${commonslang} + + + commons-collections + commons-collections + ${commonscollections} + - - - + + + joda-time + joda-time + ${jodatime} + + + + + org.elasticsearch + elasticsearch + ${elasticsearch} + + + + + org.codehaus.jackson + jackson-mapper-asl + ${jackson} + + + + + javax.enterprise + cdi-api + ${cdi} + provided + true + + + + + org.springframework + spring-test + ${spring} + test + + + org.apache.openwebbeans.test + cditest-owb + ${webbeans} + test + + + + + + + org.apache.maven.plugins maven-assembly-plugin @@ -133,38 +134,39 @@ org.codehaus.mojo wagon-maven-plugin - - + + - - - biomedcentral - BioMed Central Development Team - +0 - - - - + + + biomedcentral + BioMed Central Development Team + +0 + + + + spring-libs-snapshot http://repo.springsource.org/lib-snapshot-local - + - https://github.com/SpringSource/spring-data-elasticsearch - scm:git:git://github.com/SpringSource/spring-data-elasticsearch.git - scm:git:ssh://git@github.com:SpringSource/spring-data-elasticsearch.git - - - - Bamboo - http://build.springsource.org/browse/SPRINGDATAESh - - - - JIRA - https://jira.springsource.org/browse/DATAES + https://github.com/SpringSource/spring-data-elasticsearch + scm:git:git://github.com/SpringSource/spring-data-elasticsearch.git + scm:git:ssh://git@github.com:SpringSource/spring-data-elasticsearch.git + + + + + Bamboo + http://build.springsource.org/browse/SPRINGDATAES + + + + JIRA + https://jira.springsource.org/browse/DATAES diff --git a/src/docbkx/index.xml b/src/docbkx/index.xml index 32621e38e..05f60dde7 100644 --- a/src/docbkx/index.xml +++ b/src/docbkx/index.xml @@ -5,11 +5,11 @@ Spring Data Elasticsearch - - BioMed Central - Development Team - - + + BioMed Central + Development Team + + Copies of this document may be made for your own use and for @@ -35,8 +35,10 @@ Reference Documentation - - + + diff --git a/src/docbkx/preface.xml b/src/docbkx/preface.xml index d376dadd3..2872ded1c 100644 --- a/src/docbkx/preface.xml +++ b/src/docbkx/preface.xml @@ -3,13 +3,16 @@ "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd"> Preface - The Spring Data Elasticsearch project applies core Spring concepts to + The Spring Data Elasticsearch project applies core Spring + concepts to the - development of solutions using the Elasticsearch Search Engine. + development of solutions using the Elasticsearch Search + Engine. We have povided a "template" as a high-level abstraction for - storing,querying,sorting and faceting documents. You will notice similarities - to the Spring data solr and - mongodb support in the Spring Framework. + storing,querying,sorting and faceting documents. You will notice + similarities + to the Spring data solr and + mongodb support in the Spring Framework.
Project Metadata @@ -17,7 +20,8 @@ Version Control - - git://github.com/BioMedCentralLtd/spring-data-elasticsearch.git + git://github.com/BioMedCentralLtd/spring-data-elasticsearch.git @@ -28,7 +32,8 @@ Requires Elasticsearch - 0.20.2 and above or optional dependency or not even that if you are using Embedded Node Client - + 0.20.2 and above or optional dependency or not even that if you are + using Embedded Node Client +
\ No newline at end of file diff --git a/src/docbkx/reference/data-elasticsearch.xml b/src/docbkx/reference/data-elasticsearch.xml index 77e733330..ee3460570 100644 --- a/src/docbkx/reference/data-elasticsearch.xml +++ b/src/docbkx/reference/data-elasticsearch.xml @@ -15,8 +15,10 @@ Spring Namespace - The Spring Data Elasticsearch module contains a custom namespace allowing - definition of repository beans as well as elements for instantiating + The Spring Data Elasticsearch module contains a custom namespace + allowing + definition of repository beans as well as elements for + instantiating a ElasticsearchServer . @@ -32,7 +34,7 @@ Setting up Elasticsearch repositories using Namespace -<?xml version="1.0" encoding="UTF-8"?> + <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch" @@ -56,7 +58,7 @@ http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1. Transport Client using Namespace -<?xml version="1.0" encoding="UTF-8"?> + <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch" @@ -71,7 +73,7 @@ http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1. Node Client using Namespace -<?xml version="1.0" encoding="UTF-8"?> + <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch" @@ -87,13 +89,15 @@ http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.
Annotation based configuration - The Spring Data Elasticsearch repositories support cannot only be + The Spring Data Elasticsearch repositories support cannot only + be activated through an XML namespace but also using an annotation through JavaConfig. - Spring Data Elasticsearch repositories using JavaConfig - + Spring Data Elasticsearch repositories using JavaConfig + + @Configuration @EnableElasticsearchRepositories(basePackages = "org/springframework/data/elasticsearch/repositories") static class Config { @@ -122,12 +126,14 @@ return new ElasticsearchTemplate(nodeBuilder().local(true).node().client());
Elasticsearch Repositores using CDI - The Spring Data Elasticsearch repositories can also be set up using CDI + The Spring Data Elasticsearch repositories can also be set up + using CDI functionality. - Spring Data Elasticsearch repositories using JavaConfig -class ElasticsearchTemplateProducer { + Spring Data Elasticsearch repositories using JavaConfig + + class ElasticsearchTemplateProducer { @Produces @ApplicationScoped @@ -157,9 +163,11 @@ public void setRepository(ProductRepository repository) {
Query lookup strategies - The Elasticsearch module supports all basic query building feature as String,Abstract,Criteria or + The Elasticsearch module supports all basic query building + feature as String,Abstract,Criteria or have - it being derived from the method name. + it being derived from the + method name. @@ -180,11 +188,13 @@ public void setRepository(ProductRepository repository) { Query creation - Generally the query creation mechanism for Elasticsearch works as described + Generally the query creation mechanism for Elasticsearch works as + described in . Here's a short example - of what a Elasticsearch query method translates into: + of what a Elasticsearch query method + translates into: Query creation from method names public interface BookRepository extends Repository<Book, String> { @@ -192,7 +202,7 @@ public void setRepository(ProductRepository repository) { } The method name above will be translated into the following - Elasticsearch json query + Elasticsearch json query { "bool" : @@ -227,7 +237,8 @@ public void setRepository(ProductRepository repository) { findByNameAndPrice - {"bool" : {"must" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}} + {"bool" : {"must" : [ {"field" : {"name" : "?"}}, + {"field" : {"price" : "?"}} ]}} @@ -238,7 +249,8 @@ public void setRepository(ProductRepository repository) { findByNameOrPrice - {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}} + {"bool" : {"should" : [ {"field" : {"name" : "?"}}, + {"field" : {"price" : "?"}} ]}} @@ -260,7 +272,8 @@ public void setRepository(ProductRepository repository) { findByNameNot - {"bool" : {"must_not" : {"field" : {"name" : "?"}}}} + {"bool" : {"must_not" : {"field" : {"name" : "?"}}}} + @@ -271,7 +284,9 @@ public void setRepository(ProductRepository repository) { findByPriceBetween - {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}} + {"bool" : {"must" : {"range" : {"price" : {"from" : + ?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}} + @@ -282,7 +297,9 @@ public void setRepository(ProductRepository repository) { findByPriceLessThan - {"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}} + {"bool" : {"must" : {"range" : {"price" : {"from" : + null,"to" : ?,"include_lower" : true,"include_upper" : + true}}}}} @@ -293,7 +310,9 @@ public void setRepository(ProductRepository repository) { findByPriceGreaterThan - {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}} + {"bool" : {"must" : {"range" : {"price" : {"from" : + ?,"to" : null,"include_lower" : true,"include_upper" : + true}}}}} @@ -304,7 +323,9 @@ public void setRepository(ProductRepository repository) { findByPriceBefore - {"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}} + {"bool" : {"must" : {"range" : {"price" : {"from" : + null,"to" : ?,"include_lower" : true,"include_upper" : + true}}}}} @@ -315,7 +336,9 @@ public void setRepository(ProductRepository repository) { findByPriceAfter - {"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}} + {"bool" : {"must" : {"range" : {"price" : {"from" : + ?,"to" : null,"include_lower" : true,"include_upper" : + true}}}}} @@ -326,7 +349,8 @@ public void setRepository(ProductRepository repository) { findByNameLike - {"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}} + {"bool" : {"must" : {"field" : {"name" : {"query" : + "?*","analyze_wildcard" : true}}}}} @@ -337,7 +361,8 @@ public void setRepository(ProductRepository repository) { findByNameStartingWith - {"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}} + {"bool" : {"must" : {"field" : {"name" : {"query" : + "?*","analyze_wildcard" : true}}}}} @@ -348,7 +373,8 @@ public void setRepository(ProductRepository repository) { findByNameEndingWith - {"bool" : {"must" : {"field" : {"name" : {"query" : "*?","analyze_wildcard" : true}}}}} + {"bool" : {"must" : {"field" : {"name" : {"query" : + "*?","analyze_wildcard" : true}}}}} @@ -359,7 +385,8 @@ public void setRepository(ProductRepository repository) { findByNameContaining - {"bool" : {"must" : {"field" : {"name" : {"query" : "*?*","analyze_wildcard" : true}}}}} + {"bool" : {"must" : {"field" : {"name" : {"query" : + "*?*","analyze_wildcard" : true}}}}} @@ -370,7 +397,8 @@ public void setRepository(ProductRepository repository) { findByNameIn(Collection<String>names) - {"bool" : {"must" : {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}} + {"bool" : {"must" : {"bool" : {"should" : [ {"field" : + {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}} @@ -381,7 +409,8 @@ public void setRepository(ProductRepository repository) { findByNameNotIn(Collection<String>names) - {"bool" : {"must_not" : {"bool" : {"should" : {"field" : {"name" : "?"}}}}}} + {"bool" : {"must_not" : {"bool" : {"should" : {"field" : + {"name" : "?"}}}}}} @@ -403,7 +432,8 @@ public void setRepository(ProductRepository repository) { findByAvailableTrue - {"bool" : {"must" : {"field" : {"available" : true}}}} + {"bool" : {"must" : {"field" : {"available" : true}}}} + @@ -414,7 +444,8 @@ public void setRepository(ProductRepository repository) { findByAvailableFalse - {"bool" : {"must" : {"field" : {"available" : false}}}} + {"bool" : {"must" : {"field" : {"available" : false}}}} + @@ -425,7 +456,8 @@ public void setRepository(ProductRepository repository) { findByAvailableTrueOrderByNameDesc - {"sort" : [{ "name" : {"order" : "desc"} }],"bool" : {"must" : {"field" : {"available" : true}}}} + {"sort" : [{ "name" : {"order" : "desc"} }],"bool" : + {"must" : {"field" : {"available" : true}}}} diff --git a/src/docbkx/reference/elasticsearch-misc.xml b/src/docbkx/reference/elasticsearch-misc.xml index a5c3f935a..78aece686 100644 --- a/src/docbkx/reference/elasticsearch-misc.xml +++ b/src/docbkx/reference/elasticsearch-misc.xml @@ -6,9 +6,10 @@ This chapter covers additional support for Elasticsearch operations - that cannot be directly accessed via the repository + that cannot be directly accessed via the repository interface. - It is recommended to add those operations as custom + It is + recommended to add those operations as custom implementation as described in @@ -21,7 +22,7 @@ Filter Builder improves query speed. - + private ElasticsearchTemplate elasticsearchTemplate; SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(matchAllQuery()) @@ -31,18 +32,19 @@ Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(sea
-
- Using Scan And Scroll For Big Result Set - - Elasticsearch has scan and scroll feature for getting big result set in chunks. - ElasticsearchTemplate - has scan and scroll methods that can be used as below. - - - - Using Scan and Scroll - - +
+ Using Scan And Scroll For Big Result Set + + Elasticsearch has scan and scroll feature for getting big result set + in chunks. + ElasticsearchTemplate + has scan and scroll methods that can be used as below. + + + + Using Scan and Scroll + + SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(matchAllQuery()) .withIndices("test-index") @@ -78,6 +80,6 @@ for(SearchHit searchHit : response.getHits()){ } } } - -
+
+
\ No newline at end of file diff --git a/src/docbkx/reference/repositories.xml b/src/docbkx/reference/repositories.xml index e9bd00853..b473c297e 100644 --- a/src/docbkx/reference/repositories.xml +++ b/src/docbkx/reference/repositories.xml @@ -2,70 +2,89 @@ - Repositories + Repositories -
- Introduction +
+ Introduction - Implementing a data access layer of an application has been - cumbersome for quite a while. Too much boilerplate code had to be written. - Domain classes were anemic and not designed in a real object oriented or - domain driven manner. + Implementing a data access layer of an application has been + cumbersome for quite a while. Too much boilerplate code had to be + written. + Domain classes were anemic and not designed in a real object oriented or + domain driven manner. + - Using both of these technologies makes developers life a lot easier - regarding rich domain model's persistence. Nevertheless the amount of - boilerplate code to implement repositories especially is still quite high. - So the goal of the repository abstraction of Spring Data is to reduce the - effort to implement data access layers for various persistence stores - significantly. + Using both of these technologies makes developers life a lot + easier + regarding rich domain model's persistence. Nevertheless the amount of + boilerplate code to implement repositories especially is still quite + high. + So the goal of the repository abstraction of Spring Data is to reduce + the + effort to implement data access layers for various persistence stores + significantly. + - The following chapters will introduce the core concepts and - interfaces of Spring Data repositories in general for detailled - information on the specific features of a particular store consult the - later chapters of this document. + The following chapters will introduce the core concepts and + interfaces of Spring Data repositories in general for detailled + information on the specific features of a particular store consult + the + later chapters of this document. + - - As this part of the documentation is pulled in from Spring Data - Commons we have to decide for a particular module to be used as example. - The configuration and code samples in this chapter are using the JPA - module. Make sure you adapt e.g. the XML namespace declaration, types to - be extended to the equivalents of the module you're actually - using. - -
+ + As this part of the documentation is pulled in from Spring Data + Commons we have to decide for a particular module to be used as + example. + The configuration and code samples in this chapter are using the JPA + module. Make sure you adapt e.g. the XML namespace declaration, + types to + be extended to the equivalents of the module you're actually + using. + + +
-
- Core concepts +
+ Core concepts - The central interface in Spring Data repository abstraction is - Repository (probably not that much of a - surprise). It is typeable to the domain class to manage as well as the id - type of the domain class. This interface mainly acts as marker interface - to capture the types to deal with and help us when discovering interfaces - that extend this one. Beyond that there's - CrudRepository which provides some - sophisticated functionality around CRUD for the entity being - managed. + + The central interface in Spring Data repository abstraction is + Repository + (probably not that much of a + surprise). It is typeable to the domain class to manage as well as the id + type of the domain class. This interface mainly acts as marker interface + to capture the types to deal with and help us when discovering + interfaces + that extend this one. Beyond that there's + CrudRepository + which provides some + sophisticated functionality around CRUD for the entity being + managed. + - - <interfacename>CrudRepository</interfacename> interface + + + <interfacename>CrudRepository</interfacename> + interface + - - - + + + - + - + - + - + - - + + - public interface CrudRepository<T, ID extends Serializable> + public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> { T save(T entity); @@ -83,88 +102,107 @@ // … more functionality omitted. } - - - Saves the given entity. - + + + Saves the given entity. + - - Returns the entity identified by the given id. - + + Returns the entity identified by the given id. + - - Returns all entities. - + + Returns all entities. + - - Returns the number of entities. - + + Returns the number of entities. + - - Deletes the given entity. - + + Deletes the given entity. + - - Returns whether an entity with the given id exists. - - - - + + Returns whether an entity with the given id exists. + + + + - Usually we will have persistence technology specific sub-interfaces - to include additional technology specific methods. We will now ship - implementations for a variety of Spring Data modules that implement this - interface. + Usually we will have persistence technology specific + sub-interfaces + to include additional technology specific methods. We will now ship + implementations for a variety of Spring Data modules that implement + this + interface. + - On top of the CrudRepository there is - a PagingAndSortingRepository abstraction - that adds additional methods to ease paginated access to entities: + + On top of the + CrudRepository + there is + a + PagingAndSortingRepository + abstraction + that adds additional methods to ease paginated access to entities: + - - PagingAndSortingRepository + + PagingAndSortingRepository - public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> { + public interface PagingAndSortingRepository<T, ID extends Serializable> extends CrudRepository<T, ID> { Iterable<T> findAll(Sort sort); Page<T> findAll(Pageable pageable); } - + - Accessing the second page of User by a page - size of 20 you could simply do something like this: + + Accessing the second page of + User + by a page + size of 20 you could simply do something like this: + - PagingAndSortingRepository<User, Long> repository = // … get access to a bean + PagingAndSortingRepository<User, Long> repository = // … get access to a bean Page<User> users = repository.findAll(new PageRequest(1, 20)); -
+
-
- Query methods +
+ Query methods - Next to standard CRUD functionality repositories are usually queries - on the underlying datastore. With Spring Data declaring those queries - becomes a four-step process: + Next to standard CRUD functionality repositories are usually + queries + on the underlying datastore. With Spring Data declaring those queries + becomes a four-step process: + - - - Declare an interface extending - Repository or one of its sub-interfaces - and type it to the domain class it shall handle. + + + + Declare an interface extending + Repository + or one of its sub-interfaces + and type it to the domain class it shall handle. + - public interface PersonRepository extends Repository<User, Long> { … } - + public interface PersonRepository extends Repository<User, Long> { … } + - - Declare query methods on the interface. + + Declare query methods on the interface. - List<Person> findByLastname(String lastname); - + List<Person> findByLastname(String lastname); + - - Setup Spring to create proxy instances for those - interfaces. + + Setup Spring to create proxy instances for those + interfaces. + - <?xml version="1.0" encoding="UTF-8"?> + <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/data/jpa" @@ -177,19 +215,25 @@ </beans> - - Note that we use the JPA namespace here just by example. If - you're using the repository abstraction for any other store you need - to change this to the appropriate namespace declaration of your - store module which should be exchanging jpa in favor of - e.g. mongodb. - - + + + Note that we use the JPA namespace here just by example. If + you're using the repository abstraction for any other store you need + to change this to the appropriate namespace declaration of your + store module which should be exchanging + jpa + in favor of + e.g. + mongodb + . + + + - - Get the repository instance injected and use it. + + Get the repository instance injected and use it. - public class SomeClient { + public class SomeClient { @Autowired private PersonRepository repository; @@ -197,44 +241,61 @@ public void doSomething() { List<Person> persons = repository.findByLastname("Matthews"); } - - + + - At this stage we barely scratched the surface of what's possible - with the repositories but the general approach should be clear. Let's go - through each of these steps and figure out details and various options - that you have at each stage. + At this stage we barely scratched the surface of what's possible + with the repositories but the general approach should be clear. Let's + go + through each of these steps and figure out details and various options + that you have at each stage. + -
- Defining repository interfaces +
+ Defining repository interfaces - As a very first step you define a domain class specific repository - interface. It's got to extend Repository - and be typed to the domain class and an ID type. If you want to expose - CRUD methods for that domain type, extend - CrudRepository instead of - Repository. + + As a very first step you define a domain class specific repository + interface. It's got to extend + Repository + and be typed to the domain class and an ID type. If you want to + expose + CRUD methods for that domain type, extend + CrudRepository + instead of + Repository + . + -
- Fine tuning repository definition +
+ Fine tuning repository definition - Usually you will have your repository interface extend - Repository, - CrudRepository or - PagingAndSortingRepository. If you - don't like extending Spring Data interfaces at all you can also - annotate your repository interface with - @RepositoryDefinition. Extending - CrudRepository will expose a complete - set of methods to manipulate your entities. If you would rather be - selective about the methods being exposed, simply copy the ones you - want to expose from CrudRepository into - your domain repository. + + Usually you will have your repository interface extend + Repository + , + CrudRepository + or + PagingAndSortingRepository + . If you + don't like extending Spring Data interfaces at all you can also + annotate your repository interface with + @RepositoryDefinition + . Extending + CrudRepository + will expose a complete + set of methods to manipulate your entities. If you would rather be + selective about the methods being exposed, simply copy the ones you + want to expose from + CrudRepository + into + your domain repository. + - - Selectively exposing CRUD methods + + Selectively exposing CRUD methods - interface MyBaseRepository<T, ID extends Serializable> extends Repository<T, ID> { + interface MyBaseRepository<T, ID extends Serializable> extends Repository<T, ID> { T findOne(ID id); T save(T entity); } @@ -243,205 +304,307 @@ User findByEmailAddress(EmailAddress emailAddress); } - + - In the first step we define a common base interface for all our - domain repositories and expose findOne(…) as - well as save(…).These methods will be routed - into the base repository implementation of the store of your choice - because they are matching the method signatures in - CrudRepository. So our - UserRepository will now be able to save - users, find single ones by id as well as triggering a query to find - Users by their email address. -
-
+ + In the first step we define a common base interface for all our + domain repositories and expose + findOne(…) + as + well as + save(…) + .These methods will be routed + into the base repository implementation of the store of your choice + because they are matching the method signatures in + CrudRepository + . So our + UserRepository + will now be able to save + users, find single ones by id as well as triggering a query to find + User + s by their email address. + +
+
-
- Defining query methods +
+ Defining query methods -
- Query lookup strategies +
+ Query lookup strategies - The next thing we have to discuss is the definition of query - methods. There are two main ways that the repository proxy is able to - come up with the store specific query from the method name. The first - option is to derive the query from the method name directly, the - second is using some kind of additionally created query. What detailed - options are available pretty much depends on the actual store, - however, there's got to be some algorithm that decides what actual - query is created. + The next thing we have to discuss is the definition of query + methods. There are two main ways that the repository proxy is able + to + come up with the store specific query from the method name. The first + option is to derive the query from the method name directly, the + second is using some kind of additionally created query. What + detailed + options are available pretty much depends on the actual store, + however, there's got to be some algorithm that decides what actual + query is created. + - There are three strategies available for the repository - infrastructure to resolve the query. The strategy to be used can be - configured at the namespace through the - query-lookup-strategy attribute. However, It might be the - case that some of the strategies are not supported for specific - datastores. Here are your options: + + There are three strategies available for the repository + infrastructure to resolve the query. The strategy to be used can be + configured at the namespace through the + query-lookup-strategy + attribute. However, It might be the + case that some of the strategies are not supported for specific + datastores. Here are your options: + - - CREATE + + CREATE - This strategy will try to construct a store specific query - from the query method's name. The general approach is to remove a - given set of well-known prefixes from the method name and parse the - rest of the method. Read more about query construction in . - + + This strategy will try to construct a store specific query + from the query method's name. The general approach is to remove a + given set of well-known prefixes from the method name and parse + the + rest of the method. Read more about query construction in + + . + + - - USE_DECLARED_QUERY + + USE_DECLARED_QUERY - This strategy tries to find a declared query which will be - used for execution first. The query could be defined by an - annotation somewhere or declared by other means. Please consult the - documentation of the specific store to find out what options are - available for that store. If the repository infrastructure does not - find a declared query for the method at bootstrap time it will - fail. - + This strategy tries to find a declared query which will be + used for execution first. The query could be defined by an + annotation somewhere or declared by other means. Please consult + the + documentation of the specific store to find out what options are + available for that store. If the repository infrastructure does not + find a declared query for the method at bootstrap time it will + fail. + + - - CREATE_IF_NOT_FOUND (default) + + CREATE_IF_NOT_FOUND (default) - This strategy is actually a combination of CREATE - and USE_DECLARED_QUERY. It will try to lookup a - declared query first but create a custom method name based query if - no declared query was found. This is the default lookup strategy and - thus will be used if you don't configure anything explicitly. It - allows quick query definition by method names but also custom tuning - of these queries by introducing declared queries as needed. - -
+ + This strategy is actually a combination of + CREATE + and + USE_DECLARED_QUERY + . It will try to lookup a + declared query first but create a custom method name based query if + no declared query was found. This is the default lookup strategy and + thus will be used if you don't configure anything explicitly. It + allows quick query definition by method names but also custom + tuning + of these queries by introducing declared queries as needed. + + +
-
- Query creation +
+ Query creation - The query builder mechanism built into Spring Data repository - infrastructure is useful to build constraining queries over entities - of the repository. We will strip the prefixes findBy, - find, readBy, read, - getBy as well as get from the method and - start parsing the rest of it. At a very basic level you can define - conditions on entity properties and concatenate them with - AND and OR. + + The query builder mechanism built into Spring Data repository + infrastructure is useful to build constraining queries over + entities + of the repository. We will strip the prefixes + findBy + , + find + , + readBy + , + read + , + getBy + as well as + get + from the method and + start parsing the rest of it. At a very basic level you can define + conditions on entity properties and concatenate them with + AND + and + OR + . + - - Query creation from method names + + Query creation from method names - public interface PersonRepository extends Repository<User, Long> { + + public interface PersonRepository extends Repository<User, Long> { List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname); - } - + } + + - The actual result of parsing that method will of course depend - on the persistence store we create the query for, however, there are - some general things to notice. The expressions are usually property - traversals combined with operators that can be concatenated. As you - can see in the example you can combine property expressions with And - and Or. Beyond that you also get support for various operators like - Between, LessThan, - GreaterThan, Like for the - property expressions. As the operators supported can vary from - datastore to datastore please consult the according part of the - reference documentation. + + The actual result of parsing that method will of course depend + on the persistence store we create the query for, however, there are + some general things to notice. The expressions are usually property + traversals combined with operators that can be concatenated. As you + can see in the example you can combine property expressions with + And + and Or. Beyond that you also get support for various operators like + Between + , + LessThan + , + GreaterThan + , + Like + for the + property expressions. As the operators supported can vary from + datastore to datastore please consult the according part of the + reference documentation. + -
- Property expressions +
+ Property expressions - Property expressions can just refer to a direct property of - the managed entity (as you just saw in the example above). On query - creation time we already make sure that the parsed property is at a - property of the managed domain class. However, you can also define - constraints by traversing nested properties. Assume - Persons have Addresses - with ZipCodes. In that case a method name - of + + Property expressions can just refer to a direct property of + the managed entity (as you just saw in the example above). On query + creation time we already make sure that the parsed property is at + a + property of the managed domain class. However, you can also define + constraints by traversing nested properties. Assume + Person + s have + Address + es + with + ZipCode + s. In that case a method name + of + - List<Person> findByAddressZipCode(ZipCode zipCode); + List<Person> findByAddressZipCode(ZipCode zipCode); - will create the property traversal - x.address.zipCode. The resolution algorithm starts with - interpreting the entire part (AddressZipCode) as - property and checks the domain class for a property with that name - (uncapitalized). If it succeeds it just uses that. If not it starts - splitting up the source at the camel case parts from the right side - into a head and a tail and tries to find the according property, - e.g. AddressZip and Code. If - we find a property with that head we take the tail and continue - building the tree down from there. As in our case the first split - does not match we move the split point to the left - (Address, ZipCode). + + will create the property traversal + x.address.zipCode + . The resolution algorithm starts with + interpreting the entire part ( + AddressZipCode + ) as + property and checks the domain class for a property with that name + (uncapitalized). If it succeeds it just uses that. If not it + starts + splitting up the source at the camel case parts from the right side + into a head and a tail and tries to find the according property, + e.g. + AddressZip + and + Code + . If + we find a property with that head we take the tail and continue + building the tree down from there. As in our case the first split + does not match we move the split point to the left + ( + Address + , + ZipCode + ). + - Although this should work for most cases, there might be cases - where the algorithm could select the wrong property. Suppose our - Person class has an addressZip - property as well. Then our algorithm would match in the first split - round already and essentially choose the wrong property and finally - fail (as the type of addressZip probably has - no code property). To resolve this ambiguity you can use - _ inside your method name to manually define - traversal points. So our method name would end up like so: + + Although this should work for most cases, there might be cases + where the algorithm could select the wrong property. Suppose our + Person + class has an + addressZip + property as well. Then our algorithm would match in the first + split + round already and essentially choose the wrong property and finally + fail (as the type of + addressZip + probably has + no code property). To resolve this ambiguity you can use + _ + inside your method name to manually define + traversal points. So our method name would end up like so: + - List<Person> findByAddress_ZipCode(ZipCode zipCode); + List<Person> findByAddress_ZipCode(ZipCode zipCode); -
-
+
+
-
- Special parameter handling +
+ Special parameter handling - To hand parameters to your query you simply define method - parameters as already seen in the examples above. Besides that we will - recognizes certain specific types to apply pagination and sorting to - your queries dynamically. + To hand parameters to your query you simply define method + parameters as already seen in the examples above. Besides that we + will + recognizes certain specific types to apply pagination and sorting to + your queries dynamically. + - - Using Pageable and Sort in query methods + + Using Pageable and Sort in query methods - Page<User> findByLastname(String lastname, Pageable pageable); + Page<User> findByLastname(String lastname, Pageable pageable); List<User> findByLastname(String lastname, Sort sort); List<User> findByLastname(String lastname, Pageable pageable); - + - The first method allows you to pass a Pageable - instance to the query method to dynamically add paging to your - statically defined query. Sorting options are handed via - the Pageable instance too. If you only - need sorting, simply add a Sort parameter to your method. - As you also can see, simply returning a - List is possible as well. We will then - not retrieve the additional metadata required to build the actual - Page instance but rather simply - restrict the query to lookup only the given range of entities. + + The first method allows you to pass a + Pageable + instance to the query method to dynamically add paging to your + statically defined query. + Sorting + options are handed via + the + Pageable + instance too. If you only + need sorting, simply add a + Sort + parameter to your method. + As you also can see, simply returning a + List + is possible as well. We will then + not retrieve the additional metadata required to build the actual + Page + instance but rather simply + restrict the query to lookup only the given range of entities. + - - To find out how many pages you get for a query entirely we - have to trigger an additional count query. This will be derived from - the query you actually trigger by default. - -
-
+ + To find out how many pages you get for a query entirely we + have to trigger an additional count query. This will be derived + from + the query you actually trigger by default. + + +
+
-
- Creating repository instances +
+ Creating repository instances - So now the question is how to create instances and bean - definitions for the repository interfaces defined. + So now the question is how to create instances and bean + definitions for the repository interfaces defined. + -
- XML Configuration +
+ XML Configuration - The easiest way to do so is by using the Spring namespace that - is shipped with each Spring Data module that supports the repository - mechanism. Each of those includes a repositories element that allows - you to simply define a base package that Spring will scan for - you. + The easiest way to do so is by using the Spring namespace that + is shipped with each Spring Data module that supports the + repository + mechanism. Each of those includes a repositories element that allows + you to simply define a base package that Spring will scan for + you. + - <?xml version="1.0" encoding="UTF-8"?> + <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/data/jpa" @@ -454,75 +617,109 @@ </beans:beans> - In this case we instruct Spring to scan - com.acme.repositories and all its sub packages for - interfaces extending Repository or one - of its sub-interfaces. For each interface found it will register the - persistence technology specific - FactoryBean to create the according - proxies that handle invocations of the query methods. Each of these - beans will be registered under a bean name that is derived from the - interface name, so an interface of - UserRepository would be registered - under userRepository. The base-package - attribute allows the use of wildcards, so that you can have a pattern - of scanned packages. + + In this case we instruct Spring to scan + com.acme.repositories + and all its sub packages for + interfaces extending + Repository + or one + of its sub-interfaces. For each interface found it will register the + persistence technology specific + FactoryBean + to create the according + proxies that handle invocations of the query methods. Each of these + beans will be registered under a bean name that is derived from the + interface name, so an interface of + UserRepository + would be registered + under + userRepository + . The + base-package + attribute allows the use of wildcards, so that you can have a + pattern + of scanned packages. + - - Using filters + + Using filters - By default we will pick up every interface extending the - persistence technology specific - Repository sub-interface located - underneath the configured base package and create a bean instance - for it. However, you might want finer grained control over which - interfaces bean instances get created for. To do this we support the - use of <include-filter /> and - <exclude-filter /> elements inside - <repositories />. The semantics are exactly - equivalent to the elements in Spring's context namespace. For - details see Spring reference documentation on these - elements. + + By default we will pick up every interface extending the + persistence technology specific + Repository + sub-interface located + underneath the configured base package and create a bean instance + for it. However, you might want finer grained control over which + interfaces bean instances get created for. To do this we support + the + use of + <include-filter /> + and + <exclude-filter /> + elements inside + <repositories /> + . The semantics are exactly + equivalent to the elements in Spring's context namespace. For + details see + Spring reference documentation + on these + elements. + - E.g. to exclude certain interfaces from instantiation as - repository, you could use the following configuration: + E.g. to exclude certain interfaces from instantiation as + repository, you could use the following configuration: + - - Using exclude-filter element + + Using exclude-filter element - <repositories base-package="com.acme.repositories"> + <repositories base-package="com.acme.repositories"> <context:exclude-filter type="regex" expression=".*SomeRepository" /> </repositories> - This would exclude all interfaces ending in - SomeRepository from being - instantiated. - - -
+ + This would exclude all interfaces ending in + SomeRepository + from being + instantiated. + + + +
-
- JavaConfig +
+ JavaConfig - The repository infrastructure can also be triggered using a - store-specific - @Enable${store}Repositories annotation - on a JavaConfig class. For an introduction into Java based - configuration of the Spring container please have a look at the - reference documentation. - JavaConfig in the Spring reference documentation - - + + The repository infrastructure can also be triggered using a + store-specific + @Enable${store}Repositories + annotation + on a JavaConfig class. For an introduction into Java based + configuration of the Spring container please have a look at the + reference documentation. + + + JavaConfig in the Spring reference documentation - + + + + - A sample configuration to enable Spring Data repositories would - look something like this. + A sample configuration to enable Spring Data repositories + would + look something like this. + - - Sample annotation based repository configuration + + Sample annotation based repository configuration - @Configuration + @Configuration @EnableJpaRepositories("com.acme.repositories") class ApplicationConfiguration { @@ -531,179 +728,231 @@ // … } } - + - Note that the sample uses the JPA specific annotation which - would have to be exchanged dependingon which store module you actually - use. The same applies to the definition of the - EntityManagerFactory bean. Please - consult the sections covering the store-specific configuration. -
+ + Note that the sample uses the JPA specific annotation which + would have to be exchanged dependingon which store module you actually + use. The same applies to the definition of the + EntityManagerFactory + bean. Please + consult the sections covering the store-specific configuration. + +
-
- Standalone usage +
+ Standalone usage - You can also use the repository infrastructure outside of a - Spring container usage. You will still need to have some of the Spring - libraries on your classpath but you can generally setup repositories - programmatically as well. The Spring Data modules providing repository - support ship a persistence technology specific - RepositoryFactory that can be used as - follows: + + You can also use the repository infrastructure outside of a + Spring container usage. You will still need to have some of the Spring + libraries on your classpath but you can generally setup + repositories + programmatically as well. The Spring Data modules providing repository + support ship a persistence technology specific + RepositoryFactory + that can be used as + follows: + - - Standalone usage of repository factory + + Standalone usage of repository factory - RepositoryFactorySupport factory = … // Instantiate factory here + RepositoryFactorySupport factory = … // Instantiate factory here UserRepository repository = factory.getRepository(UserRepository.class); - -
-
-
+ +
+
+
-
- Custom implementations +
+ Custom implementations -
- Adding behaviour to single repositories +
+ Adding behaviour to single repositories - Often it is necessary to provide a custom implementation for a few - repository methods. Spring Data repositories easily allow you to provide - custom repository code and integrate it with generic CRUD abstraction - and query method functionality. To enrich a repository with custom - functionality you have to define an interface and an implementation for - that functionality first and let the repository interface you provided - so far extend that custom interface. + Often it is necessary to provide a custom implementation for a + few + repository methods. Spring Data repositories easily allow you to provide + custom repository code and integrate it with generic CRUD + abstraction + and query method functionality. To enrich a repository with custom + functionality you have to define an interface and an implementation + for + that functionality first and let the repository interface you provided + so far extend that custom interface. + - - Interface for custom repository functionality + + Interface for custom repository functionality - interface UserRepositoryCustom { + interface UserRepositoryCustom { public void someCustomMethod(User user); } - + - - Implementation of custom repository functionality + + Implementation of custom repository functionality - class UserRepositoryImpl implements UserRepositoryCustom { + + class UserRepositoryImpl implements UserRepositoryCustom { public void someCustomMethod(User user) { // Your custom implementation } - }Note that the implementation itself does not depend on - Spring Data and can be a regular Spring bean. So you can use standard - dependency injection behaviour to inject references to other beans, - take part in aspects and so on. - + } + Note that the implementation itself does not depend on + Spring Data and can be a regular Spring bean. So you can use standard + dependency injection behaviour to inject references to other beans, + take part in aspects and so on. + + - - Changes to the your basic repository interface + + Changes to the your basic repository interface - public interface UserRepository extends CrudRepository<User, Long>, UserRepositoryCustom { + + public interface UserRepository extends CrudRepository<User, Long>, UserRepositoryCustom { // Declare query methods here - }Let your standard repository interface extend the custom - one. This makes CRUD and custom functionality available to - clients. - + } + Let your standard repository interface extend the custom + one. This makes CRUD and custom functionality available to + clients. + + - - Configuration + + Configuration - If you use namespace configuration the repository infrastructure - tries to autodetect custom implementations by looking up classes in - the package we found a repository using the naming conventions - appending the namespace element's attribute - repository-impl-postfix to the classname. This suffix - defaults to Impl. + + If you use namespace configuration the repository infrastructure + tries to autodetect custom implementations by looking up classes in + the package we found a repository using the naming conventions + appending the namespace element's attribute + repository-impl-postfix + to the classname. This suffix + defaults to + Impl + . + - - Configuration example + + Configuration example - <repositories base-package="com.acme.repository" /> + + <repositories base-package="com.acme.repository" /> - <repositories base-package="com.acme.repository" repository-impl-postfix="FooBar" /> - + <repositories base-package="com.acme.repository" repository-impl-postfix="FooBar" /> + + - The first configuration example will try to lookup a class - com.acme.repository.UserRepositoryImpl to act - as custom repository implementation, where the second example will try - to lookup - com.acme.repository.UserRepositoryFooBar. - + + The first configuration example will try to lookup a class + com.acme.repository.UserRepositoryImpl + to act + as custom repository implementation, where the second example will + try + to lookup + com.acme.repository.UserRepositoryFooBar + . + + - - Manual wiring + + Manual wiring - The approach above works perfectly well if your custom - implementation uses annotation based configuration and autowiring - entirely as it will be treated as any other Spring bean. If your - custom implementation bean needs some special wiring you simply - declare the bean and name it after the conventions just described. We - will then pick up the custom bean by name rather than creating an - instance. + The approach above works perfectly well if your custom + implementation uses annotation based configuration and autowiring + entirely as it will be treated as any other Spring bean. If your + custom implementation bean needs some special wiring you simply + declare the bean and name it after the conventions just described. + We + will then pick up the custom bean by name rather than creating an + instance. + - - Manual wiring of custom implementations (I) + + Manual wiring of custom implementations (I) - <repositories base-package="com.acme.repository" /> + <repositories base-package="com.acme.repository" /> <beans:bean id="userRepositoryImpl" class="…"> <!-- further configuration --> </beans:bean> - - -
+ + +
-
- Adding custom behaviour to all repositories +
+ Adding custom behaviour to all repositories - In other cases you might want to add a single method to all of - your repository interfaces. So the approach just shown is not feasible. - The first step to achieve this is adding and intermediate interface to - declare the shared behaviour + In other cases you might want to add a single method to all of + your repository interfaces. So the approach just shown is not + feasible. + The first step to achieve this is adding and intermediate interface to + declare the shared behaviour + - - An interface declaring custom shared behaviour + + An interface declaring custom shared behaviour - + + public interface MyRepository<T, ID extends Serializable> extends JpaRepository<T, ID> { void sharedCustomMethod(ID id); - } - + } + + - Now your individual repository interfaces will extend this - intermediate interface instead of the - Repository interface to include the - functionality declared. The second step is to create an implementation - of this interface that extends the persistence technology specific - repository base class which will then act as a custom base class for the - repository proxies. + + Now your individual repository interfaces will extend this + intermediate interface instead of the + Repository + interface to include the + functionality declared. The second step is to create an implementation + of this interface that extends the persistence technology specific + repository base class which will then act as a custom base class for + the + repository proxies. + - - The default behaviour of the Spring <repositories - /> namespace is to provide an implementation for all - interfaces that fall under the base-package. This means - that if left in it's current state, an implementation instance of - MyRepository will be created by Spring. - This is of course not desired as it is just supposed to act as an - intermediary between Repository and the - actual repository interfaces you want to define for each entity. To - exclude an interface extending - Repository from being instantiated as a - repository instance it can either be annotate it with - @NoRepositoryBean or moved out side of - the configured base-package. - + + + The default behaviour of the Spring + <repositories + /> + namespace is to provide an implementation for all + interfaces that fall under the + base-package + . This means + that if left in it's current state, an implementation instance of + MyRepository + will be created by Spring. + This is of course not desired as it is just supposed to act as an + intermediary between + Repository + and the + actual repository interfaces you want to define for each entity. To + exclude an interface extending + Repository + from being instantiated as a + repository instance it can either be annotate it with + @NoRepositoryBean + or moved out side of + the configured + base-package + . + + - - Custom repository base class + + Custom repository base class - + public class MyRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements MyRepository<T, ID> { @@ -721,21 +970,30 @@ // implementation goes here } } - + - The last step is to create a custom repository factory to replace - the default RepositoryFactoryBean that will in - turn produce a custom RepositoryFactory. The new - repository factory will then provide your - MyRepositoryImpl as the implementation of any - interfaces that extend the Repository - interface, replacing the SimpleJpaRepository - implementation you just extended. + + The last step is to create a custom repository factory to replace + the default + RepositoryFactoryBean + that will in + turn produce a custom + RepositoryFactory + . The new + repository factory will then provide your + MyRepositoryImpl + as the implementation of any + interfaces that extend the + Repository + interface, replacing the + SimpleJpaRepository + implementation you just extended. + - - Custom repository factory bean + + Custom repository factory bean - + public class MyRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> { @@ -767,39 +1025,48 @@ } } } - + - Finally you can either declare beans of the custom factory - directly or use the factory-class attribute of the Spring - namespace to tell the repository infrastructure to use your custom - factory implementation. + + Finally you can either declare beans of the custom factory + directly or use the + factory-class + attribute of the Spring + namespace to tell the repository infrastructure to use your custom + factory implementation. + - - Using the custom factory with the namespace + + Using the custom factory with the namespace - <repositories base-package="com.acme.repository" + <repositories base-package="com.acme.repository" factory-class="com.acme.MyRepositoryFactoryBean" /> - -
-
+ +
+
-
- Extensions +
+ Extensions - This chapter documents a set of Spring Data extensions that enable - Spring Data usage in a variety of contexts. Currently most of the - integration is targeted towards Spring MVC. + This chapter documents a set of Spring Data extensions that + enable + Spring Data usage in a variety of contexts. Currently most of the + integration is targeted towards Spring MVC. + -
- Domain class web binding for Spring MVC +
+ Domain class web binding for Spring MVC - Given you are developing a Spring MVC web applications you - typically have to resolve domain class ids from URLs. By default it's - your task to transform that request parameter or URL part into the - domain class to hand it layers below then or execute business logic on - the entities directly. This should look something like this: + Given you are developing a Spring MVC web applications you + typically have to resolve domain class ids from URLs. By default + it's + your task to transform that request parameter or URL part into the + domain class to hand it layers below then or execute business logic + on + the entities directly. This should look something like this: + - @Controller + @Controller @RequestMapping("/users") public class UserController { @@ -820,26 +1087,39 @@ } } - First you pretty much have to declare a repository dependency for - each controller to lookup the entity managed by the controller or - repository respectively. Beyond that looking up the entity is - boilerplate as well as it's always a findOne(…) - call. Fortunately Spring provides means to register custom converting - components that allow conversion between a String - value to an arbitrary type. + + First you pretty much have to declare a repository dependency for + each controller to lookup the entity managed by the controller or + repository respectively. Beyond that looking up the entity is + boilerplate as well as it's always a + findOne(…) + call. Fortunately Spring provides means to register custom + converting + components that allow conversion between a + String + value to an arbitrary type. + - - PropertyEditors + + PropertyEditors - For versions up to Spring 3.0 simple Java - PropertyEditors had to be used. Thus, - we offer a DomainClassPropertyEditorRegistrar, - that will look up all Spring Data repositories registered in the - ApplicationContext and register a - custom PropertyEditor for the managed - domain class + + For versions up to Spring 3.0 simple Java + PropertyEditor + s had to be used. Thus, + we offer a + DomainClassPropertyEditorRegistrar + , + that will look up all Spring Data repositories registered in the + ApplicationContext + and register a + custom + PropertyEditor + for the managed + domain class + - <bean class="….web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> + <bean class="….web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="webBindingInitializer"> <bean class="….web.bind.support.ConfigurableWebBindingInitializer"> <property name="propertyEditorRegistrars"> @@ -849,11 +1129,12 @@ </property> </bean> - If you have configured Spring MVC like this you can turn your - controller into the following that reduces a lot of the clutter and - boilerplate. + If you have configured Spring MVC like this you can turn your + controller into the following that reduces a lot of the clutter and + boilerplate. + - @Controller + @Controller @RequestMapping("/users") public class UserController { @@ -865,25 +1146,32 @@ return "userForm"; } } - + - - ConversionService + + ConversionService - As of Spring 3.0 the - PropertyEditor support is superseeded - by a new conversion infrstructure that leaves all the drawbacks of - PropertyEditors behind and uses a - stateless X to Y conversion approach. We now ship with a - DomainClassConverter that pretty much mimics - the behaviour of - DomainClassPropertyEditorRegistrar. To register - the converter you have to declare - ConversionServiceFactoryBean, register the - converter and tell the Spring MVC namespace to use the configured - conversion service: + + As of Spring 3.0 the + PropertyEditor + support is superseeded + by a new conversion infrstructure that leaves all the drawbacks of + PropertyEditor + s behind and uses a + stateless X to Y conversion approach. We now ship with a + DomainClassConverter + that pretty much mimics + the behaviour of + DomainClassPropertyEditorRegistrar + . To register + the converter you have to declare + ConversionServiceFactoryBean + , register the + converter and tell the Spring MVC namespace to use the configured + conversion service: + - <mvc:annotation-driven conversion-service="conversionService" /> + <mvc:annotation-driven conversion-service="conversionService" /> <bean id="conversionService" class="….context.support.ConversionServiceFactoryBean"> <property name="converters"> @@ -894,13 +1182,13 @@ </list> </property> </bean> - -
+ +
-
- Web pagination +
+ Web pagination - @Controller + @Controller @RequestMapping("/users") public class UserController { @@ -916,16 +1204,22 @@ } } - As you can see the naive approach requires the method to contain - an HttpServletRequest parameter that has - to be parsed manually. We even omitted an appropriate failure handling - which would make the code even more verbose. The bottom line is that the - controller actually shouldn't have to handle the functionality of - extracting pagination information from the request. So we include a - PageableArgumentResolver that will do the work - for you. + + As you can see the naive approach requires the method to contain + an + HttpServletRequest + parameter that has + to be parsed manually. We even omitted an appropriate failure handling + which would make the code even more verbose. The bottom line is that + the + controller actually shouldn't have to handle the functionality of + extracting pagination information from the request. So we include a + PageableArgumentResolver + that will do the work + for you. + - <bean class="….web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> + <bean class="….web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="customArgumentResolvers"> <list> <bean class="org.springframework.data.web.PageableArgumentResolver" /> @@ -933,10 +1227,11 @@ </property> </bean> - This configuration allows you to simplify controllers down to - something like this: + This configuration allows you to simplify controllers down to + something like this: + - @Controller + @Controller @RequestMapping("/users") public class UserController { @@ -948,118 +1243,166 @@ } } - The PageableArgumentResolver will - automatically resolve request parameters to build a - PageRequest instance. By default it will expect - the following structure for the request parameters: + + The + PageableArgumentResolver + will + automatically resolve request parameters to build a + PageRequest + instance. By default it will expect + the following structure for the request parameters: + - - Request parameters evaluated by - <classname>PageableArgumentResolver</classname> +
+ + Request parameters evaluated by + <classname>PageableArgumentResolver</classname> + - - + + - + - - - page + + + + page + - The page you want to retrieve - + The page you want to retrieve + - - page.size + + + page.size + - The size of the page you want to retrieve - + The size of the page you want to retrieve + - - page.sort + + + page.sort + - The property that should be sorted by - + The property that should be sorted by + - - page.sort.dir + + + page.sort.dir + - The direction that should be used for sorting - - - -
+ The direction that should be used for sorting + + + + - In case you need multiple Pageables - to be resolved from the request (for multiple tables e.g.) you can use - Spring's @Qualifier annotation to - distinguish one from another. The request parameters then have to be - prefixed with ${qualifier}_. So a method signature like - this: + + In case you need multiple + Pageable + s + to be resolved from the request (for multiple tables e.g.) you can use + Spring's + @Qualifier + annotation to + distinguish one from another. The request parameters then have to be + prefixed with + ${qualifier}_ + . So a method signature like + this: + - public String showUsers(Model model, + public String showUsers(Model model, @Qualifier("foo") Pageable first, @Qualifier("bar") Pageable second) { … } - you'd have to populate foo_page and - bar_page and the according subproperties. + + you'd have to populate + foo_page + and + bar_page + and the according subproperties. + - - Defaulting + + Defaulting - The PageableArgumentResolver will use a - PageRequest with the first page and a page size - of 10 by default and will use that in case it can't resolve a - PageRequest from the request (because of - missing parameters e.g.). You can configure a global default on the - bean declaration directly. In case you might need controller method - specific defaults for the Pageable - simply annotate the method parameter with - @PageableDefaults and specify page and - page size as annotation attributes: + + The + PageableArgumentResolver + will use a + PageRequest + with the first page and a page size + of 10 by default and will use that in case it can't resolve a + PageRequest + from the request (because of + missing parameters e.g.). You can configure a global default on the + bean declaration directly. In case you might need controller method + specific defaults for the + Pageable + simply annotate the method parameter with + @PageableDefaults + and specify page and + page size as annotation attributes: + - public String showUsers(Model model, + public String showUsers(Model model, @PageableDefaults(pageNumber = 0, value = 30) Pageable pageable) { … } - -
+ +
-
- Repository populators +
+ Repository populators - If you have been working with the JDBC module of Spring you're - probably familiar with the support to populate a DataSource using SQL - scripts. A similar abstraction is available on the repositories level - although we don't use SQL as data definition language as we need to be - store independent of course. Thus the populators support XML (through - Spring's OXM abstraction) and JSON (through Jackson) to define data for - the repositories to be populated with. + If you have been working with the JDBC module of Spring you're + probably familiar with the support to populate a DataSource using + SQL + scripts. A similar abstraction is available on the repositories level + although we don't use SQL as data definition language as we need to + be + store independent of course. Thus the populators support XML (through + Spring's OXM abstraction) and JSON (through Jackson) to define data + for + the repositories to be populated with. + - Assume you have a file data.json with the - following content: + + Assume you have a file + data.json + with the + following content: + - - Data defined in JSON + + Data defined in JSON - [ { "_class" : "com.acme.Person", + [ { "_class" : "com.acme.Person", "firstname" : "Dave", "lastname" : "Matthews" }, { "_class" : "com.acme.Person", "firstname" : "Carter", "lastname" : "Beauford" } ] - + - You can easily populate you repositories by using the populator - elements of the repository namespace provided in Spring Data Commons. To - get the just shown data be populated to your - PersonRepository all you need to do is - the following: + + You can easily populate you repositories by using the populator + elements of the repository namespace provided in Spring Data + Commons. To + get the just shown data be populated to your + PersonRepository + all you need to do is + the following: + - - Declaring a Jackson repository populator + + Declaring a Jackson repository populator - <?xml version="1.0" encoding="UTF-8"?> + <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:repository="http://www.springframework.org/schema/data/repository" @@ -1071,24 +1414,33 @@ <repository:jackson-populator location="classpath:data.json" /> </beans> - + - This declaration causes the data.json file being read, - deserialized by a Jackson ObjectMapper. The type - the JSON object will be unmarshalled to will be determined by inspecting - the _class attribute of the JSON document. We will - eventually select the appropriate repository being able to handle the - object just deserialized. + + This declaration causes the data.json file being read, + deserialized by a Jackson + ObjectMapper + . The type + the JSON object will be unmarshalled to will be determined by + inspecting + the + _class + attribute of the JSON document. We will + eventually select the appropriate repository being able to handle the + object just deserialized. + - To rather use XML to define the repositories shall be populated - with you can use the unmarshaller-populator you hand one of the - marshaller options Spring OXM provides you with. + To rather use XML to define the repositories shall be populated + with you can use the unmarshaller-populator you hand one of the + marshaller options Spring OXM provides you with. + - - Declaring an unmarshalling repository populator (using - JAXB) + + Declaring an unmarshalling repository populator (using + JAXB) + - <?xml version="1.0" encoding="UTF-8"?> + <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:repository="http://www.springframework.org/schema/data/repository" @@ -1105,7 +1457,7 @@ <oxm:jaxb2-marshaller contextPath="com.acme" /> </beans> - -
-
+ +
+
\ No newline at end of file diff --git a/src/docbkx/resources/css/highlight.css b/src/docbkx/resources/css/highlight.css index b1727f354..9235ed112 100644 --- a/src/docbkx/resources/css/highlight.css +++ b/src/docbkx/resources/css/highlight.css @@ -3,34 +3,33 @@ code highlight CSS resemblign the Eclipse IDE default color schema @author Costin Leau */ - .hl-keyword { - color: #7F0055; - font-weight: bold; + color: #7F0055; + font-weight: bold; } .hl-comment { - color: #3F5F5F; - font-style: italic; + color: #3F5F5F; + font-style: italic; } .hl-multiline-comment { - color: #3F5FBF; - font-style: italic; + color: #3F5FBF; + font-style: italic; } .hl-tag { - color: #3F7F7F; + color: #3F7F7F; } .hl-attribute { - color: #7F007F; + color: #7F007F; } .hl-value { - color: #2A00FF; + color: #2A00FF; } .hl-string { - color: #2A00FF; + color: #2A00FF; } \ No newline at end of file diff --git a/src/docbkx/resources/css/html.css b/src/docbkx/resources/css/html.css index de5467a5c..2085916d7 100644 --- a/src/docbkx/resources/css/html.css +++ b/src/docbkx/resources/css/html.css @@ -1,112 +1,117 @@ /* borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/css/html.css */ - @IMPORT url("highlight.css"); html { - padding: 0pt; - margin: 0pt; + padding: 0pt; + margin: 0pt; } body { - margin-left: 15%; - margin-right: 15%; - font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; + margin-left: 15%; + margin-right: 15%; + font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", + sans-serif; } div { - margin: 0pt; + margin: 0pt; } p { - text-align: justify; - line-height: 1.3em; + text-align: justify; + line-height: 1.3em; } hr { - border: 1px solid gray; - background: gray; + border: 1px solid gray; + background: gray; } h1,h2,h3,h4,h5 { - color: #234623; - font-weight: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; - margin-bottom: 0em; - margin-top: 2em; + color: #234623; + font-weight: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", + sans-serif; + margin-bottom: 0em; + margin-top: 2em; } pre { - line-height: 1.0; - color: black; + line-height: 1.0; + color: black; } table code { - font-size: 110%; + font-size: 110%; } pre.programlisting { - font-size: 1em; - padding: 3pt 3pt; - border: 1pt solid black; - background: #eeeeee; - clear: both; + font-size: 1em; + padding: 3pt 3pt; + border: 1pt solid black; + background: #eeeeee; + clear: both; } div.table { - margin: 1em; - padding: 0.5em; - text-align: center; + margin: 1em; + padding: 0.5em; + text-align: center; } div.table table { - display: table; - width: 100%; + display: table; + width: 100%; } div.table td { - padding-left: 7px; - padding-right: 7px; + padding-left: 7px; + padding-right: 7px; } .sidebar { - float: right; - margin: 10px 0 10px 30px; - padding: 10px 20px 20px 20px; - width: 33%; - border: 1px solid black; - background-color: #F4F4F4; - font-size: 14px; + float: right; + margin: 10px 0 10px 30px; + padding: 10px 20px 20px 20px; + width: 33%; + border: 1px solid black; + background-color: #F4F4F4; + font-size: 14px; } .mediaobject { - padding-top: 30px; - padding-bottom: 30px; + padding-top: 30px; + padding-bottom: 30px; } .legalnotice { - font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; - font-size: 12px; - font-style: italic; + font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", + sans-serif; + font-size: 12px; + font-style: italic; } p.releaseinfo { - font-size: 100%; - font-weight: bold; - font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; - padding-top: 10px; + font-size: 100%; + font-weight: bold; + font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", + sans-serif; + padding-top: 10px; } p.pubdate { - font-size: 120%; - font-weight: bold; - font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; + font-size: 120%; + font-weight: bold; + font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", + sans-serif; } span.productname { - font-size: 200%; - font-weight: bold; - font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; + font-size: 200%; + font-weight: bold; + font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", + sans-serif; } code { diff --git a/src/docbkx/resources/xsl/fopdf.xsl b/src/docbkx/resources/xsl/fopdf.xsl index a49c9e4b8..2cef37674 100644 --- a/src/docbkx/resources/xsl/fopdf.xsl +++ b/src/docbkx/resources/xsl/fopdf.xsl @@ -1,433 +1,480 @@ - + + xmlns:fo="http://www.w3.org/1999/XSL/Format" version="1.0"> - - + + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - , - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + , + + + + + + + + Copyright © 2013 - - - - - - - - - + + + + + + + + + - - - - - - - + + + + + + + - + - - - - + + + + - -5em - -5em - + -5em + -5em + - - - - - - + + + + + + - Spring Data Elasticsearch () + Spring Data Elasticsearch ( + + ) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + - - 0 - - 1 - 1 - 0 + + + 0 + + + + 1 + + + 1 + + + 0 + - + - - - book toc - + + + book toc + - - 2 + + + 2 + - - + + - + - - - 0 - 0 - 0 + + + + 0 + + + 0 + + + 0 + - - 5mm - 10mm - 10mm + + + 5mm + + + 10mm + + + 10mm + - 15mm - 10mm - 0mm + + 15mm + + + 10mm + + + 0mm + - 18mm - 18mm + + 18mm + + + 18mm + - - 0pc + + + 0pc + - + - - justify - false + + + justify + + + false + - - 11 - 8 + + + 11 + + + 8 + - - 1.4 + + + 1.4 + - - - - + + + + - 0.8em - + 0.8em + - + - - 17.4cm + + + 17.4cm + - - - 4pt - 4pt - 4pt - 4pt - + + + 4pt + 4pt + 4pt + 4pt + - - 0.1pt - 0.1pt + + + 0.1pt + + + 0.1pt + - + - - 1 - - + + + 1 + + + - + - - - left - bold - - + + + left + bold + + pt - + - - - - - - - - + + + + + + + + - - - 0.8em - 0.8em - 0.8em - - + + + 0.8em + 0.8em + 0.8em + + pt - 0.1em - 0.1em - 0.1em - - - 0.6em - 0.6em - 0.6em - - + 0.1em + 0.1em + 0.1em + + + 0.6em + 0.6em + 0.6em + + pt - 0.1em - 0.1em - 0.1em - - - 0.4em - 0.4em - 0.4em - - + 0.1em + 0.1em + 0.1em + + + 0.4em + 0.4em + 0.4em + + pt - 0.1em - 0.1em - 0.1em - + 0.1em + 0.1em + 0.1em + - - - bold - - + + + bold + + pt - false - 0.4em - 0.6em - 0.8em - + false + 0.4em + 0.6em + 0.8em + - + - - - - + + + + pt - + - - 1em - 1em - 1em - #444444 - solid - 0.1pt - 0.5em - 0.5em - 0.5em - 0.5em - 0.5em - 0.5em - + + 1em + 1em + 1em + #444444 + solid + 0.1pt + 0.5em + 0.5em + 0.5em + 0.5em + 0.5em + 0.5em + - - 1 - - #F0F0F0 - + + + 1 + + + #F0F0F0 + - + - - 0 - 1 + + + 0 + + + 1 + - - 90 + + + 90 + - + - - '1' - src/docbkx/resources/images/admons/ + + + '1' + + + src/docbkx/resources/images/admons/ + - + - - - figure after - example before - equation before - table before - procedure before - + + + figure after + example before + equation before + table before + procedure before + - - 1 + + + 1 + - - - 0.8em - 0.8em - 0.8em - 0.1em - 0.1em - 0.1em - + + + 0.8em + 0.8em + 0.8em + 0.1em + 0.1em + 0.1em + - - - - - - - - - - - - - + + + + + + + + + + + + + - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/src/docbkx/resources/xsl/highlight-fo.xsl b/src/docbkx/resources/xsl/highlight-fo.xsl index ffc7ab447..76bf411a4 100644 --- a/src/docbkx/resources/xsl/highlight-fo.xsl +++ b/src/docbkx/resources/xsl/highlight-fo.xsl @@ -1,45 +1,57 @@ - + + xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xslthl="http://xslthl.sf.net" + exclude-result-prefixes="xslthl" version='1.0'> - + + + - + - + + + - + + + - + + + - + + + - + + + - + - + + + - + + + \ No newline at end of file diff --git a/src/docbkx/resources/xsl/highlight.xsl b/src/docbkx/resources/xsl/highlight.xsl index 5f84a82fa..d52e3bf66 100644 --- a/src/docbkx/resources/xsl/highlight.xsl +++ b/src/docbkx/resources/xsl/highlight.xsl @@ -1,43 +1,56 @@ - + + xmlns:xslthl="http://xslthl.sf.net" exclude-result-prefixes="xslthl" + version='1.0'> - + + + - + + + - + + + - + + + - + + + - + + + - + + + - + - + + + \ No newline at end of file diff --git a/src/docbkx/resources/xsl/html.xsl b/src/docbkx/resources/xsl/html.xsl index c7cccdc0d..800b308cd 100644 --- a/src/docbkx/resources/xsl/html.xsl +++ b/src/docbkx/resources/xsl/html.xsl @@ -1,108 +1,114 @@ - + - - - - - - - - 0 - 0 - 1 + xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xslthl="http://xslthl.sf.net" + exclude-result-prefixes="xslthl" version="1.0"> - + + - - - book toc - + - - 3 + + + 0 + + + 0 + + + 1 + - + - - 1 - - + + + book toc + - + + + 3 + - - 1 + - - 90 + + + 1 + + + - + - - 1 - images/admons/ - - - - figure after - example before - equation before - table before - procedure before - - - - , - - - - - - - - -
-

Authors

-

- -

-
- - - - - + + + 1 + + + + + 90 + + + + + + + 1 + + + images/admons/ + + + + + figure after + example before + equation before + table before + procedure before + + + + , + + + + + + + + +
+

Authors

+

+ +

+
+ + + + +
diff --git a/src/docbkx/resources/xsl/html_chunk.xsl b/src/docbkx/resources/xsl/html_chunk.xsl index b42481db5..e8e4cb9e1 100644 --- a/src/docbkx/resources/xsl/html_chunk.xsl +++ b/src/docbkx/resources/xsl/html_chunk.xsl @@ -1,222 +1,253 @@ - + + xmlns:fo="http://www.w3.org/1999/XSL/Format" version="1.0"> - - - + + - - '5' - '1' - 0 - 0 - 1 - - - - book toc - qandaset toc - - - 3 - - - 1 - - - - - 1 - 90 - - - - 1 - images/admons/ - - - - figure after - example before - equation before - table before - procedure before - - - - , - - - - () - - - - - -
-

Authors

-

- -

-
- - - - - - - - 1 - - - - - - - - + '5' + + + '1' + + + 0 + + + 0 + + + 1 + + + + + book toc + qandaset toc + + + + 3 + + + + + 1 + + + + + + + 1 + + + 90 + + + + + + + 1 + + + images/admons/ + + + + + figure after + example before + equation before + table before + procedure before + + + + , + + + + ( + + ) + + + + + +
+

Authors

+

+ +

+
+ + + + + + + + + 1 + + + + + + + + + - + - - + +
diff --git a/src/main/assembly/distribution.xml b/src/main/assembly/distribution.xml index e8450e0cd..4ebf2179e 100644 --- a/src/main/assembly/distribution.xml +++ b/src/main/assembly/distribution.xml @@ -1,11 +1,9 @@ - + distribution zip @@ -20,32 +18,31 @@ notice.txt changelog.txt - + dos - + target/site/reference docs/reference - + target/site/apidocs docs/javadoc - + target/${dist.finalName}.jar - dist + dist 0644 - + target/${dist.finalName}-sources.jar - sources + sources 0644 diff --git a/src/main/assembly/jar-with-dependencies.descriptor.xml b/src/main/assembly/jar-with-dependencies.descriptor.xml index b34b174fe..aaab146ed 100644 --- a/src/main/assembly/jar-with-dependencies.descriptor.xml +++ b/src/main/assembly/jar-with-dependencies.descriptor.xml @@ -1,18 +1,19 @@ - - all - - jar - - false - - - / - true - true - runtime - true - - + + all + + jar + + false + + + / + true + true + runtime + true + + \ No newline at end of file diff --git a/src/main/java/org/springframework/data/elasticsearch/ElasticsearchException.java b/src/main/java/org/springframework/data/elasticsearch/ElasticsearchException.java index c776e20a6..ba64746c4 100644 --- a/src/main/java/org/springframework/data/elasticsearch/ElasticsearchException.java +++ b/src/main/java/org/springframework/data/elasticsearch/ElasticsearchException.java @@ -15,38 +15,37 @@ */ package org.springframework.data.elasticsearch; - import java.util.Map; /** * ElasticsearchException - * + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class ElasticsearchException extends RuntimeException{ +public class ElasticsearchException extends RuntimeException { - private Map failedDocuments; + private Map failedDocuments; - public ElasticsearchException(String message) { - super(message); - } + public ElasticsearchException(String message) { + super(message); + } - public ElasticsearchException(String message, Throwable cause) { - super(message, cause); - } + public ElasticsearchException(String message, Throwable cause) { + super(message, cause); + } - public ElasticsearchException(String message, Throwable cause, Map failedDocuments) { - super(message, cause); - this.failedDocuments = failedDocuments; - } + public ElasticsearchException(String message, Throwable cause, Map failedDocuments) { + super(message, cause); + this.failedDocuments = failedDocuments; + } - public ElasticsearchException(String message, Map failedDocuments) { - super(message); - this.failedDocuments = failedDocuments; - } + public ElasticsearchException(String message, Map failedDocuments) { + super(message); + this.failedDocuments = failedDocuments; + } - public Map getFailedDocuments() { - return failedDocuments; - } + public Map getFailedDocuments() { + return failedDocuments; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/annotations/Document.java b/src/main/java/org/springframework/data/elasticsearch/annotations/Document.java index 968295f4c..16f106754 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/Document.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/Document.java @@ -15,14 +15,13 @@ */ package org.springframework.data.elasticsearch.annotations; - import org.springframework.data.annotation.Persistent; import java.lang.annotation.*; /** * Document - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -33,10 +32,15 @@ import java.lang.annotation.*; @Target({ ElementType.TYPE }) public @interface Document { - String indexName(); - String type() default ""; - short shards() default 1; - short replicas() default 5; - String refreshInterval() default "1s"; - String indexStoreType() default "fs"; + String indexName(); + + String type() default ""; + + short shards() default 1; + + short replicas() default 5; + + String refreshInterval() default "1s"; + + String indexStoreType() default "fs"; } diff --git a/src/main/java/org/springframework/data/elasticsearch/annotations/Field.java b/src/main/java/org/springframework/data/elasticsearch/annotations/Field.java index 8345d2577..c4ed4aaa6 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/Field.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/Field.java @@ -17,7 +17,6 @@ package org.springframework.data.elasticsearch.annotations; import java.lang.annotation.*; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -27,10 +26,14 @@ import java.lang.annotation.*; @Documented public @interface Field { - String type() default ""; - String index() default ""; - boolean store() default false; - String searchAnalyzer() default ""; - String indexAnalyzer() default ""; + String type() default ""; + + String index() default ""; + + boolean store() default false; + + String searchAnalyzer() default ""; + + String indexAnalyzer() default ""; } diff --git a/src/main/java/org/springframework/data/elasticsearch/annotations/Query.java b/src/main/java/org/springframework/data/elasticsearch/annotations/Query.java index bf5818c28..cc78366f5 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/Query.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/Query.java @@ -19,7 +19,7 @@ import java.lang.annotation.*; /** * Query - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -29,18 +29,18 @@ import java.lang.annotation.*; @Documented public @interface Query { - /** - * Elasticsearch query to be used when executing query. May contain placeholders eg. ?0 - * - * @return - */ - String value() default ""; + /** + * Elasticsearch query to be used when executing query. May contain placeholders eg. ?0 + * + * @return + */ + String value() default ""; - /** - * Named Query Named looked up by repository. - * - * @return - */ - String name() default ""; + /** + * Named Query Named looked up by repository. + * + * @return + */ + String name() default ""; } diff --git a/src/main/java/org/springframework/data/elasticsearch/client/NodeClientFactoryBean.java b/src/main/java/org/springframework/data/elasticsearch/client/NodeClientFactoryBean.java index 5f841ac0c..c90f952c0 100644 --- a/src/main/java/org/springframework/data/elasticsearch/client/NodeClientFactoryBean.java +++ b/src/main/java/org/springframework/data/elasticsearch/client/NodeClientFactoryBean.java @@ -27,72 +27,72 @@ import org.springframework.beans.factory.InitializingBean; import static org.elasticsearch.node.NodeBuilder.nodeBuilder; /** - * NodeClientFactoryBean - * + * NodeClientFactoryBean + * * @author Rizwan Idrees * @author Mohsin Husen */ public class NodeClientFactoryBean implements FactoryBean, InitializingBean, DisposableBean { - private static final Logger logger = LoggerFactory.getLogger(NodeClientFactoryBean.class); - private boolean local; - private boolean enableHttp; - private String clusterName; - private NodeClient nodeClient; + private static final Logger logger = LoggerFactory.getLogger(NodeClientFactoryBean.class); + private boolean local; + private boolean enableHttp; + private String clusterName; + private NodeClient nodeClient; - NodeClientFactoryBean() { - } + NodeClientFactoryBean() { + } - public NodeClientFactoryBean(boolean local) { - this.local = local; - } + public NodeClientFactoryBean(boolean local) { + this.local = local; + } - @Override - public NodeClient getObject() throws Exception { - return nodeClient; - } + @Override + public NodeClient getObject() throws Exception { + return nodeClient; + } - @Override - public Class getObjectType() { - return NodeClient.class; - } + @Override + public Class getObjectType() { + return NodeClient.class; + } - @Override - public boolean isSingleton() { - return true; - } + @Override + public boolean isSingleton() { + return true; + } - @Override - public void afterPropertiesSet() throws Exception { - ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder() - .put("http.enabled", String.valueOf(this.enableHttp)); + @Override + public void afterPropertiesSet() throws Exception { + ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder().put("http.enabled", + String.valueOf(this.enableHttp)); - nodeClient = (NodeClient) nodeBuilder().settings(settings) - .clusterName(this.clusterName).local(this.local).node().client(); - } + nodeClient = (NodeClient) nodeBuilder().settings(settings).clusterName(this.clusterName).local(this.local).node() + .client(); + } - public void setLocal(boolean local) { - this.local = local; - } + public void setLocal(boolean local) { + this.local = local; + } - public void setEnableHttp(boolean enableHttp) { - this.enableHttp = enableHttp; - } + public void setEnableHttp(boolean enableHttp) { + this.enableHttp = enableHttp; + } - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } - @Override - public void destroy() throws Exception { - try { - logger.info("Closing elasticSearch client"); - if (nodeClient != null) { - nodeClient.close(); - } - } catch (final Exception e) { - logger.error("Error closing ElasticSearch client: ", e); - } - } + @Override + public void destroy() throws Exception { + try { + logger.info("Closing elasticSearch client"); + if (nodeClient != null) { + nodeClient.close(); + } + } catch (final Exception e) { + logger.error("Error closing ElasticSearch client: ", e); + } + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/client/TransportClientFactoryBean.java b/src/main/java/org/springframework/data/elasticsearch/client/TransportClientFactoryBean.java index 9424f18d8..3e1857f68 100644 --- a/src/main/java/org/springframework/data/elasticsearch/client/TransportClientFactoryBean.java +++ b/src/main/java/org/springframework/data/elasticsearch/client/TransportClientFactoryBean.java @@ -32,79 +32,78 @@ import static org.apache.commons.lang.StringUtils.substringBefore; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; /** - * TransportClientFactoryBean - * + * TransportClientFactoryBean + * * @author Rizwan Idrees * @author Mohsin Husen */ public class TransportClientFactoryBean implements FactoryBean, InitializingBean, DisposableBean { - private static final Logger logger = LoggerFactory.getLogger(TransportClientFactoryBean.class); - private String[] clusterNodes; - private TransportClient client; - private Properties properties; - static final String COLON = ":"; + private static final Logger logger = LoggerFactory.getLogger(TransportClientFactoryBean.class); + private String[] clusterNodes; + private TransportClient client; + private Properties properties; + static final String COLON = ":"; - @Override - public void destroy() throws Exception { - try { - logger.info("Closing elasticSearch client"); - if (client != null) { - client.close(); - } - } catch (final Exception e) { - logger.error("Error closing ElasticSearch client: ", e); - } - } + @Override + public void destroy() throws Exception { + try { + logger.info("Closing elasticSearch client"); + if (client != null) { + client.close(); + } + } catch (final Exception e) { + logger.error("Error closing ElasticSearch client: ", e); + } + } - @Override - public TransportClient getObject() throws Exception { - return client; - } + @Override + public TransportClient getObject() throws Exception { + return client; + } - @Override - public Class getObjectType() { - return TransportClient.class; - } + @Override + public Class getObjectType() { + return TransportClient.class; + } - @Override - public boolean isSingleton() { - return false; - } + @Override + public boolean isSingleton() { + return false; + } - @Override - public void afterPropertiesSet() throws Exception { - buildClient(); - } + @Override + public void afterPropertiesSet() throws Exception { + buildClient(); + } - protected void buildClient() throws Exception { - client = new TransportClient(settings()); - Assert.notEmpty(clusterNodes,"[Assertion failed] clusterNodes settings missing."); - for (String clusterNode : clusterNodes) { - String hostName = substringBefore(clusterNode, COLON); - String port = substringAfter(clusterNode, COLON); - Assert.hasText(hostName,"[Assertion failed] missing host name in 'clusterNodes'"); - Assert.hasText(port,"[Assertion failed] missing port in 'clusterNodes'"); - logger.info("adding transport node : " + clusterNode); - client.addTransportAddress(new InetSocketTransportAddress(hostName, Integer.valueOf(port))); - } - client.connectedNodes(); - } + protected void buildClient() throws Exception { + client = new TransportClient(settings()); + Assert.notEmpty(clusterNodes, "[Assertion failed] clusterNodes settings missing."); + for (String clusterNode : clusterNodes) { + String hostName = substringBefore(clusterNode, COLON); + String port = substringAfter(clusterNode, COLON); + Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'"); + Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'"); + logger.info("adding transport node : " + clusterNode); + client.addTransportAddress(new InetSocketTransportAddress(hostName, Integer.valueOf(port))); + } + client.connectedNodes(); + } - private Settings settings(){ - if(properties != null){ - return settingsBuilder().put(properties).build(); - } - return settingsBuilder() - .put("client.transport.sniff",true).build(); - } + private Settings settings() { + if (properties != null) { + return settingsBuilder().put(properties).build(); + } + return settingsBuilder().put("client.transport.sniff", true).build(); + } - public void setClusterNodes(String[] clusterNodes) { - this.clusterNodes = clusterNodes; - } + public void setClusterNodes(String[] clusterNodes) { + this.clusterNodes = clusterNodes; + } - public void setProperties(Properties properties) { - this.properties = properties; - } + public void setProperties(Properties properties) { + this.properties = properties; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandler.java b/src/main/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandler.java index c0ee7c998..011ed164f 100644 --- a/src/main/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandler.java +++ b/src/main/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandler.java @@ -21,21 +21,21 @@ import org.springframework.data.repository.config.RepositoryBeanDefinitionParser import org.springframework.data.repository.config.RepositoryConfigurationExtension; /** - * ElasticsearchNamespaceHandler - * + * ElasticsearchNamespaceHandler + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class ElasticsearchNamespaceHandler extends NamespaceHandlerSupport{ +public class ElasticsearchNamespaceHandler extends NamespaceHandlerSupport { - @Override - public void init() { - RepositoryConfigurationExtension extension = new ElasticsearchRepositoryConfigExtension(); + @Override + public void init() { + RepositoryConfigurationExtension extension = new ElasticsearchRepositoryConfigExtension(); RepositoryBeanDefinitionParser parser = new RepositoryBeanDefinitionParser(extension); registerBeanDefinitionParser("repositories", parser); registerBeanDefinitionParser("node-client", new NodeClientBeanDefinitionParser()); registerBeanDefinitionParser("transport-client", new TransportClientBeanDefinitionParser()); - } + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/config/NodeClientBeanDefinitionParser.java b/src/main/java/org/springframework/data/elasticsearch/config/NodeClientBeanDefinitionParser.java index ffc03b3d6..387032fcd 100644 --- a/src/main/java/org/springframework/data/elasticsearch/config/NodeClientBeanDefinitionParser.java +++ b/src/main/java/org/springframework/data/elasticsearch/config/NodeClientBeanDefinitionParser.java @@ -25,31 +25,30 @@ import org.w3c.dom.Element; /** * NodeClientBeanDefinitionParser - * + * * @author Rizwan Idrees * @author Mohsin Husen */ public class NodeClientBeanDefinitionParser extends AbstractBeanDefinitionParser { - @Override - protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(NodeClientFactoryBean.class); - setLocalSettings(element,builder); - return getSourcedBeanDefinition(builder, element, parserContext); - } + @Override + protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(NodeClientFactoryBean.class); + setLocalSettings(element, builder); + return getSourcedBeanDefinition(builder, element, parserContext); + } - private void setLocalSettings(Element element, BeanDefinitionBuilder builder) { - builder.addPropertyValue("local", Boolean.valueOf(element.getAttribute("local"))); - builder.addPropertyValue("clusterName", element.getAttribute("cluster-name")); - builder.addPropertyValue("enableHttp",Boolean.valueOf(element.getAttribute("http-enabled"))); - } + private void setLocalSettings(Element element, BeanDefinitionBuilder builder) { + builder.addPropertyValue("local", Boolean.valueOf(element.getAttribute("local"))); + builder.addPropertyValue("clusterName", element.getAttribute("cluster-name")); + builder.addPropertyValue("enableHttp", Boolean.valueOf(element.getAttribute("http-enabled"))); + } - - private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source, - ParserContext context) { - AbstractBeanDefinition definition = builder.getBeanDefinition(); - definition.setSource(context.extractSource(source)); - return definition; - } + private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source, + ParserContext context) { + AbstractBeanDefinition definition = builder.getBeanDefinition(); + definition.setSource(context.extractSource(source)); + return definition; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/config/TransportClientBeanDefinitionParser.java b/src/main/java/org/springframework/data/elasticsearch/config/TransportClientBeanDefinitionParser.java index 43b75899b..b43a82554 100644 --- a/src/main/java/org/springframework/data/elasticsearch/config/TransportClientBeanDefinitionParser.java +++ b/src/main/java/org/springframework/data/elasticsearch/config/TransportClientBeanDefinitionParser.java @@ -23,32 +23,33 @@ import org.springframework.data.elasticsearch.client.TransportClientFactoryBean; import org.w3c.dom.Element; import static org.apache.commons.lang.StringUtils.split; + /** - * TransportClientBeanDefinitionParser - * + * TransportClientBeanDefinitionParser + * * @author Rizwan Idrees * @author Mohsin Husen */ public class TransportClientBeanDefinitionParser extends AbstractBeanDefinitionParser { - private static final String SEPARATOR_CHARS = ","; + private static final String SEPARATOR_CHARS = ","; - @Override - protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TransportClientFactoryBean.class); - setClusterNodes(element, builder); - return getSourcedBeanDefinition(builder,element, parserContext); - } + @Override + protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TransportClientFactoryBean.class); + setClusterNodes(element, builder); + return getSourcedBeanDefinition(builder, element, parserContext); + } - private void setClusterNodes(Element element, BeanDefinitionBuilder builder){ - builder.addPropertyValue("clusterNodes", split(element.getAttribute("cluster-nodes"), SEPARATOR_CHARS)); - } + private void setClusterNodes(Element element, BeanDefinitionBuilder builder) { + builder.addPropertyValue("clusterNodes", split(element.getAttribute("cluster-nodes"), SEPARATOR_CHARS)); + } - private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source, - ParserContext context) { - AbstractBeanDefinition definition = builder.getBeanDefinition(); - definition.setSource(context.extractSource(source)); - return definition; - } + private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source, + ParserContext context) { + AbstractBeanDefinition definition = builder.getBeanDefinition(); + definition.setSource(context.extractSource(source)); + return definition; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/CriteriaQueryProcessor.java b/src/main/java/org/springframework/data/elasticsearch/core/CriteriaQueryProcessor.java index 87c7dd0f7..0da61b4d0 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/CriteriaQueryProcessor.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/CriteriaQueryProcessor.java @@ -29,106 +29,109 @@ import static org.springframework.data.elasticsearch.core.query.Criteria.Operati /** * CriteriaQueryProcessor - * + * * @author Rizwan Idrees * @author Mohsin Husen */ class CriteriaQueryProcessor { + QueryBuilder createQueryFromCriteria(Criteria criteria) { + BoolQueryBuilder query = boolQuery(); - QueryBuilder createQueryFromCriteria(Criteria criteria) { - BoolQueryBuilder query = boolQuery(); + ListIterator chainIterator = criteria.getCriteriaChain().listIterator(); + while (chainIterator.hasNext()) { + Criteria chainedCriteria = chainIterator.next(); + if (chainedCriteria.isOr()) { + query.should(createQueryFragmentForCriteria(chainedCriteria)); + } else if (chainedCriteria.isNegating()) { + query.mustNot(createQueryFragmentForCriteria(chainedCriteria)); + } else { + query.must(createQueryFragmentForCriteria(chainedCriteria)); + } + } + return query; + } - ListIterator chainIterator = criteria.getCriteriaChain().listIterator(); - while (chainIterator.hasNext()) { - Criteria chainedCriteria = chainIterator.next(); - if(chainedCriteria.isOr()){ - query.should(createQueryFragmentForCriteria(chainedCriteria)); - }else if(chainedCriteria.isNegating()){ - query.mustNot(createQueryFragmentForCriteria(chainedCriteria)); - }else{ - query.must(createQueryFragmentForCriteria(chainedCriteria)); - } - } - return query; - } + private QueryBuilder createQueryFragmentForCriteria(Criteria chainedCriteria) { + Iterator it = chainedCriteria.getCriteriaEntries().iterator(); + boolean singeEntryCriteria = (chainedCriteria.getCriteriaEntries().size() == 1); + String fieldName = chainedCriteria.getField().getName(); + Assert.notNull(fieldName, "Unknown field"); + QueryBuilder query = null; - private QueryBuilder createQueryFragmentForCriteria(Criteria chainedCriteria) { - Iterator it = chainedCriteria.getCriteriaEntries().iterator(); - boolean singeEntryCriteria = (chainedCriteria.getCriteriaEntries().size() == 1); + if (singeEntryCriteria) { + Criteria.CriteriaEntry entry = it.next(); + query = processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName); + } else { + query = boolQuery(); + while (it.hasNext()) { + Criteria.CriteriaEntry entry = it.next(); + ((BoolQueryBuilder) query).must(processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName)); + } + } - String fieldName = chainedCriteria.getField().getName(); - Assert.notNull(fieldName,"Unknown field"); - QueryBuilder query = null; + addBoost(query, chainedCriteria.getBoost()); + return query; + } - if(singeEntryCriteria){ - Criteria.CriteriaEntry entry = it.next(); - query = processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName); - }else{ - query = boolQuery(); - while (it.hasNext()){ - Criteria.CriteriaEntry entry = it.next(); - ((BoolQueryBuilder)query).must(processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName)); - } - } + private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) { + if (value == null) { + return null; + } + QueryBuilder query = null; - addBoost(query, chainedCriteria.getBoost()); - return query; - } + switch (key) { + case EQUALS: + query = fieldQuery(fieldName, value); + break; + case CONTAINS: + query = fieldQuery(fieldName, "*" + value + "*").analyzeWildcard(true); + break; + case STARTS_WITH: + query = fieldQuery(fieldName, value + "*").analyzeWildcard(true); + break; + case ENDS_WITH: + query = fieldQuery(fieldName, "*" + value).analyzeWildcard(true); + break; + case EXPRESSION: + query = queryString((String) value).field(fieldName); + break; + case BETWEEN: + Object[] ranges = (Object[]) value; + query = rangeQuery(fieldName).from(ranges[0]).to(ranges[1]); + break; + case FUZZY: + query = fuzzyQuery(fieldName, (String) value); + break; + case IN: + query = boolQuery(); + Iterable collection = (Iterable) value; + for (Object item : collection) { + ((BoolQueryBuilder) query).should(fieldQuery(fieldName, item)); + } + break; + } + return query; + } - private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) { - if (value == null) { - return null; - } - QueryBuilder query = null; + private QueryBuilder buildNegationQuery(String fieldName, Iterator it) { + BoolQueryBuilder notQuery = boolQuery(); + while (it.hasNext()) { + notQuery.mustNot(fieldQuery(fieldName, it.next().getValue())); + } + return notQuery; + } - switch (key){ - case EQUALS: - query = fieldQuery(fieldName, value); break; - case CONTAINS: - query = fieldQuery(fieldName,"*" + value + "*").analyzeWildcard(true); break; - case STARTS_WITH: - query = fieldQuery(fieldName,value +"*").analyzeWildcard(true); break; - case ENDS_WITH: - query = fieldQuery(fieldName, "*"+value).analyzeWildcard(true); break; - case EXPRESSION: - query = queryString((String)value).field(fieldName); break; - case BETWEEN: - Object[] ranges = (Object[]) value; - query = rangeQuery(fieldName).from(ranges[0]).to(ranges[1]); break; - case FUZZY: - query = fuzzyQuery(fieldName, (String) value); break; - case IN: - query = boolQuery(); - Iterable collection = (Iterable) value; - for(Object item : collection){ - ((BoolQueryBuilder) query).should(fieldQuery(fieldName, item)); - } - break; - } - - return query; - } - - private QueryBuilder buildNegationQuery(String fieldName, Iterator it){ - BoolQueryBuilder notQuery = boolQuery(); - while (it.hasNext()){ - notQuery.mustNot(fieldQuery(fieldName, it.next().getValue())); - } - return notQuery; - } - - private void addBoost(QueryBuilder query, float boost){ - if(Float.isNaN(boost)){ - return; - } - if(query instanceof BoostableQueryBuilder){ - ((BoostableQueryBuilder)query).boost(boost); - } - - } + private void addBoost(QueryBuilder query, float boost) { + if (Float.isNaN(boost)) { + return; + } + if (query instanceof BoostableQueryBuilder) { + ((BoostableQueryBuilder) query).boost(boost); + } + } } 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 1d5abd847..8611f1996 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.core; - import org.springframework.data.domain.Page; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.query.*; @@ -24,235 +23,238 @@ import java.util.List; /** * ElasticsearchOperations - * + * * @author Rizwan Idrees * @author Mohsin Husen */ public interface ElasticsearchOperations { + /** + * @return Converter in use + */ + ElasticsearchConverter getElasticsearchConverter(); - /** - * @return Converter in use - */ - ElasticsearchConverter getElasticsearchConverter(); + /** + * Create an index for a class + * + * @param clazz + * @param + */ + boolean createIndex(Class clazz); - /** - * Create an index for a class - * @param clazz - * @param - */ - boolean createIndex(Class clazz); + /** + * Create mapping for a class + * + * @param clazz + * @param + */ + boolean putMapping(Class clazz); - /** - * Create mapping for a class - * @param clazz - * @param - */ - boolean putMapping(Class clazz); + /** + * Execute the query against elasticsearch and return the first returned object + * + * @param query + * @param clazz + * @return the first matching object + */ + T queryForObject(GetQuery query, Class clazz); + /** + * Execute the query against elasticsearch and return the first returned object + * + * @param query + * @param clazz + * @return the first matching object + */ + T queryForObject(CriteriaQuery query, Class clazz); - /** - * Execute the query against elasticsearch and return the first returned object - * - * @param query - * @param clazz - * @return the first matching object - */ - T queryForObject(GetQuery query, Class clazz); + /** + * Execute the query against elasticsearch and return the first returned object + * + * @param query + * @param clazz + * @return the first matching object + */ + T queryForObject(StringQuery query, Class clazz); - /** - * Execute the query against elasticsearch and return the first returned object - * - * @param query - * @param clazz - * @return the first matching object - */ - T queryForObject(CriteriaQuery query, Class clazz); + /** + * Execute the query against elasticsearch and return result as {@link Page} + * + * @param query + * @param clazz + * @return + */ + Page queryForPage(SearchQuery query, Class clazz); + /** + * Execute the query against elasticsearch and return result as {@link Page} + * + * @param query + * @param resultsMapper + * @return + */ + Page queryForPage(SearchQuery query, ResultsMapper resultsMapper); - /** - * Execute the query against elasticsearch and return the first returned object - * - * @param query - * @param clazz - * @return the first matching object - */ - T queryForObject(StringQuery query, Class clazz); + /** + * Execute the query against elasticsearch and return result as {@link Page} + * + * @param query + * @param clazz + * @return + */ + Page queryForPage(CriteriaQuery query, Class clazz); + /** + * Execute the query against elasticsearch and return result as {@link Page} + * + * @param query + * @param clazz + * @return + */ + Page queryForPage(StringQuery query, Class clazz); - /** - * Execute the query against elasticsearch and return result as {@link Page} - * - * @param query - * @param clazz - * @return - */ - Page queryForPage(SearchQuery query, Class clazz); + /** + * Execute the criteria query against elasticsearch and return result as {@link List} + * + * @param query + * @param clazz + * @param + * @return + */ + List queryForList(CriteriaQuery query, Class clazz); + /** + * Execute the string query against elasticsearch and return result as {@link List} + * + * @param query + * @param clazz + * @param + * @return + */ + List queryForList(StringQuery query, Class clazz); - /** - * Execute the query against elasticsearch and return result as {@link Page} - * - * @param query - * @param resultsMapper - * @return - */ - Page queryForPage(SearchQuery query, ResultsMapper resultsMapper); + /** + * Execute the query against elasticsearch and return ids + * + * @param query + * @return + */ + List queryForIds(SearchQuery query); + /** + * return number of elements found by for given query + * + * @param query + * @param clazz + * @return + */ + long count(SearchQuery query, Class clazz); - /** - * Execute the query against elasticsearch and return result as {@link Page} - * - * @param query - * @param clazz - * @return - */ - Page queryForPage(CriteriaQuery query, Class clazz); + /** + * Index an object. Will do save or update + * + * @param query + * @return returns the document id + */ + String index(IndexQuery query); + /** + * Bulk index all objects. Will do save or update + * + * @param queries + */ + void bulkIndex(List queries); - /** - * Execute the query against elasticsearch and return result as {@link Page} - * - * @param query - * @param clazz - * @return - */ - Page queryForPage(StringQuery query, Class clazz); + /** + * Delete the one object with provided id + * + * @param indexName + * @param type + * @param id + * @return documentId of the document deleted + */ + String delete(String indexName, String type, String id); - /** - * Execute the criteria query against elasticsearch and return result as {@link List} - * - * @param query - * @param clazz - * @param - * @return - */ - List queryForList(CriteriaQuery query, Class clazz); + /** + * Delete the one object with provided id + * + * @param clazz + * @param id + * @return documentId of the document deleted + */ + String delete(Class clazz, String id); - /** - * Execute the string query against elasticsearch and return result as {@link List} - * - * @param query - * @param clazz - * @param - * @return - */ - List queryForList(StringQuery query, Class clazz); + /** + * Delete all records matching the query + * + * @param clazz + * @param query + */ + void delete(DeleteQuery query, Class clazz); - /** - * Execute the query against elasticsearch and return ids - * - * @param query - * @return - */ - List queryForIds(SearchQuery query); + /** + * Deletes an index for given entity + * + * @param clazz + * @param + * @return + */ + boolean deleteIndex(Class clazz); - /** - * return number of elements found by for given query - * - * @param query - * @param clazz - * @return - */ - long count(SearchQuery query, Class clazz); + /** + * check if index is exists + * + * @param clazz + * @param + * @return + */ + boolean indexExists(Class clazz); - /** - * Index an object. Will do save or update - * - * @param query - * @return returns the document id - */ - String index(IndexQuery query); + /** + * refresh the index + * + * @param indexName + * @param waitForOperation + */ + void refresh(String indexName, boolean waitForOperation); - /** - * Bulk index all objects. Will do save or update - * - * @param queries - */ - void bulkIndex(List queries); + /** + * refresh the index + * + * @param clazz + * @param waitForOperation + */ + void refresh(Class clazz, boolean waitForOperation); - /** - * Delete the one object with provided id - * - * @param indexName - * @param type - * @param id - * @return documentId of the document deleted - */ - String delete(String indexName, String type, String id); + /** + * Returns scroll id for scan query + * + * @param query + * @param scrollTimeInMillis + * @param noFields + * @return + */ + String scan(SearchQuery query, long scrollTimeInMillis, boolean noFields); - /** - * Delete the one object with provided id - * - * @param clazz - * @param id - * @return documentId of the document deleted - */ - String delete(Class clazz, String id); + /** + * Scrolls the results for give scroll id + * + * @param scrollId + * @param scrollTimeInMillis + * @param resultsMapper + * @param + * @return + */ + Page scroll(String scrollId, long scrollTimeInMillis, ResultsMapper resultsMapper); - /** - * Delete all records matching the query - * @param clazz - * @param query - */ - void delete(DeleteQuery query, Class clazz); - - /** - * Deletes an index for given entity - * @param clazz - * @param - * @return - */ - boolean deleteIndex(Class clazz); - - /** - * check if index is exists - * @param clazz - * @param - * @return - */ - boolean indexExists(Class clazz); - - /** - * refresh the index - * @param indexName - * @param waitForOperation - */ - void refresh(String indexName,boolean waitForOperation); - - /** - * refresh the index - * @param clazz - * @param waitForOperation - */ - void refresh(Class clazz,boolean waitForOperation); - - /** - * Returns scroll id for scan query - * @param query - * @param scrollTimeInMillis - * @param noFields - * @return - */ - String scan(SearchQuery query, long scrollTimeInMillis, boolean noFields); - - /** - * Scrolls the results for give scroll id - * @param scrollId - * @param scrollTimeInMillis - * @param resultsMapper - * @param - * @return - */ - Page scroll(String scrollId, long scrollTimeInMillis, ResultsMapper resultsMapper); - - /** - * more like this query to search for documents that are "like" a specific document. - * @param query - * @param clazz - * @param - * @return - */ - Page moreLikeThis(MoreLikeThisQuery query, Class clazz); + /** + * more like this query to search for documents that are "like" a specific document. + * + * @param query + * @param clazz + * @param + * @return + */ + Page moreLikeThis(MoreLikeThisQuery query, 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 fd33fbed5..15db96e55 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java @@ -69,457 +69,443 @@ import static org.springframework.data.elasticsearch.core.MappingBuilder.buildMa /** * ElasticsearchTemplate - * + * * @author Rizwan Idrees * @author Mohsin Husen */ public class ElasticsearchTemplate implements ElasticsearchOperations { - private Client client; - private ElasticsearchConverter elasticsearchConverter; - private ObjectMapper objectMapper = new ObjectMapper(); + private Client client; + private ElasticsearchConverter elasticsearchConverter; + private ObjectMapper objectMapper = new ObjectMapper(); - { - objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); - } + { + objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } - public ElasticsearchTemplate(Client client) { - this(client, null); - } + public ElasticsearchTemplate(Client client) { + this(client, null); + } - public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter) { - this.client = client; - this.elasticsearchConverter = (elasticsearchConverter == null)? new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext()) : elasticsearchConverter ; - } + public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter) { + this.client = client; + this.elasticsearchConverter = (elasticsearchConverter == null) ? new MappingElasticsearchConverter( + new SimpleElasticsearchMappingContext()) : elasticsearchConverter; + } - @Override - public boolean createIndex(Class clazz) { - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - return createIndexIfNotCreated(clazz); - } + @Override + public boolean createIndex(Class clazz) { + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + return createIndexIfNotCreated(clazz); + } - @Override - public boolean putMapping(Class clazz) { - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - PutMappingRequestBuilder requestBuilder = client.admin().indices().preparePutMapping(persistentEntity.getIndexName()) - .setType(persistentEntity.getIndexType()); + @Override + public boolean putMapping(Class clazz) { + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + PutMappingRequestBuilder requestBuilder = client.admin().indices() + .preparePutMapping(persistentEntity.getIndexName()).setType(persistentEntity.getIndexType()); - try { - XContentBuilder xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(), persistentEntity.getIdProperty().getFieldName()); - return requestBuilder.setSource(xContentBuilder).execute().actionGet().isAcknowledged(); - } catch (Exception e) { - throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName() , e); - } - } + try { + XContentBuilder xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(), persistentEntity + .getIdProperty().getFieldName()); + return requestBuilder.setSource(xContentBuilder).execute().actionGet().isAcknowledged(); + } catch (Exception e) { + throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e); + } + } - @Override - public ElasticsearchConverter getElasticsearchConverter() { - return elasticsearchConverter; - } + @Override + public ElasticsearchConverter getElasticsearchConverter() { + return elasticsearchConverter; + } - @Override - public T queryForObject(GetQuery query, Class clazz) { - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - GetResponse response = client.prepareGet(persistentEntity.getIndexName(), persistentEntity.getIndexType(), query.getId()) - .execute().actionGet(); - return mapResult(response.getSourceAsString(), clazz); - } + @Override + public T queryForObject(GetQuery query, Class clazz) { + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + GetResponse response = client + .prepareGet(persistentEntity.getIndexName(), persistentEntity.getIndexType(), query.getId()).execute() + .actionGet(); + return mapResult(response.getSourceAsString(), clazz); + } - @Override - public T queryForObject(CriteriaQuery query, Class clazz) { - Page page = queryForPage(query,clazz); - Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found "+ page.getTotalElements() +" results"); - return page.getTotalElements() > 0? page.getContent().get(0) : null; - } + @Override + public T queryForObject(CriteriaQuery query, Class clazz) { + Page page = queryForPage(query, clazz); + Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found " + page.getTotalElements() + " results"); + return page.getTotalElements() > 0 ? page.getContent().get(0) : null; + } - @Override - public T queryForObject(StringQuery query, Class clazz) { - Page page = queryForPage(query,clazz); - Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found "+ page.getTotalElements() +" results"); - return page.getTotalElements() > 0? page.getContent().get(0) : null; - } + @Override + public T queryForObject(StringQuery query, Class clazz) { + Page page = queryForPage(query, clazz); + Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found " + page.getTotalElements() + " results"); + return page.getTotalElements() > 0 ? page.getContent().get(0) : null; + } - @Override - public Page queryForPage(SearchQuery query, Class clazz) { - SearchResponse response = doSearch(prepareSearch(query,clazz), query.getQuery(), query.getFilter(), query.getElasticsearchSort()); - return mapResults(response, clazz, query.getPageable()); - } + @Override + public Page queryForPage(SearchQuery query, Class clazz) { + SearchResponse response = doSearch(prepareSearch(query, clazz), query.getQuery(), query.getFilter(), + query.getElasticsearchSort()); + return mapResults(response, clazz, query.getPageable()); + } - @Override - public Page queryForPage(SearchQuery query, ResultsMapper resultsMapper) { - SearchResponse response = doSearch(prepareSearch(query), query.getQuery(), query.getFilter(), query.getElasticsearchSort()); - return resultsMapper.mapResults(response); - } + @Override + public Page queryForPage(SearchQuery query, ResultsMapper resultsMapper) { + SearchResponse response = doSearch(prepareSearch(query), query.getQuery(), query.getFilter(), + query.getElasticsearchSort()); + return resultsMapper.mapResults(response); + } - @Override - public List queryForList(CriteriaQuery query, Class clazz){ - return queryForPage(query, clazz).getContent(); - } + @Override + public List queryForList(CriteriaQuery query, Class clazz) { + return queryForPage(query, clazz).getContent(); + } - @Override - public List queryForList(StringQuery query, Class clazz){ - return queryForPage(query, clazz).getContent(); - } + @Override + public List queryForList(StringQuery query, Class clazz) { + return queryForPage(query, clazz).getContent(); + } + @Override + public List queryForIds(SearchQuery query) { + SearchRequestBuilder request = prepareSearch(query).setQuery(query.getQuery()).setNoFields(); + if (query.getFilter() != null) { + request.setFilter(query.getFilter()); + } + SearchResponse response = request.execute().actionGet(); + return extractIds(response); + } - @Override - public List queryForIds(SearchQuery query) { - SearchRequestBuilder request = prepareSearch(query).setQuery(query.getQuery()) - .setNoFields(); - if(query.getFilter() != null){ - request.setFilter(query.getFilter()); - } - SearchResponse response = request.execute().actionGet(); - return extractIds(response); - } + @Override + public Page queryForPage(CriteriaQuery criteriaQuery, Class clazz) { + QueryBuilder query = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria()); + SearchResponse response = prepareSearch(criteriaQuery, clazz).setQuery(query).execute().actionGet(); + return mapResults(response, clazz, criteriaQuery.getPageable()); + } - @Override - public Page queryForPage(CriteriaQuery criteriaQuery, Class clazz) { - QueryBuilder query = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria()); - SearchResponse response = prepareSearch(criteriaQuery,clazz) - .setQuery(query) - .execute().actionGet(); - return mapResults(response, clazz, criteriaQuery.getPageable()); - } + @Override + public Page queryForPage(StringQuery query, Class clazz) { + SearchResponse response = prepareSearch(query, clazz).setQuery(query.getSource()).execute().actionGet(); + return mapResults(response, clazz, query.getPageable()); + } - @Override - public Page queryForPage(StringQuery query, Class clazz) { - SearchResponse response = prepareSearch(query,clazz) - .setQuery(query.getSource()) - .execute().actionGet(); - return mapResults(response, clazz, query.getPageable()); - } + @Override + public long count(SearchQuery query, Class clazz) { + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + CountRequestBuilder countRequestBuilder = client.prepareCount(persistentEntity.getIndexName()).setTypes( + persistentEntity.getIndexType()); + if (query.getQuery() != null) { + countRequestBuilder.setQuery(query.getQuery()); + } + return countRequestBuilder.execute().actionGet().getCount(); + } - @Override - public long count(SearchQuery query, Class clazz) { - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - CountRequestBuilder countRequestBuilder = client.prepareCount(persistentEntity.getIndexName()) - .setTypes(persistentEntity.getIndexType()); - if(query.getQuery() != null){ - countRequestBuilder.setQuery(query.getQuery()); - } - return countRequestBuilder.execute().actionGet().getCount(); - } + @Override + public String index(IndexQuery query) { + return prepareIndex(query).execute().actionGet().getId(); + } - @Override - public String index(IndexQuery query) { - return prepareIndex(query) - .execute() - .actionGet().getId(); - } + @Override + public void bulkIndex(List queries) { + BulkRequestBuilder bulkRequest = client.prepareBulk(); + for (IndexQuery query : queries) { + bulkRequest.add(prepareIndex(query)); + } + BulkResponse bulkResponse = bulkRequest.execute().actionGet(); + if (bulkResponse.hasFailures()) { + Map failedDocuments = new HashMap(); + for (BulkItemResponse item : bulkResponse.getItems()) { + if (item.isFailed()) + failedDocuments.put(item.getId(), item.getFailureMessage()); + } + throw new ElasticsearchException( + "Bulk indexing has failures. Use ElasticsearchException.getFailedDocuments() for detailed messages [" + + failedDocuments + "]", failedDocuments); + } + } - @Override - public void bulkIndex(List queries) { - BulkRequestBuilder bulkRequest = client.prepareBulk(); - for(IndexQuery query : queries){ - bulkRequest.add(prepareIndex(query)); - } - BulkResponse bulkResponse = bulkRequest.execute().actionGet(); - if (bulkResponse.hasFailures()) { - Map failedDocuments = new HashMap(); - for (BulkItemResponse item : bulkResponse.getItems()) { - if (item.isFailed()) - failedDocuments.put(item.getId(), item.getFailureMessage()); - } - throw new ElasticsearchException("Bulk indexing has failures. Use ElasticsearchException.getFailedDocuments() for detailed messages [" + failedDocuments+"]", failedDocuments); - } - } + @Override + public boolean indexExists(Class clazz) { + return indexExists(getPersistentEntityFor(clazz).getIndexName()); + } - @Override - public boolean indexExists(Class clazz){ - return indexExists(getPersistentEntityFor(clazz).getIndexName()); - } + @Override + public boolean deleteIndex(Class clazz) { + String indexName = getPersistentEntityFor(clazz).getIndexName(); + if (indexExists(indexName)) { + return client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet().isAcknowledged(); + } + return false; + } - @Override - public boolean deleteIndex(Class clazz){ - String indexName = getPersistentEntityFor(clazz).getIndexName(); - if(indexExists(indexName)){ - return client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet().isAcknowledged(); - } - return false; - } + @Override + public String delete(String indexName, String type, String id) { + return client.prepareDelete(indexName, type, id).execute().actionGet().getId(); + } - @Override - public String delete(String indexName, String type, String id) { - return client.prepareDelete(indexName, type, id) - .execute().actionGet().getId(); - } + @Override + public String delete(Class clazz, String id) { + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + return delete(persistentEntity.getIndexName(), persistentEntity.getIndexType(), id); + } - @Override - public String delete(Class clazz, String id) { - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - return delete(persistentEntity.getIndexName(), persistentEntity.getIndexType(), id); - } + @Override + public void delete(DeleteQuery deleteQuery, Class clazz) { + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + client.prepareDeleteByQuery(persistentEntity.getIndexName()).setTypes(persistentEntity.getIndexType()) + .setQuery(deleteQuery.getQuery()).execute().actionGet(); + } - @Override - public void delete(DeleteQuery deleteQuery, Class clazz) { - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - client.prepareDeleteByQuery(persistentEntity.getIndexName()) - .setTypes(persistentEntity.getIndexType()) - .setQuery(deleteQuery.getQuery()) - .execute().actionGet(); - } + @Override + public String scan(SearchQuery searchQuery, long scrollTimeInMillis, boolean noFields) { + Assert.notNull(searchQuery.getIndices(), "No index defined for Query"); + Assert.notNull(searchQuery.getTypes(), "No type define for Query"); + Assert.notNull(searchQuery.getPageable(), "Query.pageable is required for scan & scroll"); - @Override - public String scan(SearchQuery searchQuery, long scrollTimeInMillis, boolean noFields) { - Assert.notNull(searchQuery.getIndices(), "No index defined for Query"); - Assert.notNull(searchQuery.getTypes(), "No type define for Query"); - Assert.notNull(searchQuery.getPageable(), "Query.pageable is required for scan & scroll"); + SearchRequestBuilder requestBuilder = client.prepareSearch(toArray(searchQuery.getIndices())).setSearchType(SCAN) + .setQuery(searchQuery.getQuery()).setTypes(toArray(searchQuery.getTypes())) + .setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).setFrom(0) + .setSize(searchQuery.getPageable().getPageSize()); - SearchRequestBuilder requestBuilder = client.prepareSearch(toArray(searchQuery.getIndices())) - .setSearchType(SCAN) - .setQuery(searchQuery.getQuery()) - .setTypes(toArray(searchQuery.getTypes())) - .setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)) - .setFrom(0) - .setSize(searchQuery.getPageable().getPageSize()); + if (searchQuery.getFilter() != null) { + requestBuilder.setFilter(searchQuery.getFilter()); + } - if(searchQuery.getFilter() != null){ - requestBuilder.setFilter(searchQuery.getFilter()); - } + if (noFields) { + requestBuilder.setNoFields(); + } + return requestBuilder.execute().actionGet().getScrollId(); + } - if(noFields){ - requestBuilder.setNoFields(); - } - return requestBuilder.execute().actionGet().getScrollId(); - } + @Override + public Page scroll(String scrollId, long scrollTimeInMillis, ResultsMapper resultsMapper) { + SearchResponse response = client.prepareSearchScroll(scrollId) + .setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute().actionGet(); + return resultsMapper.mapResults(response); + } - @Override - public Page scroll(String scrollId, long scrollTimeInMillis, ResultsMapper resultsMapper) { - SearchResponse response = client.prepareSearchScroll(scrollId) - .setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)) - .execute().actionGet(); - return resultsMapper.mapResults(response); - } + @Override + public Page moreLikeThis(MoreLikeThisQuery query, Class clazz) { + int startRecord = 0; + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + String indexName = isNotBlank(query.getIndexName()) ? query.getIndexName() : persistentEntity.getIndexName(); + String type = isNotBlank(query.getType()) ? query.getType() : persistentEntity.getIndexType(); - @Override - public Page moreLikeThis(MoreLikeThisQuery query, Class clazz) { - int startRecord = 0; - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - String indexName = isNotBlank(query.getIndexName())? query.getIndexName(): persistentEntity.getIndexName(); - String type = isNotBlank(query.getType())? query.getType() : persistentEntity.getIndexType(); + Assert.notNull(indexName, "No 'indexName' defined for MoreLikeThisQuery"); + Assert.notNull(type, "No 'type' defined for MoreLikeThisQuery"); + Assert.notNull(query.getId(), "No document id defined for MoreLikeThisQuery"); - Assert.notNull(indexName,"No 'indexName' defined for MoreLikeThisQuery"); - Assert.notNull(type, "No 'type' defined for MoreLikeThisQuery"); - Assert.notNull(query.getId(), "No document id defined for MoreLikeThisQuery"); + MoreLikeThisRequestBuilder requestBuilder = client.prepareMoreLikeThis(indexName, type, query.getId()); - MoreLikeThisRequestBuilder requestBuilder = - client.prepareMoreLikeThis(indexName,type, query.getId()); + if (query.getPageable() != null) { + startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize(); + requestBuilder.setSearchSize(query.getPageable().getPageSize()); + } + requestBuilder.setSearchFrom(startRecord); - if(query.getPageable() != null){ - startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize(); - requestBuilder.setSearchSize(query.getPageable().getPageSize()); - } - requestBuilder.setSearchFrom(startRecord); + if (isNotEmpty(query.getSearchIndices())) { + requestBuilder.setSearchIndices(toArray(query.getSearchIndices())); + } + if (isNotEmpty(query.getSearchTypes())) { + requestBuilder.setSearchTypes(toArray(query.getSearchTypes())); + } + if (isNotEmpty(query.getFields())) { + requestBuilder.setField(toArray(query.getFields())); + } + if (isNotBlank(query.getRouting())) { + requestBuilder.setRouting(query.getRouting()); + } + if (query.getPercentTermsToMatch() != null) { + requestBuilder.setPercentTermsToMatch(query.getPercentTermsToMatch()); + } + if (query.getMinTermFreq() != null) { + requestBuilder.setMinTermFreq(query.getMinTermFreq()); + } + if (query.getMaxQueryTerms() != null) { + requestBuilder.maxQueryTerms(query.getMaxQueryTerms()); + } + if (isNotEmpty(query.getStopWords())) { + requestBuilder.setStopWords(toArray(query.getStopWords())); + } + if (query.getMinDocFreq() != null) { + requestBuilder.setMinDocFreq(query.getMinDocFreq()); + } + if (query.getMaxDocFreq() != null) { + requestBuilder.setMaxDocFreq(query.getMaxDocFreq()); + } + if (query.getMinWordLen() != null) { + requestBuilder.setMinWordLen(query.getMinWordLen()); + } + if (query.getMaxWordLen() != null) { + requestBuilder.setMaxWordLen(query.getMaxWordLen()); + } + if (query.getBoostTerms() != null) { + requestBuilder.setBoostTerms(query.getBoostTerms()); + } - if(isNotEmpty(query.getSearchIndices())){ - requestBuilder.setSearchIndices(toArray(query.getSearchIndices())); - } - if(isNotEmpty(query.getSearchTypes())){ - requestBuilder.setSearchTypes(toArray(query.getSearchTypes())); - } - if(isNotEmpty(query.getFields())){ - requestBuilder.setField(toArray(query.getFields())); - } - if(isNotBlank(query.getRouting())){ - requestBuilder.setRouting(query.getRouting()); - } - if(query.getPercentTermsToMatch() != null){ - requestBuilder.setPercentTermsToMatch(query.getPercentTermsToMatch()); - } - if(query.getMinTermFreq() != null){ - requestBuilder.setMinTermFreq(query.getMinTermFreq()); - } - if(query.getMaxQueryTerms() != null){ - requestBuilder.maxQueryTerms(query.getMaxQueryTerms()); - } - if(isNotEmpty(query.getStopWords())){ - requestBuilder.setStopWords(toArray(query.getStopWords())); - } - if(query.getMinDocFreq() != null){ - requestBuilder.setMinDocFreq(query.getMinDocFreq()); - } - if(query.getMaxDocFreq() != null){ - requestBuilder.setMaxDocFreq(query.getMaxDocFreq()); - } - if(query.getMinWordLen() != null){ - requestBuilder.setMinWordLen(query.getMinWordLen()); - } - if(query.getMaxWordLen() != null){ - requestBuilder.setMaxWordLen(query.getMaxWordLen()); - } - if(query.getBoostTerms() != null){ - requestBuilder.setBoostTerms(query.getBoostTerms()); - } + SearchResponse response = requestBuilder.execute().actionGet(); + return mapResults(response, clazz, query.getPageable()); + } - SearchResponse response = requestBuilder.execute().actionGet(); - return mapResults(response, clazz, query.getPageable()); - } + private SearchResponse doSearch(SearchRequestBuilder searchRequest, QueryBuilder query, FilterBuilder filter, + SortBuilder sortBuilder) { + if (filter != null) { + searchRequest.setFilter(filter); + } - private SearchResponse doSearch(SearchRequestBuilder searchRequest, QueryBuilder query, FilterBuilder filter, SortBuilder sortBuilder){ - if(filter != null){ - searchRequest.setFilter(filter); - } + if (sortBuilder != null) { + searchRequest.addSort(sortBuilder); + } - if(sortBuilder != null){ - searchRequest.addSort(sortBuilder); - } + return searchRequest.setQuery(query).execute().actionGet(); + } - return searchRequest.setQuery(query).execute().actionGet(); - } + private boolean createIndexIfNotCreated(Class clazz) { + return indexExists(getPersistentEntityFor(clazz).getIndexName()) || createIndexWithSettings(clazz); + } - private boolean createIndexIfNotCreated(Class clazz) { - return indexExists(getPersistentEntityFor(clazz).getIndexName()) || createIndexWithSettings(clazz); - } + private boolean indexExists(String indexName) { + return client.admin().indices().exists(indicesExistsRequest(indexName)).actionGet().isExists(); + } - private boolean indexExists(String indexName) { - return client.admin() - .indices() - .exists(indicesExistsRequest(indexName)).actionGet().isExists(); - } + private boolean createIndexWithSettings(Class clazz) { + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + return client.admin().indices() + .create(Requests.createIndexRequest(persistentEntity.getIndexName()).settings(getSettings(persistentEntity))) + .actionGet().isAcknowledged(); + } - private boolean createIndexWithSettings(Class clazz) { - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - return client.admin().indices().create(Requests.createIndexRequest(persistentEntity.getIndexName()). - settings(getSettings(persistentEntity))).actionGet().isAcknowledged(); - } + private Map getSettings(ElasticsearchPersistentEntity persistentEntity) { + return new MapBuilder().put("index.number_of_shards", String.valueOf(persistentEntity.getShards())) + .put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas())) + .put("index.refresh_interval", persistentEntity.getRefreshInterval()) + .put("index.store.type", persistentEntity.getIndexStoreType()).map(); + } - private Map getSettings(ElasticsearchPersistentEntity persistentEntity) { - return new MapBuilder() - .put("index.number_of_shards", String.valueOf(persistentEntity.getShards())) - .put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas())) - .put("index.refresh_interval", persistentEntity.getRefreshInterval()) - .put("index.store.type", persistentEntity.getIndexStoreType()) - .map(); - } + private SearchRequestBuilder prepareSearch(Query query, Class clazz) { + if (query.getIndices().isEmpty()) { + query.addIndices(retrieveIndexNameFromPersistentEntity(clazz)); + } + if (query.getTypes().isEmpty()) { + query.addTypes(retrieveTypeFromPersistentEntity(clazz)); + } + return prepareSearch(query); + } - private SearchRequestBuilder prepareSearch(Query query, Class clazz){ - if(query.getIndices().isEmpty()){ - query.addIndices(retrieveIndexNameFromPersistentEntity(clazz)); - } - if(query.getTypes().isEmpty()){ - query.addTypes(retrieveTypeFromPersistentEntity(clazz)); - } - return prepareSearch(query); - } + private SearchRequestBuilder prepareSearch(Query query) { + Assert.notNull(query.getIndices(), "No index defined for Query"); + Assert.notNull(query.getTypes(), "No type defined for Query"); - private SearchRequestBuilder prepareSearch(Query query){ - Assert.notNull(query.getIndices(), "No index defined for Query"); - Assert.notNull(query.getTypes(), "No type defined for Query"); + int startRecord = 0; + SearchRequestBuilder searchRequestBuilder = client.prepareSearch(toArray(query.getIndices())) + .setSearchType(DFS_QUERY_THEN_FETCH).setTypes(toArray(query.getTypes())); - int startRecord = 0; - SearchRequestBuilder searchRequestBuilder = client.prepareSearch(toArray(query.getIndices())) - .setSearchType(DFS_QUERY_THEN_FETCH) - .setTypes(toArray(query.getTypes())); + if (query.getPageable() != null) { + startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize(); + searchRequestBuilder.setSize(query.getPageable().getPageSize()); + } + searchRequestBuilder.setFrom(startRecord); - if(query.getPageable() != null){ - startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize(); - searchRequestBuilder.setSize(query.getPageable().getPageSize()); - } - searchRequestBuilder.setFrom(startRecord); + if (!query.getFields().isEmpty()) { + searchRequestBuilder.addFields(toArray(query.getFields())); + } + if (query.getSort() != null) { + for (Sort.Order order : query.getSort()) { + searchRequestBuilder.addSort(order.getProperty(), order.getDirection() == Sort.Direction.DESC ? SortOrder.DESC + : SortOrder.ASC); + } + } + return searchRequestBuilder; + } - if(!query.getFields().isEmpty()){ - searchRequestBuilder.addFields(toArray(query.getFields())); - } + private IndexRequestBuilder prepareIndex(IndexQuery query) { + try { + String indexName = isBlank(query.getIndexName()) ? retrieveIndexNameFromPersistentEntity(query.getObject() + .getClass())[0] : query.getIndexName(); + String type = isBlank(query.getType()) ? retrieveTypeFromPersistentEntity(query.getObject().getClass())[0] + : query.getType(); - if(query.getSort() != null){ - for(Sort.Order order : query.getSort()){ - searchRequestBuilder.addSort(order.getProperty(), order.getDirection() == Sort.Direction.DESC? SortOrder.DESC : SortOrder.ASC); - } - } - return searchRequestBuilder; - } + IndexRequestBuilder indexRequestBuilder = client.prepareIndex(indexName, type, query.getId()).setSource( + objectMapper.writeValueAsString(query.getObject())); - private IndexRequestBuilder prepareIndex(IndexQuery query){ - try { - String indexName = isBlank(query.getIndexName())? - retrieveIndexNameFromPersistentEntity(query.getObject().getClass())[0] : query.getIndexName(); - String type = isBlank(query.getType())? - retrieveTypeFromPersistentEntity(query.getObject().getClass())[0] : query.getType(); + if (query.getVersion() != null) { + indexRequestBuilder.setVersion(query.getVersion()); + indexRequestBuilder.setVersionType(EXTERNAL); + } + return indexRequestBuilder; + } catch (IOException e) { + throw new ElasticsearchException("failed to index the document [id: " + query.getId() + "]", e); + } + } - IndexRequestBuilder indexRequestBuilder = client.prepareIndex(indexName,type,query.getId()) - .setSource(objectMapper.writeValueAsString(query.getObject())); + public void refresh(String indexName, boolean waitForOperation) { + client.admin().indices().refresh(refreshRequest(indexName).waitForOperations(waitForOperation)).actionGet(); + } - if(query.getVersion() != null){ - indexRequestBuilder.setVersion(query.getVersion()); - indexRequestBuilder.setVersionType(EXTERNAL); - } - return indexRequestBuilder; - } catch (IOException e) { - throw new ElasticsearchException("failed to index the document [id: " + query.getId() +"]",e); - } - } + public void refresh(Class clazz, boolean waitForOperation) { + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + client.admin().indices() + .refresh(refreshRequest(persistentEntity.getIndexName()).waitForOperations(waitForOperation)).actionGet(); + } - public void refresh(String indexName, boolean waitForOperation) { - client.admin().indices() - .refresh(refreshRequest(indexName).waitForOperations(waitForOperation)).actionGet(); - } + private ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz) { + Assert.isTrue(clazz.isAnnotationPresent(Document.class), "Unable to identify index name. " + clazz.getSimpleName() + + " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")"); + return elasticsearchConverter.getMappingContext().getPersistentEntity(clazz); + } - public void refresh(Class clazz, boolean waitForOperation) { - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - client.admin().indices() - .refresh(refreshRequest(persistentEntity.getIndexName()).waitForOperations(waitForOperation)).actionGet(); - } + private String[] retrieveIndexNameFromPersistentEntity(Class clazz) { + return new String[] { getPersistentEntityFor(clazz).getIndexName() }; + } - private ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz){ - Assert.isTrue(clazz.isAnnotationPresent(Document.class), "Unable to identify index name. " + - clazz.getSimpleName() + " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")"); - return elasticsearchConverter.getMappingContext().getPersistentEntity(clazz); - } + private String[] retrieveTypeFromPersistentEntity(Class clazz) { + return new String[] { getPersistentEntityFor(clazz).getIndexType() }; + } - private String[] retrieveIndexNameFromPersistentEntity(Class clazz){ - return new String[]{getPersistentEntityFor(clazz).getIndexName()}; - } + private Page mapResults(SearchResponse response, final Class elementType, final Pageable pageable) { + ResultsMapper resultsMapper = new ResultsMapper() { + @Override + public Page mapResults(SearchResponse response) { + long totalHits = response.getHits().totalHits(); + List results = new ArrayList(); + for (SearchHit hit : response.getHits()) { + if (hit != null) { + results.add(mapResult(hit.sourceAsString(), elementType)); + } + } + return new PageImpl(results, pageable, totalHits); + } + }; + return resultsMapper.mapResults(response); + } - private String[] retrieveTypeFromPersistentEntity(Class clazz){ - return new String[]{getPersistentEntityFor(clazz).getIndexType()}; - } + private List extractIds(SearchResponse response) { + List ids = new ArrayList(); + for (SearchHit hit : response.getHits()) { + if (hit != null) { + ids.add(hit.getId()); + } + } + return ids; + } - private Page mapResults(SearchResponse response, final Class elementType,final Pageable pageable){ - ResultsMapper resultsMapper = new ResultsMapper(){ - @Override - public Page mapResults(SearchResponse response) { - long totalHits = response.getHits().totalHits(); - List results = new ArrayList(); - for (SearchHit hit : response.getHits()) { - if (hit != null) { - results.add(mapResult(hit.sourceAsString(), elementType)); - } - } - return new PageImpl(results, pageable, totalHits); - } - }; - return resultsMapper.mapResults(response); - } + private T mapResult(String source, Class clazz) { + if (isBlank(source)) { + return null; + } + try { + return objectMapper.readValue(source, clazz); + } catch (IOException e) { + throw new ElasticsearchException("failed to map source [ " + source + "] to class " + clazz.getSimpleName(), e); + } + } - private List extractIds(SearchResponse response){ - List ids = new ArrayList(); - for (SearchHit hit : response.getHits()) { - if (hit != null) { - ids.add(hit.getId()); - } - } - return ids; - } + private static String[] toArray(List values) { + String[] valuesAsArray = new String[values.size()]; + return values.toArray(valuesAsArray); - private T mapResult(String source, Class clazz){ - if(isBlank(source)){ - return null; - } - try { - return objectMapper.readValue(source, clazz); - } catch (IOException e) { - throw new ElasticsearchException("failed to map source [ " + source + "] to class " + clazz.getSimpleName() , e); - } - } - - private static String[] toArray(List values){ - String[] valuesAsArray = new String[values.size()]; - return values.toArray(valuesAsArray); - - } + } } - diff --git a/src/main/java/org/springframework/data/elasticsearch/core/MappingBuilder.java b/src/main/java/org/springframework/data/elasticsearch/core/MappingBuilder.java index 567452762..cea71d65f 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/MappingBuilder.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/MappingBuilder.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.core; - import org.elasticsearch.common.xcontent.XContentBuilder; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.mapping.model.SimpleTypeHolder; @@ -36,95 +35,86 @@ import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; class MappingBuilder { - private static SimpleTypeHolder SIMPLE_TYPE_HOLDER = new SimpleTypeHolder(); + private static SimpleTypeHolder SIMPLE_TYPE_HOLDER = new SimpleTypeHolder(); - static XContentBuilder buildMapping(Class clazz, String indexType, String idFieldName) throws IOException { - XContentBuilder xContentBuilder = jsonBuilder() - .startObject().startObject(indexType).startObject("properties"); + static XContentBuilder buildMapping(Class clazz, String indexType, String idFieldName) throws IOException { + XContentBuilder xContentBuilder = jsonBuilder().startObject().startObject(indexType).startObject("properties"); - mapEntity(xContentBuilder, clazz, true, idFieldName, EMPTY); + mapEntity(xContentBuilder, clazz, true, idFieldName, EMPTY); - return xContentBuilder.endObject().endObject().endObject(); - } + return xContentBuilder.endObject().endObject().endObject(); + } - private static void mapEntity(XContentBuilder xContentBuilder, - Class clazz, - boolean isRootObject, - String idFieldName, - String nestedObjectFieldName) throws IOException{ + private static void mapEntity(XContentBuilder xContentBuilder, Class clazz, boolean isRootObject, String idFieldName, + String nestedObjectFieldName) throws IOException { - java.lang.reflect.Field[] fields = clazz.getDeclaredFields(); + java.lang.reflect.Field[] fields = clazz.getDeclaredFields(); - if(!isRootObject && isAnyPropertyAnnotatedAsField(fields)){ - xContentBuilder.startObject(nestedObjectFieldName) - .field("type", "object") - .startObject("properties"); - } + if (!isRootObject && isAnyPropertyAnnotatedAsField(fields)) { + xContentBuilder.startObject(nestedObjectFieldName).field("type", "object").startObject("properties"); + } - for(java.lang.reflect.Field field : fields){ - if(isEntity(field)){ - mapEntity(xContentBuilder, field.getType(), false, EMPTY, field.getName()); - } - Field fieldAnnotation = field.getAnnotation(Field.class); - if(isRootObject && fieldAnnotation != null && isIdField(field, idFieldName)){ - applyDefaultIdFieldMapping(xContentBuilder, field); - }else if(fieldAnnotation != null){ - applyFieldAnnotationMapping(xContentBuilder, field, fieldAnnotation); - } - } + for (java.lang.reflect.Field field : fields) { + if (isEntity(field)) { + mapEntity(xContentBuilder, field.getType(), false, EMPTY, field.getName()); + } + Field fieldAnnotation = field.getAnnotation(Field.class); + if (isRootObject && fieldAnnotation != null && isIdField(field, idFieldName)) { + applyDefaultIdFieldMapping(xContentBuilder, field); + } else if (fieldAnnotation != null) { + applyFieldAnnotationMapping(xContentBuilder, field, fieldAnnotation); + } + } - if(!isRootObject && isAnyPropertyAnnotatedAsField(fields)){ - xContentBuilder.endObject().endObject(); - } + if (!isRootObject && isAnyPropertyAnnotatedAsField(fields)) { + xContentBuilder.endObject().endObject(); + } - } + } - private static void applyDefaultIdFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field) throws IOException { - xContentBuilder.startObject(field.getName()) - .field("type", "string") - .field("index", "not_analyzed") - .endObject(); - } + private static void applyDefaultIdFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field) + throws IOException { + xContentBuilder.startObject(field.getName()).field("type", "string").field("index", "not_analyzed").endObject(); + } - private static void applyFieldAnnotationMapping(XContentBuilder xContentBuilder, - java.lang.reflect.Field field, - Field fieldAnnotation) throws IOException { - xContentBuilder.startObject(field.getName()); - xContentBuilder.field("store", fieldAnnotation.store()); - if(isNotBlank(fieldAnnotation.type())){ - xContentBuilder.field("type", fieldAnnotation.type()); - } - if(isNotBlank(fieldAnnotation.index())){ - xContentBuilder.field("index", fieldAnnotation.index()); - } - if(isNotBlank(fieldAnnotation.searchAnalyzer())){ - xContentBuilder.field("search_analyzer", fieldAnnotation.searchAnalyzer()); - } - if(isNotBlank(fieldAnnotation.indexAnalyzer())){ - xContentBuilder.field("index_analyzer", fieldAnnotation.indexAnalyzer()); - } - xContentBuilder.endObject(); - } + private static void applyFieldAnnotationMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field, + Field fieldAnnotation) throws IOException { + xContentBuilder.startObject(field.getName()); + xContentBuilder.field("store", fieldAnnotation.store()); + if (isNotBlank(fieldAnnotation.type())) { + xContentBuilder.field("type", fieldAnnotation.type()); + } + if (isNotBlank(fieldAnnotation.index())) { + xContentBuilder.field("index", fieldAnnotation.index()); + } + if (isNotBlank(fieldAnnotation.searchAnalyzer())) { + xContentBuilder.field("search_analyzer", fieldAnnotation.searchAnalyzer()); + } + if (isNotBlank(fieldAnnotation.indexAnalyzer())) { + xContentBuilder.field("index_analyzer", fieldAnnotation.indexAnalyzer()); + } + xContentBuilder.endObject(); + } - private static boolean isEntity(java.lang.reflect.Field field) { - TypeInformation typeInformation = ClassTypeInformation.from(field.getType()); - TypeInformation actualType = typeInformation.getActualType(); - boolean isComplexType = actualType == null ? false : !SIMPLE_TYPE_HOLDER.isSimpleType(actualType.getType()); - return isComplexType && !actualType.isCollectionLike() && !Map.class.isAssignableFrom(typeInformation.getType()); - } + private static boolean isEntity(java.lang.reflect.Field field) { + TypeInformation typeInformation = ClassTypeInformation.from(field.getType()); + TypeInformation actualType = typeInformation.getActualType(); + boolean isComplexType = actualType == null ? false : !SIMPLE_TYPE_HOLDER.isSimpleType(actualType.getType()); + return isComplexType && !actualType.isCollectionLike() && !Map.class.isAssignableFrom(typeInformation.getType()); + } - private static boolean isAnyPropertyAnnotatedAsField(java.lang.reflect.Field[] fields){ - if(fields != null){ - for(java.lang.reflect.Field field : fields){ - if (field.isAnnotationPresent(Field.class)){ - return true; - } - } - } - return false; - } + private static boolean isAnyPropertyAnnotatedAsField(java.lang.reflect.Field[] fields) { + if (fields != null) { + for (java.lang.reflect.Field field : fields) { + if (field.isAnnotationPresent(Field.class)) { + return true; + } + } + } + return false; + } - private static boolean isIdField(java.lang.reflect.Field field, String idFieldName){ - return idFieldName.equals(field.getName()); - } + private static boolean isIdField(java.lang.reflect.Field field, String idFieldName) { + return idFieldName.equals(field.getName()); + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/ResultsMapper.java b/src/main/java/org/springframework/data/elasticsearch/core/ResultsMapper.java index 82890ee32..b3e0a5699 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/ResultsMapper.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ResultsMapper.java @@ -20,15 +20,16 @@ import org.springframework.data.domain.Page; /** * ResultsMapper + * * @param - * + * * @author Rizwan Idrees * @author Mohsin Husen - * + * */ public interface ResultsMapper { - Page mapResults(SearchResponse response); + Page mapResults(SearchResponse response); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/convert/DateTimeConverters.java b/src/main/java/org/springframework/data/elasticsearch/core/convert/DateTimeConverters.java index e0f6a3d68..ba2c10106 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/convert/DateTimeConverters.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/convert/DateTimeConverters.java @@ -25,15 +25,15 @@ import org.springframework.core.convert.converter.Converter; import java.util.Date; /** - * DateTimeConverters - * + * DateTimeConverters + * * @author Rizwan Idrees * @author Mohsin Husen */ public final class DateTimeConverters { - private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC); + private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC); public enum JodaDateTimeConverter implements Converter { INSTANCE; diff --git a/src/main/java/org/springframework/data/elasticsearch/core/convert/ElasticsearchConverter.java b/src/main/java/org/springframework/data/elasticsearch/core/convert/ElasticsearchConverter.java index a7728c1ed..802999ef6 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/convert/ElasticsearchConverter.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/convert/ElasticsearchConverter.java @@ -21,26 +21,26 @@ import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersiste import org.springframework.data.mapping.context.MappingContext; /** - * ElasticsearchConverter - * + * ElasticsearchConverter + * * @author Rizwan Idrees * @author Mohsin Husen */ -public interface ElasticsearchConverter{ +public interface ElasticsearchConverter { - /** - * Returns the underlying {@link org.springframework.data.mapping.context.MappingContext} used by the converter. - * - * @return never {@literal null} - */ - MappingContext, ElasticsearchPersistentProperty> getMappingContext(); + /** + * Returns the underlying {@link org.springframework.data.mapping.context.MappingContext} used by the converter. + * + * @return never {@literal null} + */ + MappingContext, ElasticsearchPersistentProperty> getMappingContext(); - /** - * Returns the underlying {@link org.springframework.core.convert.ConversionService} used by the converter. - * - * @return never {@literal null}. - */ - ConversionService getConversionService(); + /** + * Returns the underlying {@link org.springframework.core.convert.ConversionService} used by the converter. + * + * @return never {@literal null}. + */ + ConversionService getConversionService(); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverter.java b/src/main/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverter.java index e05bbdfcf..5ef0003c6 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverter.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/convert/MappingElasticsearchConverter.java @@ -27,28 +27,29 @@ import org.springframework.data.mapping.context.MappingContext; import org.springframework.util.Assert; /** - * MappingElasticsearchConverter - * + * MappingElasticsearchConverter + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class MappingElasticsearchConverter implements ElasticsearchConverter, ApplicationContextAware{ +public class MappingElasticsearchConverter implements ElasticsearchConverter, ApplicationContextAware { - private final MappingContext,ElasticsearchPersistentProperty> mappingContext; + private final MappingContext, ElasticsearchPersistentProperty> mappingContext; private final GenericConversionService conversionService; @SuppressWarnings("unused") private ApplicationContext applicationContext; - public MappingElasticsearchConverter(MappingContext,ElasticsearchPersistentProperty> mappingContext) { + public MappingElasticsearchConverter( + MappingContext, ElasticsearchPersistentProperty> mappingContext) { Assert.notNull(mappingContext); this.mappingContext = mappingContext; this.conversionService = new DefaultConversionService(); } @Override - public MappingContext,ElasticsearchPersistentProperty> getMappingContext() { + public MappingContext, ElasticsearchPersistentProperty> getMappingContext() { return mappingContext; } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/mapping/ElasticsearchPersistentEntity.java b/src/main/java/org/springframework/data/elasticsearch/core/mapping/ElasticsearchPersistentEntity.java index c4c637f45..8b9ea721d 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/mapping/ElasticsearchPersistentEntity.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/mapping/ElasticsearchPersistentEntity.java @@ -16,9 +16,10 @@ package org.springframework.data.elasticsearch.core.mapping; import org.springframework.data.mapping.PersistentEntity; + /** * ElasticsearchPersistentEntity - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -26,10 +27,16 @@ import org.springframework.data.mapping.PersistentEntity; public interface ElasticsearchPersistentEntity extends PersistentEntity { String getIndexName(); - String getIndexType(); - short getShards(); - short getReplicas(); - String getRefreshInterval(); - String getIndexStoreType(); - ElasticsearchPersistentProperty getVersionProperty(); + + String getIndexType(); + + short getShards(); + + short getReplicas(); + + String getRefreshInterval(); + + String getIndexStoreType(); + + ElasticsearchPersistentProperty getVersionProperty(); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/mapping/ElasticsearchPersistentProperty.java b/src/main/java/org/springframework/data/elasticsearch/core/mapping/ElasticsearchPersistentProperty.java index 1ef8d46b9..e9918b392 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/mapping/ElasticsearchPersistentProperty.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/mapping/ElasticsearchPersistentProperty.java @@ -17,24 +17,25 @@ package org.springframework.data.elasticsearch.core.mapping; import org.springframework.core.convert.converter.Converter; import org.springframework.data.mapping.PersistentProperty; + /** - * ElasticsearchPersistentProperty - * + * ElasticsearchPersistentProperty + * * @author Rizwan Idrees * @author Mohsin Husen */ -public interface ElasticsearchPersistentProperty extends PersistentProperty{ +public interface ElasticsearchPersistentProperty extends PersistentProperty { - String getFieldName(); + String getFieldName(); - public enum PropertyToFieldNameConverter implements Converter { + public enum PropertyToFieldNameConverter implements Converter { - INSTANCE; + INSTANCE; - public String convert(ElasticsearchPersistentProperty source) { - return source.getFieldName(); - } - } + public String convert(ElasticsearchPersistentProperty source) { + return source.getFieldName(); + } + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchMappingContext.java b/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchMappingContext.java index 9e6e6493f..a78db222f 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchMappingContext.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchMappingContext.java @@ -24,7 +24,7 @@ import java.lang.reflect.Field; /** * SimpleElasticsearchMappingContext - * + * * @author Rizwan Idrees * @author Mohsin Husen */ diff --git a/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentEntity.java b/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentEntity.java index 08e20c035..8173d921b 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentEntity.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentEntity.java @@ -33,81 +33,82 @@ import static org.springframework.util.StringUtils.hasText; /** * Elasticsearch specific {@link org.springframework.data.mapping.PersistentEntity} implementation holding - * + * * @param - * + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class SimpleElasticsearchPersistentEntity extends BasicPersistentEntity implements - ElasticsearchPersistentEntity, ApplicationContextAware { +public class SimpleElasticsearchPersistentEntity extends BasicPersistentEntity + implements ElasticsearchPersistentEntity, ApplicationContextAware { - private final StandardEvaluationContext context; - private String indexName; - private String indexType; - private short shards; - private short replicas; - private String refreshInterval; - private String indexStoreType; + private final StandardEvaluationContext context; + private String indexName; + private String indexType; + private short shards; + private short replicas; + private String refreshInterval; + private String indexStoreType; - public SimpleElasticsearchPersistentEntity(TypeInformation typeInformation) { - super(typeInformation); - this.context = new StandardEvaluationContext(); - Class clazz = typeInformation.getType(); - if(clazz.isAnnotationPresent(Document.class)){ - Document document = clazz.getAnnotation(Document.class); - Assert.hasText(document.indexName(), " Unknown indexName. Make sure the indexName is defined. e.g @Document(indexName=\"foo\")"); - this.indexName = typeInformation.getType().getAnnotation(Document.class).indexName(); - this.indexType = hasText(document.type())? document.type() : clazz.getSimpleName().toLowerCase(Locale.ENGLISH); - this.shards = typeInformation.getType().getAnnotation(Document.class).shards(); - this.replicas = typeInformation.getType().getAnnotation(Document.class).replicas(); - this.refreshInterval = typeInformation.getType().getAnnotation(Document.class).refreshInterval(); - this.indexStoreType = typeInformation.getType().getAnnotation(Document.class).indexStoreType(); - } - } + public SimpleElasticsearchPersistentEntity(TypeInformation typeInformation) { + super(typeInformation); + this.context = new StandardEvaluationContext(); + Class clazz = typeInformation.getType(); + if (clazz.isAnnotationPresent(Document.class)) { + Document document = clazz.getAnnotation(Document.class); + Assert.hasText(document.indexName(), + " Unknown indexName. Make sure the indexName is defined. e.g @Document(indexName=\"foo\")"); + this.indexName = typeInformation.getType().getAnnotation(Document.class).indexName(); + this.indexType = hasText(document.type()) ? document.type() : clazz.getSimpleName().toLowerCase(Locale.ENGLISH); + this.shards = typeInformation.getType().getAnnotation(Document.class).shards(); + this.replicas = typeInformation.getType().getAnnotation(Document.class).replicas(); + this.refreshInterval = typeInformation.getType().getAnnotation(Document.class).refreshInterval(); + this.indexStoreType = typeInformation.getType().getAnnotation(Document.class).indexStoreType(); + } + } - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - context.addPropertyAccessor(new BeanFactoryAccessor()); - context.setBeanResolver(new BeanFactoryResolver(applicationContext)); - context.setRootObject(applicationContext); - } + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + context.addPropertyAccessor(new BeanFactoryAccessor()); + context.setBeanResolver(new BeanFactoryResolver(applicationContext)); + context.setRootObject(applicationContext); + } - @Override - public String getIndexName() { - return indexName; - } + @Override + public String getIndexName() { + return indexName; + } - @Override - public String getIndexType() { - return indexType; - } + @Override + public String getIndexType() { + return indexType; + } - @Override - public String getIndexStoreType() { - return indexStoreType; - } + @Override + public String getIndexStoreType() { + return indexStoreType; + } - @Override - public short getShards() { - return shards; - } + @Override + public short getShards() { + return shards; + } - @Override - public short getReplicas() { - return replicas; - } + @Override + public short getReplicas() { + return replicas; + } - @Override - public String getRefreshInterval() { - return refreshInterval; - } + @Override + public String getRefreshInterval() { + return refreshInterval; + } - @Override - public void addPersistentProperty(ElasticsearchPersistentProperty property) { - super.addPersistentProperty(property); - if(property.isVersionProperty()){ - Assert.isTrue(property.getType() == Long.class, "Version property should be Long"); - } - } + @Override + public void addPersistentProperty(ElasticsearchPersistentProperty property) { + super.addPersistentProperty(property); + if (property.isVersionProperty()) { + Assert.isTrue(property.getType() == Long.class, "Version property should be Long"); + } + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentProperty.java b/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentProperty.java index 3d0522339..b93b58d3a 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentProperty.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentProperty.java @@ -27,12 +27,12 @@ import java.util.Set; /** * Elasticsearch specific {@link org.springframework.data.mapping.PersistentProperty} implementation processing - * + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class SimpleElasticsearchPersistentProperty extends AnnotationBasedPersistentProperty implements - ElasticsearchPersistentProperty { +public class SimpleElasticsearchPersistentProperty extends + AnnotationBasedPersistentProperty implements ElasticsearchPersistentProperty { private static final Set> SUPPORTED_ID_TYPES = new HashSet>(); private static final Set SUPPORTED_ID_PROPERTY_NAMES = new HashSet(); @@ -40,11 +40,11 @@ public class SimpleElasticsearchPersistentProperty extends AnnotationBasedPersis static { SUPPORTED_ID_TYPES.add(String.class); SUPPORTED_ID_PROPERTY_NAMES.add("id"); - SUPPORTED_ID_PROPERTY_NAMES.add("documentId"); + SUPPORTED_ID_PROPERTY_NAMES.add("documentId"); } public SimpleElasticsearchPersistentProperty(Field field, PropertyDescriptor propertyDescriptor, - PersistentEntity owner, SimpleTypeHolder simpleTypeHolder) { + PersistentEntity owner, SimpleTypeHolder simpleTypeHolder) { super(field, propertyDescriptor, owner, simpleTypeHolder); } @@ -58,7 +58,7 @@ public class SimpleElasticsearchPersistentProperty extends AnnotationBasedPersis return super.isIdProperty() || SUPPORTED_ID_PROPERTY_NAMES.contains(getFieldName()); } - @Override + @Override protected Association createAssociation() { return null; } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/AbstractQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/AbstractQuery.java index 61c8e88b3..f0abaa8f2 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/AbstractQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/AbstractQuery.java @@ -26,77 +26,77 @@ import static org.apache.commons.collections.CollectionUtils.addAll; /** * AbstractQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ -abstract class AbstractQuery implements Query{ +abstract class AbstractQuery implements Query { - protected Pageable pageable = DEFAULT_PAGE; - protected Sort sort; - protected List indices = new ArrayList(); - protected List types = new ArrayList(); - protected List fields = new ArrayList(); + protected Pageable pageable = DEFAULT_PAGE; + protected Sort sort; + protected List indices = new ArrayList(); + protected List types = new ArrayList(); + protected List fields = new ArrayList(); - @Override - public Sort getSort() { - return this.sort; - } + @Override + public Sort getSort() { + return this.sort; + } - @Override - public Pageable getPageable() { - return this.pageable; - } + @Override + public Pageable getPageable() { + return this.pageable; + } - @Override - public final T setPageable(Pageable pageable) { - Assert.notNull(pageable); - this.pageable = pageable; - return (T) this.addSort(pageable.getSort()); - } + @Override + public final T setPageable(Pageable pageable) { + Assert.notNull(pageable); + this.pageable = pageable; + return (T) this.addSort(pageable.getSort()); + } - @Override - public void addFields(String...fields) { - addAll(this.fields, fields); - } + @Override + public void addFields(String... fields) { + addAll(this.fields, fields); + } - @Override - public List getFields() { - return fields; - } + @Override + public List getFields() { + return fields; + } - @Override - public List getIndices() { - return indices; - } + @Override + public List getIndices() { + return indices; + } - @Override - public void addIndices(String... indices) { - addAll(this.indices,indices); - } + @Override + public void addIndices(String... indices) { + addAll(this.indices, indices); + } - @Override - public void addTypes(String... types) { - addAll(this.types,types); - } + @Override + public void addTypes(String... types) { + addAll(this.types, types); + } - @Override - public List getTypes() { - return types; - } + @Override + public List getTypes() { + return types; + } - @SuppressWarnings("unchecked") - public final T addSort(Sort sort) { - if (sort == null) { - return (T) this; - } + @SuppressWarnings("unchecked") + public final T addSort(Sort sort) { + if (sort == null) { + return (T) this; + } - if (this.sort == null) { - this.sort = sort; - } else { - this.sort = this.sort.and(sort); - } + if (this.sort == null) { + this.sort = sort; + } else { + this.sort = this.sort.and(sort); + } - return (T) this; - } + return (T) this; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/Criteria.java b/src/main/java/org/springframework/data/elasticsearch/core/query/Criteria.java index 6ac0979c3..f375eb2d8 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/Criteria.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/Criteria.java @@ -30,7 +30,7 @@ import org.springframework.util.Assert; /** * Criteria is the central class when constructing queries. It follows more or less a fluent API style, which allows to * easily chain together multiple criteria. - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -251,11 +251,10 @@ public class Criteria { * @return */ public Criteria fuzzy(String s) { - criteria.add(new CriteriaEntry(OperationKey.FUZZY, s)); - return this; + criteria.add(new CriteriaEntry(OperationKey.FUZZY, s)); + return this; } - /** * Crates new CriteriaEntry allowing native elasticsearch expressions * @@ -342,11 +341,10 @@ public class Criteria { */ public Criteria in(Iterable values) { Assert.notNull(values, "Collection of 'in' values must not be null"); - criteria.add(new CriteriaEntry(OperationKey.IN, values)); + criteria.add(new CriteriaEntry(OperationKey.IN, values)); return this; } - private void assertNoBlankInWildcardedQuery(String searchString, boolean leadingWildcard, boolean trailingWildcard) { if (StringUtils.contains(searchString, CRITERIA_VALUE_SEPERATOR)) { throw new InvalidDataAccessApiUsageException("Cannot constructQuery '" + (leadingWildcard ? "*" : "") + "\"" @@ -384,13 +382,13 @@ public class Criteria { return this.negating; } - public boolean isAnd(){ - return AND_OPERATOR == getConjunctionOperator(); - } + public boolean isAnd() { + return AND_OPERATOR == getConjunctionOperator(); + } - public boolean isOr(){ - return OR_OPERATOR == getConjunctionOperator(); - } + public boolean isOr() { + return OR_OPERATOR == getConjunctionOperator(); + } public float getBoost() { return this.boost; @@ -431,7 +429,7 @@ public class Criteria { public static class CriteriaEntry { - private OperationKey key; + private OperationKey key; private Object value; CriteriaEntry(OperationKey key, Object value) { diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/CriteriaQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/CriteriaQuery.java index 806b5a36c..734e710d2 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/CriteriaQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/CriteriaQuery.java @@ -15,67 +15,67 @@ */ package org.springframework.data.elasticsearch.core.query; - import org.springframework.data.domain.Pageable; import org.springframework.util.Assert; /** - * CriteriaQuery - * + * CriteriaQuery + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class CriteriaQuery extends AbstractQuery{ +public class CriteriaQuery extends AbstractQuery { - private Criteria criteria; - private CriteriaQuery() { - } + private Criteria criteria; - public CriteriaQuery(Criteria criteria) { - this(criteria, null); - } + private CriteriaQuery() { + } - public CriteriaQuery(Criteria criteria, Pageable pageable) { - this.criteria = criteria; - this.pageable = pageable; - if (pageable != null) { - this.addSort(pageable.getSort()); - } - } + public CriteriaQuery(Criteria criteria) { + this(criteria, null); + } - public static final Query fromQuery(CriteriaQuery source) { - return fromQuery(source, new CriteriaQuery()); - } + public CriteriaQuery(Criteria criteria, Pageable pageable) { + this.criteria = criteria; + this.pageable = pageable; + if (pageable != null) { + this.addSort(pageable.getSort()); + } + } - public static T fromQuery(CriteriaQuery source, T destination) { - if (source == null || destination == null) { - return null; - } + public static final Query fromQuery(CriteriaQuery source) { + return fromQuery(source, new CriteriaQuery()); + } - if (source.getCriteria() != null) { - destination.addCriteria(source.getCriteria()); - } + public static T fromQuery(CriteriaQuery source, T destination) { + if (source == null || destination == null) { + return null; + } - if (source.getSort() != null) { - destination.addSort(source.getSort()); - } + if (source.getCriteria() != null) { + destination.addCriteria(source.getCriteria()); + } - return destination; - } + if (source.getSort() != null) { + destination.addSort(source.getSort()); + } - @SuppressWarnings("unchecked") - public final T addCriteria(Criteria criteria) { - Assert.notNull(criteria, "Cannot add null criteria."); - if (this.criteria == null) { - this.criteria = criteria; - } else { - this.criteria.and(criteria); - } - return (T) this; - } + return destination; + } - public Criteria getCriteria() { - return this.criteria; - } + @SuppressWarnings("unchecked") + public final T addCriteria(Criteria criteria) { + Assert.notNull(criteria, "Cannot add null criteria."); + if (this.criteria == null) { + this.criteria = criteria; + } else { + this.criteria.and(criteria); + } + return (T) this; + } + + public Criteria getCriteria() { + return this.criteria; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/DeleteQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/DeleteQuery.java index 28f3ab7fb..4578c834c 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/DeleteQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/DeleteQuery.java @@ -15,23 +15,23 @@ */ package org.springframework.data.elasticsearch.core.query; - import org.elasticsearch.index.query.QueryBuilder; + /** * DeleteQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class DeleteQuery{ +public class DeleteQuery { - private QueryBuilder query; + private QueryBuilder query; - public QueryBuilder getQuery() { - return query; - } + public QueryBuilder getQuery() { + return query; + } - public void setQuery(QueryBuilder query) { - this.query = query; - } + public void setQuery(QueryBuilder query) { + this.query = query; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/Field.java b/src/main/java/org/springframework/data/elasticsearch/core/query/Field.java index 4ba4eac6b..56e7268a2 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/Field.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/Field.java @@ -17,7 +17,7 @@ package org.springframework.data.elasticsearch.core.query; /** * Defines a Field that can be used within a Criteria. - * + * * @author Rizwan Idrees * @author Mohsin Husen */ diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/GetQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/GetQuery.java index ce4ff4997..76f1df9bf 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/GetQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/GetQuery.java @@ -16,20 +16,20 @@ package org.springframework.data.elasticsearch.core.query; /** - * GetQuery - * + * GetQuery + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class GetQuery{ +public class GetQuery { - private String id; + private String id; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/IndexQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/IndexQuery.java index 8535ccc0d..aeeda64ab 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/IndexQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/IndexQuery.java @@ -17,56 +17,56 @@ package org.springframework.data.elasticsearch.core.query; /** * IndexQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class IndexQuery{ +public class IndexQuery { - private String id; - private Object object; - private Long version; - private String indexName; - private String type; + private String id; + private Object object; + private Long version; + private String indexName; + private String type; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public Object getObject() { - return object; - } + public Object getObject() { + return object; + } - public void setObject(Object object) { - this.object = object; - } + public void setObject(Object object) { + this.object = object; + } - public Long getVersion() { - return version; - } + public Long getVersion() { + return version; + } - public void setVersion(Long version) { - this.version = version; - } + public void setVersion(Long version) { + this.version = version; + } - public String getIndexName() { - return indexName; - } + public String getIndexName() { + return indexName; + } - public void setIndexName(String indexName) { - this.indexName = indexName; - } + public void setIndexName(String indexName) { + this.indexName = indexName; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/MoreLikeThisQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/MoreLikeThisQuery.java index 33baa4373..f95099c13 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/MoreLikeThisQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/MoreLikeThisQuery.java @@ -25,164 +25,164 @@ import static org.springframework.data.elasticsearch.core.query.Query.DEFAULT_PA /** * MoreLikeThisQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ public class MoreLikeThisQuery { - private String id; - private String indexName; - private String type; - private List searchIndices = new ArrayList(); - private List searchTypes = new ArrayList(); - private List fields = new ArrayList(); - private String routing; - private Float percentTermsToMatch; - private Integer minTermFreq; - private Integer maxQueryTerms; - private List stopWords = new ArrayList(); - private Integer minDocFreq; - private Integer maxDocFreq; - private Integer minWordLen; - private Integer maxWordLen; - private Float boostTerms; - private Pageable pageable = DEFAULT_PAGE; + private String id; + private String indexName; + private String type; + private List searchIndices = new ArrayList(); + private List searchTypes = new ArrayList(); + private List fields = new ArrayList(); + private String routing; + private Float percentTermsToMatch; + private Integer minTermFreq; + private Integer maxQueryTerms; + private List stopWords = new ArrayList(); + private Integer minDocFreq; + private Integer maxDocFreq; + private Integer minWordLen; + private Integer maxWordLen; + private Float boostTerms; + private Pageable pageable = DEFAULT_PAGE; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getIndexName() { - return indexName; - } + public String getIndexName() { + return indexName; + } - public void setIndexName(String indexName) { - this.indexName = indexName; - } + public void setIndexName(String indexName) { + this.indexName = indexName; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public List getSearchIndices() { - return searchIndices; - } + public List getSearchIndices() { + return searchIndices; + } - public void addSearchIndices(String...searchIndices) { - addAll(this.searchIndices, searchIndices); - } + public void addSearchIndices(String... searchIndices) { + addAll(this.searchIndices, searchIndices); + } - public List getSearchTypes() { - return searchTypes; - } + public List getSearchTypes() { + return searchTypes; + } - public void addSearchTypes(String...searchTypes) { - addAll(this.searchTypes, searchTypes); - } + public void addSearchTypes(String... searchTypes) { + addAll(this.searchTypes, searchTypes); + } - public List getFields() { - return fields; - } + public List getFields() { + return fields; + } - public void addFields(String...fields) { - addAll(this.fields,fields); - } + public void addFields(String... fields) { + addAll(this.fields, fields); + } - public String getRouting() { - return routing; - } + public String getRouting() { + return routing; + } - public void setRouting(String routing) { - this.routing = routing; - } + public void setRouting(String routing) { + this.routing = routing; + } - public Float getPercentTermsToMatch() { - return percentTermsToMatch; - } + public Float getPercentTermsToMatch() { + return percentTermsToMatch; + } - public void setPercentTermsToMatch(Float percentTermsToMatch) { - this.percentTermsToMatch = percentTermsToMatch; - } + public void setPercentTermsToMatch(Float percentTermsToMatch) { + this.percentTermsToMatch = percentTermsToMatch; + } - public Integer getMinTermFreq() { - return minTermFreq; - } + public Integer getMinTermFreq() { + return minTermFreq; + } - public void setMinTermFreq(Integer minTermFreq) { - this.minTermFreq = minTermFreq; - } + public void setMinTermFreq(Integer minTermFreq) { + this.minTermFreq = minTermFreq; + } - public Integer getMaxQueryTerms() { - return maxQueryTerms; - } + public Integer getMaxQueryTerms() { + return maxQueryTerms; + } - public void setMaxQueryTerms(Integer maxQueryTerms) { - this.maxQueryTerms = maxQueryTerms; - } + public void setMaxQueryTerms(Integer maxQueryTerms) { + this.maxQueryTerms = maxQueryTerms; + } - public List getStopWords() { - return stopWords; - } + public List getStopWords() { + return stopWords; + } - public void addStopWords(String...stopWords) { - addAll(this.stopWords,stopWords); - } + public void addStopWords(String... stopWords) { + addAll(this.stopWords, stopWords); + } - public Integer getMinDocFreq() { - return minDocFreq; - } + public Integer getMinDocFreq() { + return minDocFreq; + } - public void setMinDocFreq(Integer minDocFreq) { - this.minDocFreq = minDocFreq; - } + public void setMinDocFreq(Integer minDocFreq) { + this.minDocFreq = minDocFreq; + } - public Integer getMaxDocFreq() { - return maxDocFreq; - } + public Integer getMaxDocFreq() { + return maxDocFreq; + } - public void setMaxDocFreq(Integer maxDocFreq) { - this.maxDocFreq = maxDocFreq; - } + public void setMaxDocFreq(Integer maxDocFreq) { + this.maxDocFreq = maxDocFreq; + } - public Integer getMinWordLen() { - return minWordLen; - } + public Integer getMinWordLen() { + return minWordLen; + } - public void setMinWordLen(Integer minWordLen) { - this.minWordLen = minWordLen; - } + public void setMinWordLen(Integer minWordLen) { + this.minWordLen = minWordLen; + } - public Integer getMaxWordLen() { - return maxWordLen; - } + public Integer getMaxWordLen() { + return maxWordLen; + } - public void setMaxWordLen(Integer maxWordLen) { - this.maxWordLen = maxWordLen; - } + public void setMaxWordLen(Integer maxWordLen) { + this.maxWordLen = maxWordLen; + } - public Float getBoostTerms() { - return boostTerms; - } + public Float getBoostTerms() { + return boostTerms; + } - public void setBoostTerms(Float boostTerms) { - this.boostTerms = boostTerms; - } + public void setBoostTerms(Float boostTerms) { + this.boostTerms = boostTerms; + } - public Pageable getPageable() { - return pageable; - } + public Pageable getPageable() { + return pageable; + } - public void setPageable(Pageable pageable) { - this.pageable = pageable; - } + public void setPageable(Pageable pageable) { + this.pageable = pageable; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQuery.java index b2ba04b43..86596e2bd 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQuery.java @@ -15,40 +15,38 @@ */ package org.springframework.data.elasticsearch.core.query; - import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.sort.SortBuilder; /** * NativeSearchQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak */ public class NativeSearchQuery extends AbstractQuery implements SearchQuery { - private QueryBuilder query; - private FilterBuilder filter; - private SortBuilder sort; + private QueryBuilder query; + private FilterBuilder filter; + private SortBuilder sort; - public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, SortBuilder sort) { - this.query = query; - this.filter = filter; - this.sort = sort; - } + public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, SortBuilder sort) { + this.query = query; + this.filter = filter; + this.sort = sort; + } - public QueryBuilder getQuery() { - return query; - } + public QueryBuilder getQuery() { + return query; + } + public FilterBuilder getFilter() { + return filter; + } - public FilterBuilder getFilter() { - return filter; - } - - public SortBuilder getElasticsearchSort() { - return sort; - } + public SortBuilder getElasticsearchSort() { + return sort; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQueryBuilder.java b/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQueryBuilder.java index 44a09f052..b31573d78 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQueryBuilder.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/NativeSearchQueryBuilder.java @@ -22,7 +22,7 @@ import org.springframework.data.domain.Pageable; /** * NativeSearchQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak @@ -30,63 +30,63 @@ import org.springframework.data.domain.Pageable; public class NativeSearchQueryBuilder { - private QueryBuilder queryBuilder; - private FilterBuilder filterBuilder; - private SortBuilder sortBuilder; - private Pageable pageable; - private String[] indices; - private String[] types; - private String[] fields; + private QueryBuilder queryBuilder; + private FilterBuilder filterBuilder; + private SortBuilder sortBuilder; + private Pageable pageable; + private String[] indices; + private String[] types; + private String[] fields; - public NativeSearchQueryBuilder withQuery(QueryBuilder queryBuilder){ - this.queryBuilder = queryBuilder; - return this; - } + public NativeSearchQueryBuilder withQuery(QueryBuilder queryBuilder) { + this.queryBuilder = queryBuilder; + return this; + } - public NativeSearchQueryBuilder withFilter(FilterBuilder filterBuilder){ - this.filterBuilder = filterBuilder; - return this; - } + public NativeSearchQueryBuilder withFilter(FilterBuilder filterBuilder) { + this.filterBuilder = filterBuilder; + return this; + } - public NativeSearchQueryBuilder withSort(SortBuilder sortBuilder){ - this.sortBuilder = sortBuilder; - return this; - } + public NativeSearchQueryBuilder withSort(SortBuilder sortBuilder) { + this.sortBuilder = sortBuilder; + return this; + } - public NativeSearchQueryBuilder withPageable(Pageable pageable){ - this.pageable = pageable; - return this; - } + public NativeSearchQueryBuilder withPageable(Pageable pageable) { + this.pageable = pageable; + return this; + } - public NativeSearchQueryBuilder withIndices(String... indices){ - this.indices = indices; - return this; - } + public NativeSearchQueryBuilder withIndices(String... indices) { + this.indices = indices; + return this; + } - public NativeSearchQueryBuilder withTypes(String... types){ - this.types = types; - return this; - } + public NativeSearchQueryBuilder withTypes(String... types) { + this.types = types; + return this; + } - public NativeSearchQueryBuilder withFields(String... fields){ - this.fields = fields; - return this; - } + public NativeSearchQueryBuilder withFields(String... fields) { + this.fields = fields; + return this; + } - public NativeSearchQuery build(){ - NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryBuilder,filterBuilder,sortBuilder); - if(pageable != null){ - nativeSearchQuery.setPageable(pageable); - } - if(indices != null) { - nativeSearchQuery.addIndices(indices); - } - if(types != null) { - nativeSearchQuery.addTypes(types); - } - if(fields != null) { - nativeSearchQuery.addFields(fields); - } - return nativeSearchQuery; - } + public NativeSearchQuery build() { + NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryBuilder, filterBuilder, sortBuilder); + if (pageable != null) { + nativeSearchQuery.setPageable(pageable); + } + if (indices != null) { + nativeSearchQuery.addIndices(indices); + } + if (types != null) { + nativeSearchQuery.addTypes(types); + } + if (fields != null) { + nativeSearchQuery.addFields(fields); + } + return nativeSearchQuery; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/Query.java b/src/main/java/org/springframework/data/elasticsearch/core/query/Query.java index 67784bcf8..3d85f9bf7 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/Query.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/Query.java @@ -15,99 +15,97 @@ */ package org.springframework.data.elasticsearch.core.query; - import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import java.util.List; + /** * Query - * + * * @author Rizwan Idrees * @author Mohsin Husen */ public interface Query { - public static final int DEFAULT_PAGE_SIZE = 10; - public static final Pageable DEFAULT_PAGE = new PageRequest(0, DEFAULT_PAGE_SIZE); + public static final int DEFAULT_PAGE_SIZE = 10; + public static final Pageable DEFAULT_PAGE = new PageRequest(0, DEFAULT_PAGE_SIZE); + /** + * restrict result to entries on given page. Corresponds to the 'start' and 'rows' parameter in elasticsearch + * + * @param pageable + * @return + */ + T setPageable(Pageable pageable); - /** - * restrict result to entries on given page. Corresponds to the 'start' and 'rows' parameter in elasticsearch - * - * @param pageable - * @return - */ - T setPageable(Pageable pageable); + /** + * Get filter queries if defined + * + * @return + */ + // List getFilterQueries(); + /** + * Get page settings if defined + * + * @return + */ + Pageable getPageable(); + /** + * Add {@link org.springframework.data.domain.Sort} to query + * + * @param sort + * @return + */ + T addSort(Sort sort); - /** - * Get filter queries if defined - * - * @return - */ - //List getFilterQueries(); + /** + * @return null if not set + */ + Sort getSort(); - /** - * Get page settings if defined - * - * @return - */ - Pageable getPageable(); + /** + * Get Indices to be searched + * + * @return + */ + List getIndices(); + /** + * Add Indices to be added as part of search request + * + * @param indices + */ + void addIndices(String... indices); + /** + * Add types to be searched + * + * @param types + */ + void addTypes(String... types); - /** - * Add {@link org.springframework.data.domain.Sort} to query - * - * @param sort - * @return - */ - T addSort(Sort sort); + /** + * Get types to be searched + * + * @return + */ + List getTypes(); - /** - * @return null if not set - */ - Sort getSort(); + /** + * Add fields to be added as part of search request + * + * @param fields + */ + void addFields(String... fields); - - /** - * Get Indices to be searched - * @return - */ - List getIndices(); - - - /** - * Add Indices to be added as part of search request - * @param indices - */ - void addIndices(String...indices); - - /** - * Add types to be searched - * @param types - */ - void addTypes(String...types); - - /** - * Get types to be searched - * @return - */ - List getTypes(); - - /** - * Add fields to be added as part of search request - * @param fields - */ - void addFields(String...fields); - - - /** - * Get fields to be returned as part of search request - * @return - */ - List getFields(); + /** + * Get fields to be returned as part of search request + * + * @return + */ + List getFields(); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/SearchQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/SearchQuery.java index 16315c64b..cbd535810 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/SearchQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/SearchQuery.java @@ -18,15 +18,18 @@ package org.springframework.data.elasticsearch.core.query; import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.sort.SortBuilder; + /** * NativeSearchQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak */ public interface SearchQuery extends Query { - QueryBuilder getQuery(); - FilterBuilder getFilter(); - SortBuilder getElasticsearchSort(); + QueryBuilder getQuery(); + + FilterBuilder getFilter(); + + SortBuilder getElasticsearchSort(); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/SimpleField.java b/src/main/java/org/springframework/data/elasticsearch/core/query/SimpleField.java index 6fb346eb5..649573821 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/SimpleField.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/SimpleField.java @@ -17,7 +17,7 @@ package org.springframework.data.elasticsearch.core.query; /** * The most trivial implementation of a Field - * + * * @author Rizwan Idrees * @author Mohsin Husen */ diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/StringQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/StringQuery.java index 9f59a3236..b77eb0956 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/StringQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/StringQuery.java @@ -15,38 +15,36 @@ */ package org.springframework.data.elasticsearch.core.query; - import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; /** * StringQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class StringQuery extends AbstractQuery{ +public class StringQuery extends AbstractQuery { - private String source; + private String source; - public StringQuery(String source) { - this.source = source; - } + public StringQuery(String source) { + this.source = source; + } - public StringQuery(String source, Pageable pageable) { - this.source = source; - this.pageable = pageable; - } + public StringQuery(String source, Pageable pageable) { + this.source = source; + this.pageable = pageable; + } - public StringQuery(String source, Pageable pageable, Sort sort) { - this.pageable = pageable; - this.sort = sort; - this.source = source; - } + public StringQuery(String source, Pageable pageable, Sort sort) { + this.pageable = pageable; + this.sort = sort; + this.source = source; + } - - public String getSource() { - return source; - } + public String getSource() { + return source; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchCrudRepository.java b/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchCrudRepository.java index f340b5505..617c921bc 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchCrudRepository.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchCrudRepository.java @@ -23,12 +23,12 @@ import java.util.List; /** * @param * @param - * + * * @author Rizwan Idrees * @author Mohsin Husen */ public interface ElasticsearchCrudRepository extends PagingAndSortingRepository { - List save(List entities); + List save(List entities); } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchRepository.java b/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchRepository.java index febdd97fd..352a68913 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchRepository.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchRepository.java @@ -26,20 +26,20 @@ import java.io.Serializable; /** * @param * @param - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @NoRepositoryBean -public interface ElasticsearchRepository extends ElasticsearchCrudRepository { +public interface ElasticsearchRepository extends ElasticsearchCrudRepository { - S index(S entity); + S index(S entity); - Iterable search(QueryBuilder query); + Iterable search(QueryBuilder query); - Page search(QueryBuilder query, Pageable pageable); + Page search(QueryBuilder query, Pageable pageable); - Page search(SearchQuery searchQuery); + Page search(SearchQuery searchQuery); - Page searchSimilar(T entity, SearchQuery searchQuery); + Page searchSimilar(T entity, SearchQuery searchQuery); } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/cdi/ElasticsearchRepositoryBean.java b/src/main/java/org/springframework/data/elasticsearch/repository/cdi/ElasticsearchRepositoryBean.java index e18a333a5..9efe063a9 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/cdi/ElasticsearchRepositoryBean.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/cdi/ElasticsearchRepositoryBean.java @@ -28,7 +28,7 @@ import java.util.Set; /** * Uses CdiRepositoryBean to create ElasticsearchRepository instances. - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -36,8 +36,8 @@ public class ElasticsearchRepositoryBean extends CdiRepositoryBean { private final Bean elasticsearchOperationsBean; - public ElasticsearchRepositoryBean(Bean operations, Set qualifiers, Class repositoryType, - BeanManager beanManager) { + public ElasticsearchRepositoryBean(Bean operations, Set qualifiers, + Class repositoryType, BeanManager beanManager) { super(qualifiers, repositoryType, beanManager); Assert.notNull(operations, "Cannot create repository with 'null' for ElasticsearchOperations."); @@ -46,7 +46,8 @@ public class ElasticsearchRepositoryBean extends CdiRepositoryBean { @Override protected T create(CreationalContext creationalContext, Class repositoryType) { - ElasticsearchOperations elasticsearchOperations = getDependencyInstance(elasticsearchOperationsBean, ElasticsearchOperations.class); + ElasticsearchOperations elasticsearchOperations = getDependencyInstance(elasticsearchOperationsBean, + ElasticsearchOperations.class); return new ElasticsearchRepositoryFactory(elasticsearchOperations).getRepository(repositoryType); } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/cdi/ElasticsearchRepositoryExtension.java b/src/main/java/org/springframework/data/elasticsearch/repository/cdi/ElasticsearchRepositoryExtension.java index f5e8e82e2..4fe639395 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/cdi/ElasticsearchRepositoryExtension.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/cdi/ElasticsearchRepositoryExtension.java @@ -33,7 +33,7 @@ import java.util.Set; /** * ElasticsearchRepositoryExtension - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -53,24 +53,25 @@ public class ElasticsearchRepositoryExtension extends CdiRepositoryExtensionSupp } void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) { - for (Entry, Set> entry : getRepositoryTypes()) { + for (Entry, Set> entry : getRepositoryTypes()) { Class repositoryType = entry.getKey(); Set qualifiers = entry.getValue(); Bean repositoryBean = createRepositoryBean(repositoryType, qualifiers, beanManager); - afterBeanDiscovery.addBean(repositoryBean); + afterBeanDiscovery.addBean(repositoryBean); } } private Bean createRepositoryBean(Class repositoryType, Set qualifiers, BeanManager beanManager) { - Bean elasticsearchOperationsBean = this.elasticsearchOperationsMap.get(qualifiers.toString()); + Bean elasticsearchOperationsBean = this.elasticsearchOperationsMap.get(qualifiers + .toString()); if (elasticsearchOperationsBean == null) { throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.", - ElasticsearchOperations.class.getName(), qualifiers)); + ElasticsearchOperations.class.getName(), qualifiers)); } - return new ElasticsearchRepositoryBean(elasticsearchOperationsBean, qualifiers, repositoryType, beanManager); + return new ElasticsearchRepositoryBean(elasticsearchOperationsBean, qualifiers, repositoryType, beanManager); } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/config/ElasticsearchRepositoriesRegistrar.java b/src/main/java/org/springframework/data/elasticsearch/repository/config/ElasticsearchRepositoriesRegistrar.java index 69c41cd3e..774044128 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/config/ElasticsearchRepositoriesRegistrar.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/config/ElasticsearchRepositoriesRegistrar.java @@ -21,9 +21,9 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi import java.lang.annotation.Annotation; /** - * {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} implementation to trigger configuration of the {@link EnableElasticsearchRepositories} - * annotation. - * + * {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} implementation to trigger configuration + * of the {@link EnableElasticsearchRepositories} annotation. + * * @author Rizwan Idrees * @author Mohsin Husen */ diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/config/ElasticsearchRepositoryConfigExtension.java b/src/main/java/org/springframework/data/elasticsearch/repository/config/ElasticsearchRepositoryConfigExtension.java index d92880159..7a336cd46 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/config/ElasticsearchRepositoryConfigExtension.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/config/ElasticsearchRepositoryConfigExtension.java @@ -23,12 +23,11 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi import org.springframework.data.repository.config.XmlRepositoryConfigurationSource; import org.w3c.dom.Element; - - /** - * {@link org.springframework.data.repository.config.RepositoryConfigurationExtension} implementation to configure Elasticsearch repository configuration support, - * evaluating the {@link EnableElasticsearchRepositories} annotation or the equivalent XML element. - * + * {@link org.springframework.data.repository.config.RepositoryConfigurationExtension} implementation to configure + * Elasticsearch repository configuration support, evaluating the {@link EnableElasticsearchRepositories} annotation or + * the equivalent XML element. + * * @author Rizwan Idrees * @author Mohsin Husen */ diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/config/EnableElasticsearchRepositories.java b/src/main/java/org/springframework/data/elasticsearch/repository/config/EnableElasticsearchRepositories.java index 0a5d884ee..b282d43a1 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/config/EnableElasticsearchRepositories.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/config/EnableElasticsearchRepositories.java @@ -24,9 +24,9 @@ import org.springframework.data.repository.query.QueryLookupStrategy.Key; import java.lang.annotation.*; /** - * Annotation to enable Elasticsearch repositories. Will scan the package of the annotated configuration class for Spring Data - * repositories by default. - * + * Annotation to enable Elasticsearch repositories. Will scan the package of the annotated configuration class for + * Spring Data repositories by default. + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -39,7 +39,8 @@ public @interface EnableElasticsearchRepositories { /** * Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.: - * {@code @EnableElasticsearchRepositories("org.my.pkg")} instead of {@code @EnableElasticsearchRepositories(basePackages="org.my.pkg")}. + * {@code @EnableElasticsearchRepositories("org.my.pkg")} instead of + * {@code @EnableElasticsearchRepositories(basePackages="org.my.pkg")}. */ String[] value() default {}; @@ -85,16 +86,17 @@ public @interface EnableElasticsearchRepositories { String namedQueriesLocation() default ""; /** - * Returns the key of the {@link org.springframework.data.repository.query.QueryLookupStrategy} to be used for lookup queries for query methods. Defaults to + * Returns the key of the {@link org.springframework.data.repository.query.QueryLookupStrategy} to be used for lookup + * queries for query methods. Defaults to * {@link org.springframework.data.repository.query.QueryLookupStrategy.Key#CREATE_IF_NOT_FOUND}. - * + * * @return */ Key queryLookupStrategy() default Key.CREATE_IF_NOT_FOUND; /** - * Returns the {@link org.springframework.beans.factory.FactoryBean} class to be used for each repository instance. Defaults to - * {@link ElasticsearchRepositoryFactoryBean}. + * Returns the {@link org.springframework.beans.factory.FactoryBean} class to be used for each repository instance. + * Defaults to {@link ElasticsearchRepositoryFactoryBean}. * * @return */ @@ -103,8 +105,8 @@ public @interface EnableElasticsearchRepositories { // Elasticsearch specific configuration /** - * Configures the name of the {@link ElasticsearchTemplate} bean definition to be used to create repositories discovered - * through this annotation. Defaults to {@code elasticsearchTemplate}. + * Configures the name of the {@link ElasticsearchTemplate} bean definition to be used to create repositories + * discovered through this annotation. Defaults to {@code elasticsearchTemplate}. * * @return */ diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/query/AbstractElasticsearchRepositoryQuery.java b/src/main/java/org/springframework/data/elasticsearch/repository/query/AbstractElasticsearchRepositoryQuery.java index bef4bbd39..c3c79eddf 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/query/AbstractElasticsearchRepositoryQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/query/AbstractElasticsearchRepositoryQuery.java @@ -21,24 +21,25 @@ import org.springframework.data.repository.query.RepositoryQuery; /** * AbstractElasticsearchRepositoryQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ public abstract class AbstractElasticsearchRepositoryQuery implements RepositoryQuery { - protected ElasticsearchQueryMethod queryMethod; - protected ElasticsearchOperations elasticsearchOperations; + protected ElasticsearchQueryMethod queryMethod; + protected ElasticsearchOperations elasticsearchOperations; - public AbstractElasticsearchRepositoryQuery(ElasticsearchQueryMethod queryMethod, ElasticsearchOperations elasticsearchOperations) { - this.queryMethod = queryMethod; - this.elasticsearchOperations = elasticsearchOperations; - } + public AbstractElasticsearchRepositoryQuery(ElasticsearchQueryMethod queryMethod, + ElasticsearchOperations elasticsearchOperations) { + this.queryMethod = queryMethod; + this.elasticsearchOperations = elasticsearchOperations; + } - @Override - public QueryMethod getQueryMethod() { - return queryMethod; - } + @Override + public QueryMethod getQueryMethod() { + return queryMethod; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchPartQuery.java b/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchPartQuery.java index 876968141..30c024543 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchPartQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchPartQuery.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.repository.query; - import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; import org.springframework.data.elasticsearch.core.query.CriteriaQuery; @@ -25,40 +24,39 @@ import org.springframework.data.repository.query.ParametersParameterAccessor; import org.springframework.data.repository.query.parser.PartTree; /** - * ElasticsearchPartQuery - * + * ElasticsearchPartQuery + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery{ +public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery { - private final PartTree tree; - private final MappingContext mappingContext; + private final PartTree tree; + private final MappingContext mappingContext; + public ElasticsearchPartQuery(ElasticsearchQueryMethod method, ElasticsearchOperations elasticsearchOperations) { + super(method, elasticsearchOperations); + this.tree = new PartTree(method.getName(), method.getEntityInformation().getJavaType()); + this.mappingContext = elasticsearchOperations.getElasticsearchConverter().getMappingContext(); + } - public ElasticsearchPartQuery(ElasticsearchQueryMethod method, ElasticsearchOperations elasticsearchOperations) { - super(method, elasticsearchOperations); - this.tree = new PartTree(method.getName(), method.getEntityInformation().getJavaType()); - this.mappingContext = elasticsearchOperations.getElasticsearchConverter().getMappingContext(); - } + @Override + public Object execute(Object[] parameters) { + ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters); + CriteriaQuery query = createQuery(accessor); + if (queryMethod.isPageQuery()) { + query.setPageable(accessor.getPageable()); + return elasticsearchOperations.queryForPage(query, queryMethod.getEntityInformation().getJavaType()); + } else if (queryMethod.isCollectionQuery()) { + if (accessor.getPageable() != null) { + query.setPageable(accessor.getPageable()); + } + return elasticsearchOperations.queryForList(query, queryMethod.getEntityInformation().getJavaType()); + } + return elasticsearchOperations.queryForObject(query, queryMethod.getEntityInformation().getJavaType()); + } - @Override - public Object execute(Object[] parameters) { - ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters); - CriteriaQuery query = createQuery(accessor); - if(queryMethod.isPageQuery()){ - query.setPageable(accessor.getPageable()); - return elasticsearchOperations.queryForPage(query, queryMethod.getEntityInformation().getJavaType()); - } else if (queryMethod.isCollectionQuery()) { - if(accessor.getPageable() != null){ - query.setPageable(accessor.getPageable()); - } - return elasticsearchOperations.queryForList(query,queryMethod.getEntityInformation().getJavaType()); - } - return elasticsearchOperations.queryForObject(query, queryMethod.getEntityInformation().getJavaType()); - } - - public CriteriaQuery createQuery(ParametersParameterAccessor accessor) { - return new ElasticsearchQueryCreator(tree, accessor, mappingContext).createQuery(); - } + public CriteriaQuery createQuery(ParametersParameterAccessor accessor) { + return new ElasticsearchQueryCreator(tree, accessor, mappingContext).createQuery(); + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchQueryMethod.java b/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchQueryMethod.java index ec63155c4..ffcd040de 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchQueryMethod.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchQueryMethod.java @@ -26,33 +26,35 @@ import org.springframework.util.StringUtils; import java.lang.reflect.Method; /** - * ElasticsearchQueryMethod - * + * ElasticsearchQueryMethod + * * @author Rizwan Idrees * @author Mohsin Husen */ public class ElasticsearchQueryMethod extends QueryMethod { - private final ElasticsearchEntityInformation entityInformation; - private Method method; + private final ElasticsearchEntityInformation entityInformation; + private Method method; - public ElasticsearchQueryMethod(Method method, RepositoryMetadata metadata, ElasticsearchEntityInformationCreator elasticsearchEntityInformationCreator) { - super(method, metadata); - this.entityInformation = elasticsearchEntityInformationCreator.getEntityInformation(metadata.getReturnedDomainClass(method)); - this.method = method; - } + public ElasticsearchQueryMethod(Method method, RepositoryMetadata metadata, + ElasticsearchEntityInformationCreator elasticsearchEntityInformationCreator) { + super(method, metadata); + this.entityInformation = elasticsearchEntityInformationCreator.getEntityInformation(metadata + .getReturnedDomainClass(method)); + this.method = method; + } - public boolean hasAnnotatedQuery() { - return getQueryAnnotation() != null; - } + public boolean hasAnnotatedQuery() { + return getQueryAnnotation() != null; + } - public String getAnnotatedQuery() { - String query = (String) AnnotationUtils.getValue(getQueryAnnotation(), "value"); - return StringUtils.hasText(query) ? query : null; - } + public String getAnnotatedQuery() { + String query = (String) AnnotationUtils.getValue(getQueryAnnotation(), "value"); + return StringUtils.hasText(query) ? query : null; + } - private Query getQueryAnnotation() { - return this.method.getAnnotation(Query.class); - } + private Query getQueryAnnotation() { + return this.method.getAnnotation(Query.class); + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchStringQuery.java b/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchStringQuery.java index 178c30d8b..cef6fbf38 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchStringQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/query/ElasticsearchStringQuery.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.repository.query; - import org.springframework.core.convert.support.GenericConversionService; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.convert.DateTimeConverters; @@ -28,78 +27,78 @@ import java.util.regex.Pattern; /** * ElasticsearchStringQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQuery{ +public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQuery { - private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)"); - private String query; + private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)"); + private String query; - private final GenericConversionService conversionService = new GenericConversionService(); + private final GenericConversionService conversionService = new GenericConversionService(); - { - if (!conversionService.canConvert(java.util.Date.class, String.class)) { - conversionService.addConverter(DateTimeConverters.JavaDateConverter.INSTANCE); - } - if (!conversionService.canConvert(org.joda.time.ReadableInstant.class, String.class)) { - conversionService.addConverter(DateTimeConverters.JodaDateTimeConverter.INSTANCE); - } - if (!conversionService.canConvert(org.joda.time.LocalDateTime.class, String.class)) { - conversionService.addConverter(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE); - } + { + if (!conversionService.canConvert(java.util.Date.class, String.class)) { + conversionService.addConverter(DateTimeConverters.JavaDateConverter.INSTANCE); + } + if (!conversionService.canConvert(org.joda.time.ReadableInstant.class, String.class)) { + conversionService.addConverter(DateTimeConverters.JodaDateTimeConverter.INSTANCE); + } + if (!conversionService.canConvert(org.joda.time.LocalDateTime.class, String.class)) { + conversionService.addConverter(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE); + } - } + } - public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod, ElasticsearchOperations elasticsearchOperations, String query) { - super(queryMethod, elasticsearchOperations); - Assert.notNull(query, "Query cannot be empty"); - this.query = query; - } + public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod, + ElasticsearchOperations elasticsearchOperations, String query) { + super(queryMethod, elasticsearchOperations); + Assert.notNull(query, "Query cannot be empty"); + this.query = query; + } - @Override - public Object execute(Object[] parameters) { - ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters); - StringQuery stringQuery = createQuery(accessor); - if(queryMethod.isPageQuery()){ - stringQuery.setPageable(accessor.getPageable()); - return elasticsearchOperations.queryForPage(stringQuery, queryMethod.getEntityInformation().getJavaType()); - } else if(queryMethod.isCollectionQuery()) { - if(accessor.getPageable() != null) { - stringQuery.setPageable(accessor.getPageable()); - } - return elasticsearchOperations.queryForList(stringQuery,queryMethod.getEntityInformation().getJavaType()); - } + @Override + public Object execute(Object[] parameters) { + ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters); + StringQuery stringQuery = createQuery(accessor); + if (queryMethod.isPageQuery()) { + stringQuery.setPageable(accessor.getPageable()); + return elasticsearchOperations.queryForPage(stringQuery, queryMethod.getEntityInformation().getJavaType()); + } else if (queryMethod.isCollectionQuery()) { + if (accessor.getPageable() != null) { + stringQuery.setPageable(accessor.getPageable()); + } + return elasticsearchOperations.queryForList(stringQuery, queryMethod.getEntityInformation().getJavaType()); + } - return elasticsearchOperations.queryForObject(stringQuery, queryMethod.getEntityInformation().getJavaType()); - } + return elasticsearchOperations.queryForObject(stringQuery, queryMethod.getEntityInformation().getJavaType()); + } + protected StringQuery createQuery(ParametersParameterAccessor parameterAccessor) { + String queryString = replacePlaceholders(this.query, parameterAccessor); + return new StringQuery(queryString); + } - protected StringQuery createQuery(ParametersParameterAccessor parameterAccessor) { - String queryString = replacePlaceholders(this.query, parameterAccessor); - return new StringQuery(queryString); - } + private String replacePlaceholders(String input, ParametersParameterAccessor accessor) { + Matcher matcher = PARAMETER_PLACEHOLDER.matcher(input); + String result = input; + while (matcher.find()) { + String group = matcher.group(); + int index = Integer.parseInt(matcher.group(1)); + result = result.replace(group, getParameterWithIndex(accessor, index)); + } + return result; + } - private String replacePlaceholders(String input, ParametersParameterAccessor accessor) { - Matcher matcher = PARAMETER_PLACEHOLDER.matcher(input); - String result = input; - while (matcher.find()) { - String group = matcher.group(); - int index = Integer.parseInt(matcher.group(1)); - result = result.replace(group, getParameterWithIndex(accessor, index)); - } - return result; - } - - private String getParameterWithIndex(ParametersParameterAccessor accessor, int index) { - Object parameter = accessor.getBindableValue(index); - if (parameter == null) { - return "null"; - } - if (conversionService.canConvert(parameter.getClass(), String.class)) { - return conversionService.convert(parameter, String.class); - } - return parameter.toString(); - } + private String getParameterWithIndex(ParametersParameterAccessor accessor, int index) { + Object parameter = accessor.getBindableValue(index); + if (parameter == null) { + return "null"; + } + if (conversionService.canConvert(parameter.getClass(), String.class)) { + return conversionService.convert(parameter, String.class); + } + return parameter.toString(); + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/query/parser/ElasticsearchQueryCreator.java b/src/main/java/org/springframework/data/elasticsearch/repository/query/parser/ElasticsearchQueryCreator.java index 3d9959a99..f068e86e6 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/query/parser/ElasticsearchQueryCreator.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/query/parser/ElasticsearchQueryCreator.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.repository.query.parser; - import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.domain.Sort; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; @@ -33,104 +32,106 @@ import java.util.Iterator; /** * ElasticsearchQueryCreator - * + * * @author Rizwan Idrees * @author Mohsin Husen */ -public class ElasticsearchQueryCreator extends AbstractQueryCreator{ +public class ElasticsearchQueryCreator extends AbstractQueryCreator { - private final MappingContext context; + private final MappingContext context; - public ElasticsearchQueryCreator(PartTree tree, ParameterAccessor parameters, MappingContext context) { - super(tree, parameters); - this.context = context; - } + public ElasticsearchQueryCreator(PartTree tree, ParameterAccessor parameters, + MappingContext context) { + super(tree, parameters); + this.context = context; + } - public ElasticsearchQueryCreator(PartTree tree, MappingContext context) { - super(tree); - this.context = context; - } + public ElasticsearchQueryCreator(PartTree tree, MappingContext context) { + super(tree); + this.context = context; + } - @Override - protected CriteriaQuery create(Part part, Iterator iterator) { - PersistentPropertyPath path = context.getPersistentPropertyPath(part.getProperty()); - return new CriteriaQuery(from(part.getType(), - new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator)); - } + @Override + protected CriteriaQuery create(Part part, Iterator iterator) { + PersistentPropertyPath path = context + .getPersistentPropertyPath(part.getProperty()); + return new CriteriaQuery(from(part.getType(), + new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator)); + } - @Override - protected CriteriaQuery and(Part part, CriteriaQuery base, Iterator iterator) { - if (base == null) { - return create(part, iterator); - } - PersistentPropertyPath path = context.getPersistentPropertyPath(part.getProperty()); - return base.addCriteria(from(part.getType(), - new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator)); - } + @Override + protected CriteriaQuery and(Part part, CriteriaQuery base, Iterator iterator) { + if (base == null) { + return create(part, iterator); + } + PersistentPropertyPath path = context + .getPersistentPropertyPath(part.getProperty()); + return base.addCriteria(from(part.getType(), + new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator)); + } - @Override - protected CriteriaQuery or(CriteriaQuery base, CriteriaQuery query) { - return new CriteriaQuery(base.getCriteria().or(query.getCriteria())); - } + @Override + protected CriteriaQuery or(CriteriaQuery base, CriteriaQuery query) { + return new CriteriaQuery(base.getCriteria().or(query.getCriteria())); + } - @Override - protected CriteriaQuery complete(CriteriaQuery query, Sort sort) { - if (query == null) { - return null; - } - return query.addSort(sort); - } + @Override + protected CriteriaQuery complete(CriteriaQuery query, Sort sort) { + if (query == null) { + return null; + } + return query.addSort(sort); + } + private Criteria from(Part.Type type, Criteria instance, Iterator parameters) { + Criteria criteria = instance; + if (criteria == null) { + criteria = new Criteria(); + } + switch (type) { + case TRUE: + return criteria.is(true); + case FALSE: + return criteria.is(false); + case SIMPLE_PROPERTY: + return criteria.is(parameters.next()); + case NEGATING_SIMPLE_PROPERTY: + return criteria.is(parameters.next()).not(); + case REGEX: + return criteria.expression(parameters.next().toString()); + case LIKE: + case STARTING_WITH: + return criteria.startsWith(parameters.next().toString()); + case ENDING_WITH: + return criteria.endsWith(parameters.next().toString()); + case CONTAINING: + return criteria.contains(parameters.next().toString()); + case AFTER: + case GREATER_THAN: + case GREATER_THAN_EQUAL: + return criteria.greaterThanEqual(parameters.next()); + case BEFORE: + case LESS_THAN: + case LESS_THAN_EQUAL: + return criteria.lessThanEqual(parameters.next()); + case BETWEEN: + return criteria.between(parameters.next(), parameters.next()); + case IN: + return criteria.in(asArray(parameters.next())); + case NOT_IN: + return criteria.in(asArray(parameters.next())).not(); + default: + throw new InvalidDataAccessApiUsageException("Illegal criteria found '" + type + "'."); + } + } - private Criteria from(Part.Type type, Criteria instance, Iterator parameters) { - Criteria criteria = instance; - if (criteria == null) { - criteria = new Criteria(); - } - switch (type) { - case TRUE: - return criteria.is(true); - case FALSE: - return criteria.is(false); - case SIMPLE_PROPERTY: - return criteria.is(parameters.next()); - case NEGATING_SIMPLE_PROPERTY: - return criteria.is(parameters.next()).not(); - case REGEX: - return criteria.expression(parameters.next().toString()); - case LIKE: - case STARTING_WITH: - return criteria.startsWith(parameters.next().toString()); - case ENDING_WITH: - return criteria.endsWith(parameters.next().toString()); - case CONTAINING: - return criteria.contains(parameters.next().toString()); - case AFTER: - case GREATER_THAN: - case GREATER_THAN_EQUAL: - return criteria.greaterThanEqual(parameters.next()); - case BEFORE: - case LESS_THAN: - case LESS_THAN_EQUAL: - return criteria.lessThanEqual(parameters.next()); - case BETWEEN: - return criteria.between(parameters.next(), parameters.next()); - case IN: - return criteria.in(asArray(parameters.next())); - case NOT_IN: - return criteria.in(asArray(parameters.next())).not(); - default: - throw new InvalidDataAccessApiUsageException("Illegal criteria found '" + type + "'."); - } - } - - private Object[] asArray(Object o) { - if (o instanceof Collection) { - return ((Collection) o).toArray(); - } else if (o.getClass().isArray()) { - return (Object[]) o; - } - return new Object[] { o }; - } + private Object[] asArray(Object o) { + if (o instanceof Collection) { + return ((Collection) o).toArray(); + } else if (o.getClass().isArray()) { + return (Object[]) o; + } + return new Object[] { o }; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/AbstractElasticsearchRepository.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/AbstractElasticsearchRepository.java index f75240c47..11f135a0d 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/AbstractElasticsearchRepository.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/AbstractElasticsearchRepository.java @@ -36,283 +36,273 @@ import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.springframework.data.elasticsearch.core.query.Query.DEFAULT_PAGE; /** - * Elasticsearch specific repository implementation. Likely to be used as target within {@link ElasticsearchRepositoryFactory} - * - * + * Elasticsearch specific repository implementation. Likely to be used as target within + * {@link ElasticsearchRepositoryFactory} + * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Ryan Henszey */ -public abstract class AbstractElasticsearchRepository implements ElasticsearchRepository { +public abstract class AbstractElasticsearchRepository implements + ElasticsearchRepository { + protected ElasticsearchOperations elasticsearchOperations; + protected Class entityClass; + protected ElasticsearchEntityInformation entityInformation; - protected ElasticsearchOperations elasticsearchOperations; - protected Class entityClass; - protected ElasticsearchEntityInformation entityInformation; + public AbstractElasticsearchRepository() { + } - public AbstractElasticsearchRepository() { - } + public AbstractElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) { + Assert.notNull(elasticsearchOperations); + this.setElasticsearchOperations(elasticsearchOperations); + } - public AbstractElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) { - Assert.notNull(elasticsearchOperations); - this.setElasticsearchOperations(elasticsearchOperations); - } + public AbstractElasticsearchRepository(ElasticsearchEntityInformation metadata, + ElasticsearchOperations elasticsearchOperations) { + this(elasticsearchOperations); + Assert.notNull(metadata); + this.entityInformation = metadata; + setEntityClass(this.entityInformation.getJavaType()); + createIndex(); + putMapping(); + } - public AbstractElasticsearchRepository(ElasticsearchEntityInformation metadata, ElasticsearchOperations elasticsearchOperations) { - this(elasticsearchOperations); - Assert.notNull(metadata); - this.entityInformation = metadata; - setEntityClass(this.entityInformation.getJavaType()); - createIndex(); - putMapping(); - } + private void createIndex() { + elasticsearchOperations.createIndex(getEntityClass()); + } - private void createIndex(){ - elasticsearchOperations.createIndex(getEntityClass()); - } + private void putMapping() { + elasticsearchOperations.putMapping(getEntityClass()); + } - private void putMapping(){ - elasticsearchOperations.putMapping(getEntityClass()); - } + @Override + public T findOne(ID id) { + GetQuery query = new GetQuery(); + query.setId(stringIdRepresentation(id)); + return elasticsearchOperations.queryForObject(query, getEntityClass()); + } - @Override - public T findOne(ID id) { - GetQuery query = new GetQuery(); - query.setId(stringIdRepresentation(id)); - return elasticsearchOperations.queryForObject(query, getEntityClass()); - } + @Override + public Iterable findAll() { + int itemCount = (int) this.count(); + if (itemCount == 0) { + return new PageImpl(Collections. emptyList()); + } + return this.findAll(new PageRequest(0, Math.max(1, itemCount))); + } - @Override - public Iterable findAll() { - int itemCount = (int) this.count(); - if (itemCount == 0) { - return new PageImpl(Collections. emptyList()); - } - return this.findAll(new PageRequest(0, Math.max(1, itemCount))); - } + @Override + public Page findAll(Pageable pageable) { + SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withPageable(pageable).build(); + return elasticsearchOperations.queryForPage(query, getEntityClass()); + } - @Override - public Page findAll(Pageable pageable) { - SearchQuery query = new NativeSearchQueryBuilder() - .withQuery(matchAllQuery()) - .withPageable(pageable) - .build(); - return elasticsearchOperations.queryForPage(query, getEntityClass()); - } + @Override + public Iterable findAll(Sort sort) { + int itemCount = (int) this.count(); + if (itemCount == 0) { + return new PageImpl(Collections. emptyList()); + } + SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withPageable(new PageRequest(0, itemCount, sort)).build(); + return elasticsearchOperations.queryForPage(query, getEntityClass()); + } - @Override - public Iterable findAll(Sort sort) { - int itemCount = (int) this.count(); - if (itemCount == 0) { - return new PageImpl(Collections. emptyList()); - } - SearchQuery query = new NativeSearchQueryBuilder() - .withQuery(matchAllQuery()) - .withPageable(new PageRequest(0,itemCount, sort)) - .build(); - return elasticsearchOperations.queryForPage(query, getEntityClass()); - } + @Override + public Iterable findAll(Iterable ids) { + SearchQuery query = new NativeSearchQueryBuilder().withQuery(inQuery(entityInformation.getIdAttribute(), ids)) + .build(); + return elasticsearchOperations.queryForPage(query, getEntityClass()); + } - @Override - public Iterable findAll(Iterable ids) { - SearchQuery query = new NativeSearchQueryBuilder() - .withQuery(inQuery(entityInformation.getIdAttribute(), ids)) - .build(); - return elasticsearchOperations.queryForPage(query, getEntityClass()); - } + @Override + public long count() { + SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); + return elasticsearchOperations.count(query, getEntityClass()); + } - @Override - public long count() { - SearchQuery query = new NativeSearchQueryBuilder() - .withQuery(matchAllQuery()).build(); - return elasticsearchOperations.count(query,getEntityClass()); - } + @Override + public S save(S entity) { + Assert.notNull(entity, "Cannot save 'null' entity."); + elasticsearchOperations.index(createIndexQuery(entity)); + elasticsearchOperations.refresh(entityInformation.getIndexName(), true); + return entity; + } - @Override - public S save(S entity) { - Assert.notNull(entity, "Cannot save 'null' entity."); - elasticsearchOperations.index(createIndexQuery(entity)); - elasticsearchOperations.refresh(entityInformation.getIndexName(), true); - return entity; - } + public List save(List entities) { + Assert.notNull(entities, "Cannot insert 'null' as a List."); + Assert.notEmpty(entities, "Cannot insert empty List."); + List queries = new ArrayList(); + for (S s : entities) { + queries.add(createIndexQuery(s)); + } + elasticsearchOperations.bulkIndex(queries); + elasticsearchOperations.refresh(entityInformation.getIndexName(), true); + return entities; + } - public List save(List entities) { - Assert.notNull(entities, "Cannot insert 'null' as a List."); - Assert.notEmpty(entities,"Cannot insert empty List."); - List queries = new ArrayList(); - for(S s:entities){ - queries.add(createIndexQuery(s)); - } - elasticsearchOperations.bulkIndex(queries); - elasticsearchOperations.refresh(entityInformation.getIndexName(), true); - return entities; - } + @Override + public S index(S entity) { + return save(entity); + } - @Override - public S index(S entity) { - return save(entity); - } + @Override + public Iterable save(Iterable entities) { + Assert.notNull(entities, "Cannot insert 'null' as a List."); + if (!(entities instanceof Collection)) { + throw new InvalidDataAccessApiUsageException("Entities have to be inside a collection"); + } + List queries = new ArrayList(); + for (S s : entities) { + queries.add(createIndexQuery(s)); + } + elasticsearchOperations.bulkIndex(queries); + elasticsearchOperations.refresh(entityInformation.getIndexName(), true); + return entities; + } - @Override - public Iterable save(Iterable entities) { - Assert.notNull(entities, "Cannot insert 'null' as a List."); - if (!(entities instanceof Collection)) { - throw new InvalidDataAccessApiUsageException("Entities have to be inside a collection"); - } - List queries = new ArrayList(); - for(S s: entities){ - queries.add(createIndexQuery(s)); - } - elasticsearchOperations.bulkIndex(queries); - elasticsearchOperations.refresh(entityInformation.getIndexName(), true); - return entities; - } + @Override + public boolean exists(ID id) { + return findOne(id) != null; + } - @Override - public boolean exists(ID id) { - return findOne(id) != null; - } + @Override + public Iterable search(QueryBuilder query) { + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).build(); + int count = (int) elasticsearchOperations.count(searchQuery, getEntityClass()); + if (count == 0) { + return new PageImpl(Collections. emptyList()); + } + searchQuery.setPageable(new PageRequest(0, count)); + return elasticsearchOperations.queryForPage(searchQuery, getEntityClass()); + } - @Override - public Iterable search(QueryBuilder query) { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(query).build(); - int count = (int) elasticsearchOperations.count(searchQuery, getEntityClass()); - if(count == 0){ - return new PageImpl(Collections.emptyList()); - } - searchQuery.setPageable(new PageRequest(0, count)); - return elasticsearchOperations.queryForPage(searchQuery, getEntityClass()); - } + @Override + public Page search(QueryBuilder query, Pageable pageable) { + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).withPageable(pageable).build(); + return elasticsearchOperations.queryForPage(searchQuery, getEntityClass()); + } - @Override - public Page search(QueryBuilder query, Pageable pageable) { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(query) - .withPageable(pageable) - .build(); - return elasticsearchOperations.queryForPage(searchQuery, getEntityClass()); - } + @Override + public Page search(SearchQuery query) { + return elasticsearchOperations.queryForPage(query, getEntityClass()); + } - @Override - public Page search(SearchQuery query){ - return elasticsearchOperations.queryForPage(query, getEntityClass()); - } + @Override + public Page searchSimilar(T entity, SearchQuery searchQuery) { + Assert.notNull(entity, "Cannot search similar records for 'null'."); + Assert.notNull(searchQuery.getFields(), "Fields cannot be 'null'"); + MoreLikeThisQuery query = new MoreLikeThisQuery(); + query.setId(stringIdRepresentation(extractIdFromBean(entity))); + query.setPageable(searchQuery.getPageable() != null ? searchQuery.getPageable() : DEFAULT_PAGE); + query.addFields(searchQuery.getFields().toArray(new String[searchQuery.getFields().size()])); + if (!searchQuery.getIndices().isEmpty()) { + query.addSearchIndices(searchQuery.getIndices().toArray(new String[searchQuery.getIndices().size()])); + } + if (!searchQuery.getTypes().isEmpty()) { + query.addSearchTypes(searchQuery.getTypes().toArray(new String[searchQuery.getTypes().size()])); + } + return elasticsearchOperations.moreLikeThis(query, getEntityClass()); + } - @Override - public Page searchSimilar(T entity, SearchQuery searchQuery) { - Assert.notNull(entity, "Cannot search similar records for 'null'."); - Assert.notNull(searchQuery.getFields(), "Fields cannot be 'null'"); - MoreLikeThisQuery query = new MoreLikeThisQuery(); - query.setId(stringIdRepresentation(extractIdFromBean(entity))); - query.setPageable(searchQuery.getPageable() != null ? searchQuery.getPageable() : DEFAULT_PAGE); - query.addFields(searchQuery.getFields().toArray(new String[searchQuery.getFields().size()])); - if(!searchQuery.getIndices().isEmpty()) { - query.addSearchIndices(searchQuery.getIndices().toArray(new String[searchQuery.getIndices().size()])); - } - if(!searchQuery.getTypes().isEmpty()){ - query.addSearchTypes(searchQuery.getTypes().toArray(new String[searchQuery.getTypes().size()])); - } - return elasticsearchOperations.moreLikeThis(query, getEntityClass()); - } + @Override + public void delete(ID id) { + Assert.notNull(id, "Cannot delete entity with id 'null'."); + elasticsearchOperations.delete(entityInformation.getIndexName(), entityInformation.getType(), + stringIdRepresentation(id)); + elasticsearchOperations.refresh(entityInformation.getIndexName(), true); + } + @Override + public void delete(T entity) { + Assert.notNull(entity, "Cannot delete 'null' entity."); + delete(extractIdFromBean(entity)); + elasticsearchOperations.refresh(entityInformation.getIndexName(), true); + } - @Override - public void delete(ID id) { - Assert.notNull(id, "Cannot delete entity with id 'null'."); - elasticsearchOperations.delete(entityInformation.getIndexName(), entityInformation.getType(),stringIdRepresentation(id)); - elasticsearchOperations.refresh(entityInformation.getIndexName(),true); - } + @Override + public void delete(Iterable entities) { + Assert.notNull(entities, "Cannot delete 'null' list."); + for (T entity : entities) { + delete(entity); + } + } - @Override - public void delete(T entity) { - Assert.notNull(entity, "Cannot delete 'null' entity."); - delete(extractIdFromBean(entity)); - elasticsearchOperations.refresh(entityInformation.getIndexName(), true); - } + @Override + public void deleteAll() { + DeleteQuery deleteQuery = new DeleteQuery(); + deleteQuery.setQuery(matchAllQuery()); + elasticsearchOperations.delete(deleteQuery, getEntityClass()); + elasticsearchOperations.refresh(entityInformation.getIndexName(), true); + } - @Override - public void delete(Iterable entities) { - Assert.notNull(entities, "Cannot delete 'null' list."); - for (T entity : entities) { - delete(entity); - } - } + private IndexQuery createIndexQuery(T entity) { + IndexQuery query = new IndexQuery(); + query.setObject(entity); + query.setId(stringIdRepresentation(extractIdFromBean(entity))); + query.setVersion(extractVersionFromBean(entity)); + return query; + } - @Override - public void deleteAll() { - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(matchAllQuery()); - elasticsearchOperations.delete(deleteQuery, getEntityClass()); - elasticsearchOperations.refresh(entityInformation.getIndexName(),true); - } + @SuppressWarnings("unchecked") + private Class resolveReturnedClassFromGenericType() { + ParameterizedType parameterizedType = resolveReturnedClassFromGenericType(getClass()); + return (Class) parameterizedType.getActualTypeArguments()[0]; + } - private IndexQuery createIndexQuery(T entity){ - IndexQuery query = new IndexQuery(); - query.setObject(entity); - query.setId(stringIdRepresentation(extractIdFromBean(entity))); - query.setVersion(extractVersionFromBean(entity)); - return query; - } + private ParameterizedType resolveReturnedClassFromGenericType(Class clazz) { + Object genericSuperclass = clazz.getGenericSuperclass(); + if (genericSuperclass instanceof ParameterizedType) { + ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; + Type rawtype = parameterizedType.getRawType(); + if (SimpleElasticsearchRepository.class.equals(rawtype)) { + return parameterizedType; + } + } + return resolveReturnedClassFromGenericType(clazz.getSuperclass()); + } - @SuppressWarnings("unchecked") - private Class resolveReturnedClassFromGenericType() { - ParameterizedType parameterizedType = resolveReturnedClassFromGenericType(getClass()); - return (Class) parameterizedType.getActualTypeArguments()[0]; - } + public Class getEntityClass() { + if (!isEntityClassSet()) { + try { + this.entityClass = resolveReturnedClassFromGenericType(); + } catch (Exception e) { + throw new InvalidDataAccessApiUsageException("Unable to resolve EntityClass. Please use according setter!", e); + } + } + return entityClass; + } - private ParameterizedType resolveReturnedClassFromGenericType(Class clazz) { - Object genericSuperclass = clazz.getGenericSuperclass(); - if (genericSuperclass instanceof ParameterizedType) { - ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass; - Type rawtype = parameterizedType.getRawType(); - if (SimpleElasticsearchRepository.class.equals(rawtype)) { - return parameterizedType; - } - } - return resolveReturnedClassFromGenericType(clazz.getSuperclass()); - } + private boolean isEntityClassSet() { + return entityClass != null; + } - public Class getEntityClass() { - if (!isEntityClassSet()) { - try { - this.entityClass = resolveReturnedClassFromGenericType(); - } catch (Exception e) { - throw new InvalidDataAccessApiUsageException("Unable to resolve EntityClass. Please use according setter!", e); - } - } - return entityClass; - } + public final void setEntityClass(Class entityClass) { + Assert.notNull(entityClass, "EntityClass must not be null."); + this.entityClass = entityClass; + } - private boolean isEntityClassSet() { - return entityClass != null; - } + public final void setElasticsearchOperations(ElasticsearchOperations elasticsearchOperations) { + Assert.notNull(elasticsearchOperations, "ElasticsearchOperations must not be null."); + this.elasticsearchOperations = elasticsearchOperations; + } - public final void setEntityClass(Class entityClass) { - Assert.notNull(entityClass, "EntityClass must not be null."); - this.entityClass = entityClass; - } + protected ID extractIdFromBean(T entity) { + if (entityInformation != null) { + return entityInformation.getId(entity); + } + return null; + } - public final void setElasticsearchOperations(ElasticsearchOperations elasticsearchOperations) { - Assert.notNull(elasticsearchOperations, "ElasticsearchOperations must not be null."); - this.elasticsearchOperations = elasticsearchOperations; - } + protected abstract String stringIdRepresentation(ID id); - - protected ID extractIdFromBean(T entity) { - if (entityInformation != null) { - return entityInformation.getId(entity); - } - return null; - } - - protected abstract String stringIdRepresentation(ID id); - - private Long extractVersionFromBean(T entity){ - if (entityInformation != null) { - return entityInformation.getVersion(entity); - } - return null; - } + private Long extractVersionFromBean(T entity) { + if (entityInformation != null) { + return entityInformation.getVersion(entity); + } + return null; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformation.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformation.java index 9289223ac..f643e46c1 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformation.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformation.java @@ -22,14 +22,17 @@ import java.io.Serializable; /** * @param * @param - * + * * @author Rizwan Idrees * @author Mohsin Husen */ public interface ElasticsearchEntityInformation extends EntityInformation { String getIdAttribute(); - String getIndexName(); - String getType(); - Long getVersion(T entity); + + String getIndexName(); + + String getType(); + + Long getVersion(T entity); } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformationCreator.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformationCreator.java index 02b3f6e3a..c69051c5c 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformationCreator.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformationCreator.java @@ -18,8 +18,8 @@ package org.springframework.data.elasticsearch.repository.support; import java.io.Serializable; /** - * ElasticsearchEntityInformationCreator - * + * ElasticsearchEntityInformationCreator + * * @author Rizwan Idrees * @author Mohsin Husen */ diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformationCreatorImpl.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformationCreatorImpl.java index 875b0d1f2..07e7f3489 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformationCreatorImpl.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchEntityInformationCreatorImpl.java @@ -24,7 +24,7 @@ import java.io.Serializable; /** * ElasticsearchEntityInformationCreatorImpl - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -33,7 +33,7 @@ public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchE private final MappingContext, ElasticsearchPersistentProperty> mappingContext; public ElasticsearchEntityInformationCreatorImpl( - MappingContext, ElasticsearchPersistentProperty> mappingContext) { + MappingContext, ElasticsearchPersistentProperty> mappingContext) { Assert.notNull(mappingContext); this.mappingContext = mappingContext; } @@ -41,7 +41,7 @@ public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchE @Override @SuppressWarnings("unchecked") public ElasticsearchEntityInformation getEntityInformation(Class domainClass) { - ElasticsearchPersistentEntity persistentEntity = (ElasticsearchPersistentEntity) mappingContext + ElasticsearchPersistentEntity persistentEntity = (ElasticsearchPersistentEntity) mappingContext .getPersistentEntity(domainClass); return new MappingElasticsearchEntityInformation(persistentEntity); } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactory.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactory.java index d6451e023..b98350ecf 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactory.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactory.java @@ -35,90 +35,87 @@ import org.springframework.util.Assert; /** * Factory to create {@link ElasticsearchRepository} - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Ryan Henszey */ public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport { - - private final ElasticsearchOperations elasticsearchOperations; - private final ElasticsearchEntityInformationCreator entityInformationCreator; + private final ElasticsearchOperations elasticsearchOperations; + private final ElasticsearchEntityInformationCreator entityInformationCreator; - public ElasticsearchRepositoryFactory(ElasticsearchOperations elasticsearchOperations) { - Assert.notNull(elasticsearchOperations); - this.elasticsearchOperations = elasticsearchOperations; - this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(elasticsearchOperations.getElasticsearchConverter() - .getMappingContext()); - } + public ElasticsearchRepositoryFactory(ElasticsearchOperations elasticsearchOperations) { + Assert.notNull(elasticsearchOperations); + this.elasticsearchOperations = elasticsearchOperations; + this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(elasticsearchOperations + .getElasticsearchConverter().getMappingContext()); + } - @Override - public ElasticsearchEntityInformation getEntityInformation(Class domainClass) { - return entityInformationCreator.getEntityInformation(domainClass); - } + @Override + public ElasticsearchEntityInformation getEntityInformation(Class domainClass) { + return entityInformationCreator.getEntityInformation(domainClass); + } - @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) - protected Object getTargetRepository(RepositoryMetadata metadata) { - - ElasticsearchEntityInformation entityInformation = getEntityInformation(metadata.getDomainType()); - - AbstractElasticsearchRepository repository; - - //Probably a better way to store and look these up. - if(Integer.class.isAssignableFrom(entityInformation.getIdType()) || - Long.class.isAssignableFrom(entityInformation.getIdType()) || - Double.class.isAssignableFrom(entityInformation.getIdType())){ - //logger.debug("Using NumberKeyedRepository for " + metadata.getRepositoryInterface()); - repository = new NumberKeyedRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations); - } - else if (entityInformation.getIdType() == String.class){ - //logger.debug("Using SimpleElasticsearchRepository for " + metadata.getRepositoryInterface()); - repository = new SimpleElasticsearchRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations); - } - else { - throw new IllegalArgumentException("Unsuppored ID type " + entityInformation.getIdType()); - } - repository.setEntityClass(metadata.getDomainType()); - - return repository; - } + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected Object getTargetRepository(RepositoryMetadata metadata) { - @Override - protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { - if (isQueryDslRepository(metadata.getRepositoryInterface())) { - throw new IllegalArgumentException("QueryDsl Support has not been implemented yet."); - } - return SimpleElasticsearchRepository.class; - } + ElasticsearchEntityInformation entityInformation = getEntityInformation(metadata.getDomainType()); - private static boolean isQueryDslRepository(Class repositoryInterface) { - return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface); - } + AbstractElasticsearchRepository repository; - @Override - protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key) { - return new ElasticsearchQueryLookupStrategy(); - } + // Probably a better way to store and look these up. + if (Integer.class.isAssignableFrom(entityInformation.getIdType()) + || Long.class.isAssignableFrom(entityInformation.getIdType()) + || Double.class.isAssignableFrom(entityInformation.getIdType())) { + // logger.debug("Using NumberKeyedRepository for " + metadata.getRepositoryInterface()); + repository = new NumberKeyedRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations); + } else if (entityInformation.getIdType() == String.class) { + // logger.debug("Using SimpleElasticsearchRepository for " + metadata.getRepositoryInterface()); + repository = new SimpleElasticsearchRepository(getEntityInformation(metadata.getDomainType()), + elasticsearchOperations); + } else { + throw new IllegalArgumentException("Unsuppored ID type " + entityInformation.getIdType()); + } + repository.setEntityClass(metadata.getDomainType()); - private class ElasticsearchQueryLookupStrategy implements QueryLookupStrategy { + return repository; + } - @Override - public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, NamedQueries namedQueries) { + @Override + protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { + if (isQueryDslRepository(metadata.getRepositoryInterface())) { + throw new IllegalArgumentException("QueryDsl Support has not been implemented yet."); + } + return SimpleElasticsearchRepository.class; + } - ElasticsearchQueryMethod queryMethod = new ElasticsearchQueryMethod(method, metadata, entityInformationCreator); - String namedQueryName = queryMethod.getNamedQueryName(); + private static boolean isQueryDslRepository(Class repositoryInterface) { + return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface); + } - if (namedQueries.hasQuery(namedQueryName)) { - String namedQuery = namedQueries.getQuery(namedQueryName); - return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, namedQuery); - } - else if (queryMethod.hasAnnotatedQuery()) { - return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, queryMethod.getAnnotatedQuery()); - } - return new ElasticsearchPartQuery(queryMethod, elasticsearchOperations); - } - } + @Override + protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key) { + return new ElasticsearchQueryLookupStrategy(); + } + + private class ElasticsearchQueryLookupStrategy implements QueryLookupStrategy { + + @Override + public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, NamedQueries namedQueries) { + + ElasticsearchQueryMethod queryMethod = new ElasticsearchQueryMethod(method, metadata, entityInformationCreator); + String namedQueryName = queryMethod.getNamedQueryName(); + + if (namedQueries.hasQuery(namedQueryName)) { + String namedQuery = namedQueries.getQuery(namedQueryName); + return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, namedQuery); + } else if (queryMethod.hasAnnotatedQuery()) { + return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, queryMethod.getAnnotatedQuery()); + } + return new ElasticsearchPartQuery(queryMethod, elasticsearchOperations); + } + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactoryBean.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactoryBean.java index 5fb11f26a..538a831ec 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactoryBean.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/ElasticsearchRepositoryFactoryBean.java @@ -24,13 +24,14 @@ import org.springframework.util.Assert; import java.io.Serializable; /** - * Spring {@link org.springframework.beans.factory.FactoryBean} implementation to ease container based configuration for XML namespace and JavaConfig. - * + * Spring {@link org.springframework.beans.factory.FactoryBean} implementation to ease container based configuration for + * XML namespace and JavaConfig. + * * @author Rizwan Idrees * @author Mohsin Husen */ public class ElasticsearchRepositoryFactoryBean, S, ID extends Serializable> extends - RepositoryFactoryBeanSupport { + RepositoryFactoryBeanSupport { private ElasticsearchOperations operations; @@ -50,14 +51,13 @@ public class ElasticsearchRepositoryFactoryBean, S, */ @Override public void afterPropertiesSet() { - super.afterPropertiesSet(); + super.afterPropertiesSet(); Assert.notNull(operations, "ElasticsearchOperations must be configured!"); } - - @Override - protected RepositoryFactorySupport createRepositoryFactory() { - return new ElasticsearchRepositoryFactory(operations); - } + @Override + protected RepositoryFactorySupport createRepositoryFactory() { + return new ElasticsearchRepositoryFactory(operations); + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/MappingElasticsearchEntityInformation.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/MappingElasticsearchEntityInformation.java index 1e67a33d4..47f5d0693 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/MappingElasticsearchEntityInformation.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/MappingElasticsearchEntityInformation.java @@ -26,81 +26,82 @@ import org.springframework.data.repository.core.support.AbstractEntityInformatio import org.springframework.util.Assert; /** - * Elasticsearch specific implementation of {@link org.springframework.data.repository.core.support.AbstractEntityInformation} - * + * Elasticsearch specific implementation of + * {@link org.springframework.data.repository.core.support.AbstractEntityInformation} + * * @param * @param - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Ryan Henszey */ public class MappingElasticsearchEntityInformation extends AbstractEntityInformation - implements ElasticsearchEntityInformation { + implements ElasticsearchEntityInformation { - private static final Logger logger = LoggerFactory.getLogger(MappingElasticsearchEntityInformation.class); - private final ElasticsearchPersistentEntity entityMetadata; - private final String indexName; - private final String type; - private Class idClass; + private static final Logger logger = LoggerFactory.getLogger(MappingElasticsearchEntityInformation.class); + private final ElasticsearchPersistentEntity entityMetadata; + private final String indexName; + private final String type; + private Class idClass; - public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity entity) { - this(entity, null, null); - } + public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity entity) { + this(entity, null, null); + } - public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity entity, String indexName, String type) { - super(entity.getType()); - this.entityMetadata = entity; - this.indexName = indexName; - this.type = type; - this.idClass = entity.getIdProperty().getType(); - } + public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity entity, String indexName, String type) { + super(entity.getType()); + this.entityMetadata = entity; + this.indexName = indexName; + this.type = type; + this.idClass = entity.getIdProperty().getType(); + } - @SuppressWarnings("unchecked") - @Override - public ID getId(T entity) { - ElasticsearchPersistentProperty id = entityMetadata.getIdProperty(); - try { - return (ID) BeanWrapper.create(entity, null).getProperty(id); - } catch (Exception e) { - throw new IllegalStateException("ID could not be resolved", e); - } - } + @SuppressWarnings("unchecked") + @Override + public ID getId(T entity) { + ElasticsearchPersistentProperty id = entityMetadata.getIdProperty(); + try { + return (ID) BeanWrapper.create(entity, null).getProperty(id); + } catch (Exception e) { + throw new IllegalStateException("ID could not be resolved", e); + } + } - @SuppressWarnings("unchecked") - @Override - public Class getIdType() { - return (Class)idClass; - } + @SuppressWarnings("unchecked") + @Override + public Class getIdType() { + return (Class) idClass; + } - @Override - public String getIdAttribute() { - Assert.notNull(entityMetadata.getIdProperty(),"Unable to identify 'id' property in class " + entityMetadata.getType().getSimpleName() +". Make sure the 'id' property is annotated with @Id or named as 'id' or 'documentId' "); - return entityMetadata.getIdProperty().getFieldName(); - } + @Override + public String getIdAttribute() { + Assert.notNull(entityMetadata.getIdProperty(), "Unable to identify 'id' property in class " + + entityMetadata.getType().getSimpleName() + + ". Make sure the 'id' property is annotated with @Id or named as 'id' or 'documentId' "); + return entityMetadata.getIdProperty().getFieldName(); + } - @Override - public String getIndexName() { - return indexName != null? indexName : entityMetadata.getIndexName(); - } + @Override + public String getIndexName() { + return indexName != null ? indexName : entityMetadata.getIndexName(); + } - @Override - public String getType() { - return type != null? type : entityMetadata.getIndexType(); - } + @Override + public String getType() { + return type != null ? type : entityMetadata.getIndexType(); + } - @Override - public Long getVersion(T entity) { - ElasticsearchPersistentProperty versionProperty = entityMetadata.getVersionProperty(); - try { - if(versionProperty != null){ - return (Long) BeanWrapper.create(entity, null).getProperty(versionProperty); - } - } catch (Exception e) { - throw new IllegalStateException("failed to load version field", e); - } - return null; - } + @Override + public Long getVersion(T entity) { + ElasticsearchPersistentProperty versionProperty = entityMetadata.getVersionProperty(); + try { + if (versionProperty != null) { + return (Long) BeanWrapper.create(entity, null).getProperty(versionProperty); + } + } catch (Exception e) { + throw new IllegalStateException("failed to load version field", e); + } + return null; + } } - - diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/NumberKeyedRepository.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/NumberKeyedRepository.java index 73bb58813..2cc8aa3b7 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/NumberKeyedRepository.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/NumberKeyedRepository.java @@ -18,34 +18,32 @@ package org.springframework.data.elasticsearch.repository.support; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; /** - * Elasticsearch specific repository implementation. Likely to be used as target within {@link ElasticsearchRepositoryFactory} - * - * + * Elasticsearch specific repository implementation. Likely to be used as target within + * {@link ElasticsearchRepositoryFactory} + * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Ryan Henszey */ -public class NumberKeyedRepository extends AbstractElasticsearchRepository { +public class NumberKeyedRepository extends AbstractElasticsearchRepository { - - public NumberKeyedRepository() { - super(); - } + public NumberKeyedRepository() { + super(); + } - public NumberKeyedRepository(ElasticsearchEntityInformation metadata,ElasticsearchOperations elasticsearchOperations) { - super(metadata, elasticsearchOperations); - } + public NumberKeyedRepository(ElasticsearchEntityInformation metadata, + ElasticsearchOperations elasticsearchOperations) { + super(metadata, elasticsearchOperations); + } - public NumberKeyedRepository(ElasticsearchOperations elasticsearchOperations) { - super(elasticsearchOperations); - } - - - - @Override - protected String stringIdRepresentation(ID id) { - return String.valueOf(id); - } - + public NumberKeyedRepository(ElasticsearchOperations elasticsearchOperations) { + super(elasticsearchOperations); + } + + @Override + protected String stringIdRepresentation(ID id) { + return String.valueOf(id); + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepository.java b/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepository.java index a5d37c049..41e32ca22 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepository.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepository.java @@ -18,30 +18,32 @@ package org.springframework.data.elasticsearch.repository.support; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; /** - * Elasticsearch specific repository implementation. Likely to be used as target within {@link ElasticsearchRepositoryFactory} - * - * + * Elasticsearch specific repository implementation. Likely to be used as target within + * {@link ElasticsearchRepositoryFactory} + * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Ryan Henszey */ -public class SimpleElasticsearchRepository extends AbstractElasticsearchRepository { - - public SimpleElasticsearchRepository() { - super(); - } +public class SimpleElasticsearchRepository extends AbstractElasticsearchRepository { - public SimpleElasticsearchRepository(ElasticsearchEntityInformation metadata,ElasticsearchOperations elasticsearchOperations) { - super(metadata, elasticsearchOperations); - } + public SimpleElasticsearchRepository() { + super(); + } - public SimpleElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) { - super(elasticsearchOperations); - } + public SimpleElasticsearchRepository(ElasticsearchEntityInformation metadata, + ElasticsearchOperations elasticsearchOperations) { + super(metadata, elasticsearchOperations); + } - @Override - protected String stringIdRepresentation(String id) { - return id; - } + public SimpleElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) { + super(elasticsearchOperations); + } + + @Override + protected String stringIdRepresentation(String id) { + return id; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/Author.java b/src/test/java/org/springframework/data/elasticsearch/Author.java index f476fe58b..2df1d1c04 100644 --- a/src/test/java/org/springframework/data/elasticsearch/Author.java +++ b/src/test/java/org/springframework/data/elasticsearch/Author.java @@ -14,28 +14,29 @@ * limitations under the License. */ package org.springframework.data.elasticsearch; + /** * @author Rizwan Idrees * @author Mohsin Husen */ public class Author { - private String id; - private String name; + private String id; + private String name; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/Book.java b/src/test/java/org/springframework/data/elasticsearch/Book.java index f35f436ef..fad247f40 100644 --- a/src/test/java/org/springframework/data/elasticsearch/Book.java +++ b/src/test/java/org/springframework/data/elasticsearch/Book.java @@ -17,39 +17,40 @@ package org.springframework.data.elasticsearch; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; + /** * @author Rizwan Idrees * @author Mohsin Husen */ -@Document(indexName = "book",type = "book", indexStoreType = "memory", shards = 1 , replicas = 0, refreshInterval = "-1" ) +@Document(indexName = "book", type = "book", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class Book { - @Id - private String id; - private String name; - private Author author; + @Id + private String id; + private String name; + private Author author; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Author getAuthor() { - return author; - } + public Author getAuthor() { + return author; + } - public void setAuthor(Author author) { - this.author = author; - } + public void setAuthor(Author author) { + this.author = author; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/DoubleIDEntity.java b/src/test/java/org/springframework/data/elasticsearch/DoubleIDEntity.java index 5ac691656..3955b38db 100644 --- a/src/test/java/org/springframework/data/elasticsearch/DoubleIDEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/DoubleIDEntity.java @@ -24,48 +24,46 @@ import org.springframework.data.elasticsearch.annotations.Document; * @author Mohsin Husen */ -@Document(indexName = "double-keyed-entity", type = "double-keyed-entity", indexStoreType = "memory", shards = 1 , replicas = 0, refreshInterval = "-1") +@Document(indexName = "double-keyed-entity", type = "double-keyed-entity", indexStoreType = "memory", 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; - } + @Id + private Double id; + private String type; + private String message; + @Version + private Long version; - public Long getVersion() { - return 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; + } - public void setVersion(Long version) { - this.version = version; - } - - - } diff --git a/src/test/java/org/springframework/data/elasticsearch/IntegerIDEntity.java b/src/test/java/org/springframework/data/elasticsearch/IntegerIDEntity.java index 11996c7f3..9b9206093 100644 --- a/src/test/java/org/springframework/data/elasticsearch/IntegerIDEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/IntegerIDEntity.java @@ -24,49 +24,46 @@ import org.springframework.data.elasticsearch.annotations.Document; * @author Mohsin Husen */ -@Document(indexName = "integer-keyed-entity", type = "integer-keyed-entity", indexStoreType = "memory", shards = 1 , replicas = 0, refreshInterval = "-1") +@Document(indexName = "integer-keyed-entity", type = "integer-keyed-entity", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class IntegerIDEntity { + @Id + private Integer id; + private String type; + private String message; + @Version + private Long version; - @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 Integer getId() { + return id; + } - public Long getVersion() { - return version; - } + 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; + } - public void setVersion(Long version) { - this.version = version; - } - - - } diff --git a/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java b/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java index 5ddde6b71..ad949eed8 100644 --- a/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.data.elasticsearch.repositories.SampleElasticSearchBookRepository; @@ -24,38 +23,36 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; - import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; + /** * @author Rizwan Idrees * @author Mohsin Husen */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/repository-test-nested-object.xml") -public class NestedObjectTests{ +public class NestedObjectTests { - @Resource - private SampleElasticSearchBookRepository repository; + @Resource + private SampleElasticSearchBookRepository repository; - - @Test - public void shouldIndexNestedObject(){ - //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 - repository.save(book); - //then - assertThat(repository.findOne(id), is(notNullValue())); - } + @Test + public void shouldIndexNestedObject() { + // 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 + repository.save(book); + // then + assertThat(repository.findOne(id), is(notNullValue())); + } } - diff --git a/src/test/java/org/springframework/data/elasticsearch/NonDocumentEntity.java b/src/test/java/org/springframework/data/elasticsearch/NonDocumentEntity.java index 6d31c015d..1dafdebe4 100644 --- a/src/test/java/org/springframework/data/elasticsearch/NonDocumentEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/NonDocumentEntity.java @@ -15,32 +15,32 @@ */ package org.springframework.data.elasticsearch; - 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; + @Id + private String someId; + private String someField1; + private String someField2; - public String getSomeField1() { - return someField1; - } + public String getSomeField1() { + return someField1; + } - public void setSomeField1(String someField1) { - this.someField1 = someField1; - } + public void setSomeField1(String someField1) { + this.someField1 = someField1; + } - public String getSomeField2() { - return someField2; - } + public String getSomeField2() { + return someField2; + } - public void setSomeField2(String someField2) { - this.someField2 = someField2; - } + public void setSomeField2(String someField2) { + this.someField2 = someField2; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/NonDocumentEntityTests.java b/src/test/java/org/springframework/data/elasticsearch/NonDocumentEntityTests.java index bca4b6ffd..d461a253f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/NonDocumentEntityTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/NonDocumentEntityTests.java @@ -15,23 +15,21 @@ */ package org.springframework.data.elasticsearch; - import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.elasticsearch.repositories.NonDocumentEntityRepository; + /** * @author Rizwan Idrees * @author Mohsin Husen */ public class NonDocumentEntityTests { - - @Test(expected = BeanCreationException.class) - public void shouldNotInitialiseRepositoryWithNonDocument(){ - //when - ClassPathXmlApplicationContext ctx = - new ClassPathXmlApplicationContext("/repository-non-document-entity.xml"); - ctx.getBean(NonDocumentEntityRepository.class); - } + @Test(expected = BeanCreationException.class) + public void shouldNotInitialiseRepositoryWithNonDocument() { + // when + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/repository-non-document-entity.xml"); + ctx.getBean(NonDocumentEntityRepository.class); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/SampleEntity.java b/src/test/java/org/springframework/data/elasticsearch/SampleEntity.java index 15c474db2..dc890d840 100644 --- a/src/test/java/org/springframework/data/elasticsearch/SampleEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/SampleEntity.java @@ -25,93 +25,82 @@ import org.springframework.data.elasticsearch.annotations.Document; * @author Rizwan Idrees * @author Mohsin Husen */ -@Document(indexName = "test-index", type = "test-type", indexStoreType = "memory", shards = 1 , replicas = 0, refreshInterval = "-1") +@Document(indexName = "test-index", type = "test-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class SampleEntity { - @Id - private String id; - private String type; - private String message; - private int rate; - private boolean available; - @Version - private Long version; + @Id + private String id; + private String type; + private String message; + private int rate; + private boolean available; + @Version + private Long version; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } - public int getRate() { - return rate; - } + public int getRate() { + return rate; + } - public void setRate(int rate) { - this.rate = rate; - } + public void setRate(int rate) { + this.rate = rate; + } - public boolean isAvailable() { - return available; - } + public boolean isAvailable() { + return available; + } - public void setAvailable(boolean available) { - this.available = available; - } + public void setAvailable(boolean available) { + this.available = available; + } - public Long getVersion() { - return version; - } + public Long getVersion() { + return version; + } - public void setVersion(Long version) { - this.version = 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; - } - SampleEntity rhs = (SampleEntity) obj; - return new EqualsBuilder().append(this.id, rhs.id) - .append(this.type, rhs.type) - .append(this.message, rhs.message) - .append(this.rate,rhs.rate) - .append(this.available,rhs.available) - .append(this.version,rhs.version) - .isEquals(); - } + @Override + public boolean equals(Object obj) { + if (!(obj instanceof SampleEntity)) { + return false; + } + if (this == obj) { + return true; + } + SampleEntity rhs = (SampleEntity) obj; + return new EqualsBuilder().append(this.id, rhs.id).append(this.type, rhs.type).append(this.message, rhs.message) + .append(this.rate, rhs.rate).append(this.available, rhs.available).append(this.version, rhs.version).isEquals(); + } - @Override - public int hashCode() { - return new HashCodeBuilder() - .append(id) - .append(type) - .append(message) - .append(rate) - .append(available) - .append(version) - .toHashCode(); - } + @Override + public int hashCode() { + return new HashCodeBuilder().append(id).append(type).append(message).append(rate).append(available).append(version) + .toHashCode(); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/SampleMappingEntity.java b/src/test/java/org/springframework/data/elasticsearch/SampleMappingEntity.java index ff184b6c5..f82629c84 100644 --- a/src/test/java/org/springframework/data/elasticsearch/SampleMappingEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/SampleMappingEntity.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch; - import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; @@ -24,47 +23,43 @@ import org.springframework.data.elasticsearch.annotations.Field; * @author Rizwan Idrees * @author Mohsin Husen */ -@Document(indexName = "test-mapping", type = "mapping", indexStoreType = "memory", shards = 1 , replicas = 0, refreshInterval = "-1") +@Document(indexName = "test-mapping", type = "mapping", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class SampleMappingEntity { - @Id - private String id; - @Field(type = "string", index = "not_analyzed", store = true, searchAnalyzer = "standard", indexAnalyzer = "standard") - private String message; + @Id + private String id; + @Field(type = "string", index = "not_analyzed", store = true, searchAnalyzer = "standard", indexAnalyzer = "standard") + private String message; - private NestedEntity nested; + private NestedEntity nested; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getMessage() { - return message; - } + public String getMessage() { + return message; + } - public void setMessage(String message) { - this.message = message; - } + public void setMessage(String message) { + this.message = message; + } + static class NestedEntity { + @Field(type = "string") + private String someField; - static class NestedEntity{ - @Field(type = "string") - private String someField; + public String getSomeField() { + return someField; + } - public String getSomeField() { - return someField; - } - - public void setSomeField(String someField) { - this.someField = someField; - } - } + public void setSomeField(String someField) { + this.someField = someField; + } + } } - - - diff --git a/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java b/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java index 87ba04b11..bfb4ff13e 100644 --- a/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java @@ -39,25 +39,26 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("namespace.xml") public class ElasticsearchNamespaceHandlerTests { - @Autowired - private ApplicationContext context; + @Autowired + private ApplicationContext context; - @Test - public void shouldCreatesNodeClient() { - assertThat(context.getBean(NodeClientFactoryBean.class), is(notNullValue())); - assertThat(context.getBean(NodeClientFactoryBean.class), is(instanceOf(NodeClientFactoryBean.class))); - } + @Test + public void shouldCreatesNodeClient() { + assertThat(context.getBean(NodeClientFactoryBean.class), is(notNullValue())); + assertThat(context.getBean(NodeClientFactoryBean.class), is(instanceOf(NodeClientFactoryBean.class))); + } - @Test - public void shouldCreateTransportClient() { - assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue())); - assertThat(context.getBean(TransportClientFactoryBean.class), is(instanceOf(TransportClientFactoryBean.class))); - } + @Test + public void shouldCreateTransportClient() { + assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue())); + assertThat(context.getBean(TransportClientFactoryBean.class), is(instanceOf(TransportClientFactoryBean.class))); + } - @Test - public void shouldCreateRepository(){ - assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue())); - assertThat(context.getBean(SampleElasticsearchRepository.class), is(instanceOf(SampleElasticsearchRepository.class))); - } + @Test + public void shouldCreateRepository() { + assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue())); + assertThat(context.getBean(SampleElasticsearchRepository.class), + is(instanceOf(SampleElasticsearchRepository.class))); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/config/EnableElasticsearchRepositoriesTests.java b/src/test/java/org/springframework/data/elasticsearch/config/EnableElasticsearchRepositoriesTests.java index 0c5d0a889..ec9b0fbcf 100644 --- a/src/test/java/org/springframework/data/elasticsearch/config/EnableElasticsearchRepositoriesTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/EnableElasticsearchRepositoriesTests.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.config; - import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -41,22 +40,22 @@ import static org.junit.Assert.assertThat; @ContextConfiguration public class EnableElasticsearchRepositoriesTests { - @Configuration - @EnableElasticsearchRepositories(basePackages = "org.springframework.data.elasticsearch.repositories") - static class Config { + @Configuration + @EnableElasticsearchRepositories(basePackages = "org.springframework.data.elasticsearch.repositories") + static class Config { - @Bean - public ElasticsearchOperations elasticsearchTemplate() { - return new ElasticsearchTemplate(nodeBuilder().local(true).clusterName("testCluster").node().client()); - } - } + @Bean + public ElasticsearchOperations elasticsearchTemplate() { + return new ElasticsearchTemplate(nodeBuilder().local(true).clusterName("testCluster").node().client()); + } + } - @Autowired - private SampleElasticsearchRepository repository; + @Autowired + private SampleElasticsearchRepository repository; - @Test - public void bootstrapsRepository() { - assertThat(repository, is(notNullValue())); - } + @Test + public void bootstrapsRepository() { + assertThat(repository, is(notNullValue())); + } } 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 f74510e57..c0d413c60 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.core; - import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.sort.FieldSortBuilder; @@ -45,6 +44,7 @@ import static org.elasticsearch.index.query.QueryBuilders.fieldQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; + /** * @author Rizwan Idrees * @author Mohsin Husen @@ -53,686 +53,673 @@ import static org.junit.Assert.*; @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before(){ - elasticsearchTemplate.createIndex(SampleEntity.class); - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(matchAllQuery()); - elasticsearchTemplate.delete(deleteQuery,SampleEntity.class); - elasticsearchTemplate.refresh(SampleEntity.class, true); - } - - @Test - public void shouldReturnCountForGivenSearchQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); - //when - long count = elasticsearchTemplate.count(searchQuery, SampleEntity.class); - //then - assertThat(count, is(equalTo(1L))); - } - - @Test - public void shouldReturnObjectForGivenId(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - //when - GetQuery getQuery = new GetQuery(); - getQuery.setId(documentId); - SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); - //then - assertNotNull("not null....", sampleEntity1); - assertEquals(sampleEntity, sampleEntity1); - } - - @Test - public void shouldReturnPageForGivenSearchQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - - 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)); - } - - @Test - public void shouldDoBulkIndex(){ - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("some message"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - - indexQueries.add(indexQuery2); - //when - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - //then - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); - Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), is(equalTo(2L))); - } - - @Test - public void shouldDeleteDocumentForGivenId(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - //when - elasticsearchTemplate.delete("test-index","test-type",documentId); - elasticsearchTemplate.refresh(SampleEntity.class, true); - //then - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build(); - Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); - } - - @Test - public void shouldDeleteEntityForGivenId(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - //when - elasticsearchTemplate.delete(SampleEntity.class,documentId); - elasticsearchTemplate.refresh(SampleEntity.class, true); - //then - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build(); - Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); - } - - @Test - public void shouldDeleteDocumentForGivenQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - //when - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(fieldQuery("id", documentId)); - elasticsearchTemplate.delete(deleteQuery,SampleEntity.class); - //then - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id",documentId)).build(); - Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); - assertThat(sampleEntities.getTotalElements(), equalTo(0L)); - } - - @Test - public void shouldFilterSearchResultsForGivenFilter(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchAllQuery()) - .withFilter(boolFilter().must(termFilter("id", documentId))) - .build(); - //when - Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); - //then - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); - } - - @Test - public void shouldSortResultsGivenSortCriteria(){ - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("abc"); - sampleEntity1.setRate(10); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("xyz"); - sampleEntity2.setRate(5); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - - //third document - String documentId3 = randomNumeric(5); - SampleEntity sampleEntity3 = new SampleEntity(); - sampleEntity3.setId(documentId3); - sampleEntity3.setMessage("xyz"); - sampleEntity3.setRate(15); - sampleEntity3.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery3 = new IndexQuery(); - indexQuery3.setId(documentId3); - indexQuery3.setObject(sampleEntity3); - - indexQueries.add(indexQuery1); - indexQueries.add(indexQuery2); - indexQueries.add(indexQuery3); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class, true); - - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchAllQuery()) - .withSort(new FieldSortBuilder("rate").ignoreUnmapped(true).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())); - } - - @Test - public void shouldExecuteStringQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - - StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); - //when - Page sampleEntities = elasticsearchTemplate.queryForPage(stringQuery,SampleEntity.class); - //then - assertThat(sampleEntities.getTotalElements(), equalTo(1L)); - } - - @Test - public void shouldReturnPageableResultsGivenStringQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - - StringQuery stringQuery = new StringQuery(matchAllQuery().toString(),new PageRequest(0,10)); - //when - Page sampleEntities = elasticsearchTemplate.queryForPage(stringQuery,SampleEntity.class); - - //then - assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L))); - } - - @Test - @Ignore("By default, the search request will fail if there is no mapping associated with a field. The ignore_unmapped option allows to ignore fields that have no mapping and not sort by them") - public void shouldReturnSortedPageableResultsGivenStringQuery(){ - //todo - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - - StringQuery stringQuery = new StringQuery(matchAllQuery().toString(),new PageRequest(0,10), new Sort(new Sort.Order(Sort.Direction.ASC,"messsage"))); - //when - Page sampleEntities = elasticsearchTemplate.queryForPage(stringQuery,SampleEntity.class); - //then - assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L))); - } - - @Test - public void shouldReturnObjectMatchingGivenStringQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - - StringQuery stringQuery = new StringQuery(fieldQuery("id",documentId).toString()); - //when - SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(stringQuery, SampleEntity.class); - //then - assertThat(sampleEntity1, is(notNullValue())); - assertThat(sampleEntity1.getId(), is(equalTo(documentId))); - } - - @Test - public void shouldCreateIndexGivenEntityClass(){ - //when - boolean created = elasticsearchTemplate.createIndex(SampleEntity.class); - //then - assertThat(created, is(true)); - } - - - @Test - public void shouldExecuteGivenCriteriaQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some test message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("test")); - - //when - SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(criteriaQuery,SampleEntity.class); - //then - assertThat(sampleEntity1, is(notNullValue())); - } - - @Test - public void shouldReturnSpecifiedFields(){ - //given - String documentId = randomNumeric(5); - String message = "some test message"; - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage(message); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchAllQuery()) - .withIndices("test-index") - .withTypes("test-type") - .withFields("message") - .build(); - //when - Page page = elasticsearchTemplate.queryForPage(searchQuery, new ResultsMapper() { - @Override - public Page mapResults(SearchResponse response) { - List values = new ArrayList(); - for(SearchHit searchHit : response.getHits()){ - values.add((String) searchHit.field("message").value()); - } - return new PageImpl(values); - } - }); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - assertThat(page.getContent().get(0), is(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," + - " we want a painless setup and a completely free search schema, we want to be able to index data simply using JSON over HTTP, " + - "we want our search server to be always available, we want to be able to start with one machine and scale to hundreds, " + - "we want real-time search, we want simple multi-tenancy, and we want a solution that is built for the cloud."; - - String documentId1 = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId1); - sampleEntity1.setMessage(sampleMessage); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId1); - indexQuery1.setObject(sampleEntity1); - - elasticsearchTemplate.index(indexQuery1); - - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage(sampleMessage); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - - elasticsearchTemplate.index(indexQuery2); - elasticsearchTemplate.refresh(SampleEntity.class, true); - - - MoreLikeThisQuery moreLikeThisQuery = new MoreLikeThisQuery(); - 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(sampleEntity1)); - } - - @Test - public void shouldReturnResultsWithScanAndScroll(){ - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("some message"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - - indexQueries.add(indexQuery2); - //when - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - //then - - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchAllQuery()) - .withIndices("test-index") - .withTypes("test-type") - .withPageable(new PageRequest(0,1)) - .build(); - - String scrollId = elasticsearchTemplate.scan(searchQuery,1000,false); - List sampleEntities = new ArrayList(); - boolean hasRecords = true; - while (hasRecords){ - Page page = elasticsearchTemplate.scroll(scrollId, 5000L , new ResultsMapper() { - @Override - public Page mapResults(SearchResponse response) { - List chunk = new ArrayList(); - for(SearchHit searchHit : response.getHits()){ - if(response.getHits().getHits().length <= 0) { - return null; - } - SampleEntity user = new SampleEntity(); - user.setId(searchHit.getId()); - user.setMessage((String)searchHit.getSource().get("message")); - chunk.add(user); - } - return new PageImpl(chunk); - } - - }); - if(page != null) { - sampleEntities.addAll(page.getContent()); - hasRecords = page.hasNextPage(); - } - else{ - hasRecords = false; - } - - } - assertThat(sampleEntities.size(), is(equalTo(2))); - } - - @Test - public void shouldReturnListForGivenCriteria(){ - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("test message"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("test test"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - - indexQueries.add(indexQuery2); - - //second document - String documentId3 = randomNumeric(5); - SampleEntity sampleEntity3 = new SampleEntity(); - sampleEntity3.setId(documentId3); - sampleEntity3.setMessage("some message"); - sampleEntity3.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery3 = new IndexQuery(); - indexQuery3.setId(documentId3); - indexQuery3.setObject(sampleEntity3); - - indexQueries.add(indexQuery3); - //when - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - //when - CriteriaQuery singleCriteriaQuery = new CriteriaQuery(new Criteria("message").contains("test")); - CriteriaQuery multipleCriteriaQuery = new CriteriaQuery(new Criteria("message").contains("some").and("message").contains("message")); - List sampleEntitiesForSingleCriteria = elasticsearchTemplate.queryForList(singleCriteriaQuery,SampleEntity.class); - List sampleEntitiesForAndCriteria = elasticsearchTemplate.queryForList(multipleCriteriaQuery,SampleEntity.class); - //then - assertThat(sampleEntitiesForSingleCriteria.size(),is(2)); - assertThat(sampleEntitiesForAndCriteria.size(),is(1)); - } - - @Test - public void shouldReturnListForGivenStringQuery(){ - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("test message"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("test test"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - - indexQueries.add(indexQuery2); - - //second document - String documentId3 = randomNumeric(5); - SampleEntity sampleEntity3 = new SampleEntity(); - sampleEntity3.setId(documentId3); - sampleEntity3.setMessage("some message"); - sampleEntity3.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery3 = new IndexQuery(); - indexQuery3.setId(documentId3); - indexQuery3.setObject(sampleEntity3); - - indexQueries.add(indexQuery3); - //when - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - //when - StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); - List sampleEntities = elasticsearchTemplate.queryForList(stringQuery,SampleEntity.class); - //then - assertThat(sampleEntities.size(),is(3)); - } - - @Test - public void shouldPutMappingForGivenEntity()throws Exception{ - //given - Class entity = SampleMappingEntity.class; - elasticsearchTemplate.createIndex(entity); - //when - assertThat(elasticsearchTemplate.putMapping(entity) , is(true)) ; - } - - @Test - public void shouldDeleteIndexForGivenEntity(){ - //given - Class clazz = SampleEntity.class; - //when - elasticsearchTemplate.deleteIndex(clazz); - //then - assertThat(elasticsearchTemplate.indexExists(clazz),is(false)); - } - - + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + elasticsearchTemplate.createIndex(SampleEntity.class); + DeleteQuery deleteQuery = new DeleteQuery(); + deleteQuery.setQuery(matchAllQuery()); + elasticsearchTemplate.delete(deleteQuery, SampleEntity.class); + elasticsearchTemplate.refresh(SampleEntity.class, true); + } + + @Test + public void shouldReturnCountForGivenSearchQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); + // when + long count = elasticsearchTemplate.count(searchQuery, SampleEntity.class); + // then + assertThat(count, is(equalTo(1L))); + } + + @Test + public void shouldReturnObjectForGivenId() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + // when + GetQuery getQuery = new GetQuery(); + getQuery.setId(documentId); + SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); + // then + assertNotNull("not null....", sampleEntity1); + assertEquals(sampleEntity, sampleEntity1); + } + + @Test + public void shouldReturnPageForGivenSearchQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + + 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)); + } + + @Test + public void shouldDoBulkIndex() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("some message"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + + indexQueries.add(indexQuery2); + // when + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + // then + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); + Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + assertThat(sampleEntities.getTotalElements(), is(equalTo(2L))); + } + + @Test + public void shouldDeleteDocumentForGivenId() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + // when + elasticsearchTemplate.delete("test-index", "test-type", documentId); + elasticsearchTemplate.refresh(SampleEntity.class, true); + // then + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build(); + Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + } + + @Test + public void shouldDeleteEntityForGivenId() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + // when + elasticsearchTemplate.delete(SampleEntity.class, documentId); + elasticsearchTemplate.refresh(SampleEntity.class, true); + // then + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build(); + Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + } + + @Test + public void shouldDeleteDocumentForGivenQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + // when + DeleteQuery deleteQuery = new DeleteQuery(); + deleteQuery.setQuery(fieldQuery("id", documentId)); + elasticsearchTemplate.delete(deleteQuery, SampleEntity.class); + // then + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build(); + Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + } + + @Test + public void shouldFilterSearchResultsForGivenFilter() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFilter(boolFilter().must(termFilter("id", documentId))).build(); + // when + Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then + assertThat(sampleEntities.getTotalElements(), equalTo(1L)); + } + + @Test + public void shouldSortResultsGivenSortCriteria() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("abc"); + sampleEntity1.setRate(10); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("xyz"); + sampleEntity2.setRate(5); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + + // third document + String documentId3 = randomNumeric(5); + SampleEntity sampleEntity3 = new SampleEntity(); + sampleEntity3.setId(documentId3); + sampleEntity3.setMessage("xyz"); + sampleEntity3.setRate(15); + sampleEntity3.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery3 = new IndexQuery(); + indexQuery3.setId(documentId3); + indexQuery3.setObject(sampleEntity3); + + indexQueries.add(indexQuery1); + indexQueries.add(indexQuery2); + indexQueries.add(indexQuery3); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withSort(new FieldSortBuilder("rate").ignoreUnmapped(true).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())); + } + + @Test + public void shouldExecuteStringQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + + StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); + // when + Page sampleEntities = elasticsearchTemplate.queryForPage(stringQuery, SampleEntity.class); + // then + assertThat(sampleEntities.getTotalElements(), equalTo(1L)); + } + + @Test + public void shouldReturnPageableResultsGivenStringQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + + StringQuery stringQuery = new StringQuery(matchAllQuery().toString(), new PageRequest(0, 10)); + // when + Page sampleEntities = elasticsearchTemplate.queryForPage(stringQuery, SampleEntity.class); + + // then + assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L))); + } + + @Test + @Ignore("By default, the search request will fail if there is no mapping associated with a field. The ignore_unmapped option allows to ignore fields that have no mapping and not sort by them") + public void shouldReturnSortedPageableResultsGivenStringQuery() { + // todo + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + + StringQuery stringQuery = new StringQuery(matchAllQuery().toString(), new PageRequest(0, 10), new Sort( + new Sort.Order(Sort.Direction.ASC, "messsage"))); + // when + Page sampleEntities = elasticsearchTemplate.queryForPage(stringQuery, SampleEntity.class); + // then + assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L))); + } + + @Test + public void shouldReturnObjectMatchingGivenStringQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + + StringQuery stringQuery = new StringQuery(fieldQuery("id", documentId).toString()); + // when + SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(stringQuery, SampleEntity.class); + // then + assertThat(sampleEntity1, is(notNullValue())); + assertThat(sampleEntity1.getId(), is(equalTo(documentId))); + } + + @Test + public void shouldCreateIndexGivenEntityClass() { + // when + boolean created = elasticsearchTemplate.createIndex(SampleEntity.class); + // then + assertThat(created, is(true)); + } + + @Test + public void shouldExecuteGivenCriteriaQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some test message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("test")); + + // when + SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); + // then + assertThat(sampleEntity1, is(notNullValue())); + } + + @Test + public void shouldReturnSpecifiedFields() { + // given + String documentId = randomNumeric(5); + String message = "some test message"; + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage(message); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices("test-index") + .withTypes("test-type").withFields("message").build(); + // when + Page page = elasticsearchTemplate.queryForPage(searchQuery, new ResultsMapper() { + @Override + public Page mapResults(SearchResponse response) { + List values = new ArrayList(); + for (SearchHit searchHit : response.getHits()) { + values.add((String) searchHit.field("message").value()); + } + return new PageImpl(values); + } + }); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page.getContent().get(0), is(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," + + " we want a painless setup and a completely free search schema, we want to be able to index data simply using JSON over HTTP, " + + "we want our search server to be always available, we want to be able to start with one machine and scale to hundreds, " + + "we want real-time search, we want simple multi-tenancy, and we want a solution that is built for the cloud."; + + String documentId1 = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId1); + sampleEntity1.setMessage(sampleMessage); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId1); + indexQuery1.setObject(sampleEntity1); + + elasticsearchTemplate.index(indexQuery1); + + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage(sampleMessage); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + + elasticsearchTemplate.index(indexQuery2); + elasticsearchTemplate.refresh(SampleEntity.class, true); + + MoreLikeThisQuery moreLikeThisQuery = new MoreLikeThisQuery(); + 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(sampleEntity1)); + } + + @Test + public void shouldReturnResultsWithScanAndScroll() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("some message"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + + indexQueries.add(indexQuery2); + // when + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + // then + + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices("test-index") + .withTypes("test-type").withPageable(new PageRequest(0, 1)).build(); + + String scrollId = elasticsearchTemplate.scan(searchQuery, 1000, false); + List sampleEntities = new ArrayList(); + boolean hasRecords = true; + while (hasRecords) { + Page page = elasticsearchTemplate.scroll(scrollId, 5000L, new ResultsMapper() { + @Override + public Page mapResults(SearchResponse response) { + List chunk = new ArrayList(); + for (SearchHit searchHit : response.getHits()) { + if (response.getHits().getHits().length <= 0) { + return null; + } + SampleEntity user = new SampleEntity(); + user.setId(searchHit.getId()); + user.setMessage((String) searchHit.getSource().get("message")); + chunk.add(user); + } + return new PageImpl(chunk); + } + + }); + if (page != null) { + sampleEntities.addAll(page.getContent()); + hasRecords = page.hasNextPage(); + } else { + hasRecords = false; + } + + } + assertThat(sampleEntities.size(), is(equalTo(2))); + } + + @Test + public void shouldReturnListForGivenCriteria() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("test message"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("test test"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + + indexQueries.add(indexQuery2); + + // second document + String documentId3 = randomNumeric(5); + SampleEntity sampleEntity3 = new SampleEntity(); + sampleEntity3.setId(documentId3); + sampleEntity3.setMessage("some message"); + sampleEntity3.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery3 = new IndexQuery(); + indexQuery3.setId(documentId3); + indexQuery3.setObject(sampleEntity3); + + indexQueries.add(indexQuery3); + // when + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + // when + CriteriaQuery singleCriteriaQuery = new CriteriaQuery(new Criteria("message").contains("test")); + CriteriaQuery multipleCriteriaQuery = new CriteriaQuery(new Criteria("message").contains("some").and("message") + .contains("message")); + List sampleEntitiesForSingleCriteria = elasticsearchTemplate.queryForList(singleCriteriaQuery, + SampleEntity.class); + List sampleEntitiesForAndCriteria = elasticsearchTemplate.queryForList(multipleCriteriaQuery, + SampleEntity.class); + // then + assertThat(sampleEntitiesForSingleCriteria.size(), is(2)); + assertThat(sampleEntitiesForAndCriteria.size(), is(1)); + } + + @Test + public void shouldReturnListForGivenStringQuery() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("test message"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("test test"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + + indexQueries.add(indexQuery2); + + // second document + String documentId3 = randomNumeric(5); + SampleEntity sampleEntity3 = new SampleEntity(); + sampleEntity3.setId(documentId3); + sampleEntity3.setMessage("some message"); + sampleEntity3.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery3 = new IndexQuery(); + indexQuery3.setId(documentId3); + indexQuery3.setObject(sampleEntity3); + + indexQueries.add(indexQuery3); + // when + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + // when + StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); + List sampleEntities = elasticsearchTemplate.queryForList(stringQuery, SampleEntity.class); + // then + assertThat(sampleEntities.size(), is(3)); + } + + @Test + public void shouldPutMappingForGivenEntity() throws Exception { + // given + Class entity = SampleMappingEntity.class; + elasticsearchTemplate.createIndex(entity); + // when + assertThat(elasticsearchTemplate.putMapping(entity), is(true)); + } + + @Test + public void shouldDeleteIndexForGivenEntity() { + // given + Class clazz = SampleEntity.class; + // when + elasticsearchTemplate.deleteIndex(clazz); + // then + assertThat(elasticsearchTemplate.indexExists(clazz), is(false)); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/convert/DateTimeConvertersTests.java b/src/test/java/org/springframework/data/elasticsearch/core/convert/DateTimeConvertersTests.java index efbeac6df..d332cd931 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/convert/DateTimeConvertersTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/convert/DateTimeConvertersTests.java @@ -31,44 +31,44 @@ import java.util.TimeZone; * @author Mohsin Husen */ public class DateTimeConvertersTests { - @Test - public void testJodaDateTimeConverterWithNullValue() { - Assert.assertNull(DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(null)); - } + @Test + public void testJodaDateTimeConverterWithNullValue() { + Assert.assertNull(DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(null)); + } - @Test - public void testJodaDateTimeConverter() { - DateTime dateTime = new DateTime(2013, 1,24 , 6, 35, 0, DateTimeZone.UTC); - Assert.assertEquals("2013-01-24T06:35:00.000Z", - DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(dateTime)); - } + @Test + public void testJodaDateTimeConverter() { + DateTime dateTime = new DateTime(2013, 1, 24, 6, 35, 0, DateTimeZone.UTC); + Assert + .assertEquals("2013-01-24T06:35:00.000Z", DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(dateTime)); + } - @Test - public void testJodaLocalDateTimeConverterWithNullValue() { - Assert.assertNull(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(null)); - } + @Test + public void testJodaLocalDateTimeConverterWithNullValue() { + Assert.assertNull(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(null)); + } - @Test - public void testJodaLocalDateTimeConverter() { - LocalDateTime dateTime = new LocalDateTime(new DateTime(2013, 1,24, 6, 35, 0, DateTimeZone.UTC).getMillis(), - DateTimeZone.UTC); - Assert.assertEquals("2013-01-24T06:35:00.000Z", - DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(dateTime)); - } + @Test + public void testJodaLocalDateTimeConverter() { + LocalDateTime dateTime = new LocalDateTime(new DateTime(2013, 1, 24, 6, 35, 0, DateTimeZone.UTC).getMillis(), + DateTimeZone.UTC); + Assert.assertEquals("2013-01-24T06:35:00.000Z", + DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(dateTime)); + } - @Test - public void testJavaDateConverterWithNullValue() { - Assert.assertNull(DateTimeConverters.JavaDateConverter.INSTANCE.convert(null)); - } + @Test + public void testJavaDateConverterWithNullValue() { + Assert.assertNull(DateTimeConverters.JavaDateConverter.INSTANCE.convert(null)); + } - @Test - public void testJavaDateConverter() { - DateTime dateTime = new DateTime(2013, 1,24, 6, 35, 0, DateTimeZone.UTC); - Calendar calendar = Calendar.getInstance(); - calendar.setTimeZone(TimeZone.getTimeZone("UTC")); - calendar.setTimeInMillis(dateTime.getMillis()); + @Test + public void testJavaDateConverter() { + DateTime dateTime = new DateTime(2013, 1, 24, 6, 35, 0, DateTimeZone.UTC); + Calendar calendar = Calendar.getInstance(); + calendar.setTimeZone(TimeZone.getTimeZone("UTC")); + calendar.setTimeInMillis(dateTime.getMillis()); - Assert.assertEquals("2013-01-24T06:35:00.000Z", - DateTimeConverters.JavaDateConverter.INSTANCE.convert(calendar.getTime())); - } + Assert.assertEquals("2013-01-24T06:35:00.000Z", + DateTimeConverters.JavaDateConverter.INSTANCE.convert(calendar.getTime())); + } } 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 9b6a7dfe1..2348ce930 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,7 +15,6 @@ */ package org.springframework.data.elasticsearch.core.convert; - import org.junit.Test; import org.springframework.core.convert.ConversionService; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; @@ -23,36 +22,37 @@ import org.springframework.data.mapping.context.MappingContext; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; + /** * @author Rizwan Idrees * @author Mohsin Husen */ public class MappingElasticsearchConverterTests { - @Test(expected = IllegalArgumentException.class) - public void shouldFailToInitializeGivenMappingContextIsNull(){ - //given - new MappingElasticsearchConverter(null); - } + @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))); - } + @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))); + } - @Test - public void shouldReturnDefaultConversionService(){ - //given - MappingElasticsearchConverter converter = new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext()); - //when - ConversionService conversionService = converter.getConversionService(); - //then - assertThat(conversionService, is(notNullValue())); - } + @Test + public void shouldReturnDefaultConversionService() { + // given + MappingElasticsearchConverter converter = new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext()); + // when + ConversionService conversionService = converter.getConversionService(); + // then + assertThat(conversionService, is(notNullValue())); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentEntityTests.java b/src/test/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentEntityTests.java index daeeea195..5124dc871 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentEntityTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/mapping/SimpleElasticsearchPersistentEntityTests.java @@ -24,85 +24,85 @@ import org.springframework.data.util.TypeInformation; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; + /** * @author Rizwan Idrees * @author Mohsin Husen */ public class SimpleElasticsearchPersistentEntityTests { - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionGivenVersionPropertyIsNotLong() throws NoSuchFieldException, IntrospectionException { - //given - TypeInformation typeInformation = ClassTypeInformation.from(EntityWithWrongVersionType.class); - SimpleElasticsearchPersistentProperty persistentProperty = - new SimpleElasticsearchPersistentProperty(EntityWithWrongVersionType.class.getDeclaredField("version"), - new PropertyDescriptor("version", EntityWithWrongVersionType.class), - new SimpleElasticsearchPersistentEntity(typeInformation), - new SimpleTypeHolder()); + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionGivenVersionPropertyIsNotLong() throws NoSuchFieldException, IntrospectionException { + // given + TypeInformation typeInformation = ClassTypeInformation.from(EntityWithWrongVersionType.class); + SimpleElasticsearchPersistentProperty persistentProperty = new SimpleElasticsearchPersistentProperty( + EntityWithWrongVersionType.class.getDeclaredField("version"), new PropertyDescriptor("version", + EntityWithWrongVersionType.class), new SimpleElasticsearchPersistentEntity( + typeInformation), new SimpleTypeHolder()); - //when - new SimpleElasticsearchPersistentEntity(typeInformation).addPersistentProperty(persistentProperty); - } + // when + new SimpleElasticsearchPersistentEntity(typeInformation).addPersistentProperty(persistentProperty); + } + @Test(expected = MappingException.class) + public void shouldThrowExceptionGivenMultipleVersionPropertiesArePresent() throws NoSuchFieldException, + IntrospectionException { + // given + TypeInformation typeInformation = ClassTypeInformation.from(EntityWithMultipleVersionField.class); + SimpleElasticsearchPersistentProperty persistentProperty1 = new SimpleElasticsearchPersistentProperty( + EntityWithMultipleVersionField.class.getDeclaredField("version1"), new PropertyDescriptor("version1", + EntityWithMultipleVersionField.class), + new SimpleElasticsearchPersistentEntity(typeInformation), + new SimpleTypeHolder()); - @Test(expected = MappingException.class) - public void shouldThrowExceptionGivenMultipleVersionPropertiesArePresent() throws NoSuchFieldException, IntrospectionException { - //given - TypeInformation typeInformation = ClassTypeInformation.from(EntityWithMultipleVersionField.class); - SimpleElasticsearchPersistentProperty persistentProperty1 = - new SimpleElasticsearchPersistentProperty(EntityWithMultipleVersionField.class.getDeclaredField("version1"), - new PropertyDescriptor("version1", EntityWithMultipleVersionField.class), - new SimpleElasticsearchPersistentEntity(typeInformation), - new SimpleTypeHolder()); + SimpleElasticsearchPersistentProperty persistentProperty2 = new SimpleElasticsearchPersistentProperty( + EntityWithMultipleVersionField.class.getDeclaredField("version2"), new PropertyDescriptor("version2", + EntityWithMultipleVersionField.class), + new SimpleElasticsearchPersistentEntity(typeInformation), + new SimpleTypeHolder()); - SimpleElasticsearchPersistentProperty persistentProperty2 = - new SimpleElasticsearchPersistentProperty(EntityWithMultipleVersionField.class.getDeclaredField("version2"), - new PropertyDescriptor("version2", EntityWithMultipleVersionField.class), - new SimpleElasticsearchPersistentEntity(typeInformation), - new SimpleTypeHolder()); + SimpleElasticsearchPersistentEntity simpleElasticsearchPersistentEntity = new SimpleElasticsearchPersistentEntity( + typeInformation); + simpleElasticsearchPersistentEntity.addPersistentProperty(persistentProperty1); + // when + simpleElasticsearchPersistentEntity.addPersistentProperty(persistentProperty2); + } - SimpleElasticsearchPersistentEntity simpleElasticsearchPersistentEntity = new SimpleElasticsearchPersistentEntity(typeInformation); - simpleElasticsearchPersistentEntity.addPersistentProperty(persistentProperty1); - //when - simpleElasticsearchPersistentEntity.addPersistentProperty(persistentProperty2); - } + private class EntityWithWrongVersionType { + @Version + private String version; + public String getVersion() { + return version; + } - private class EntityWithWrongVersionType { - @Version - private String version; + public void setVersion(String version) { + this.version = version; + } + } - public String getVersion() { - return version; - } + private class EntityWithMultipleVersionField { - public void setVersion(String version) { - this.version = version; - } - } + @Version + private Long version1; + @Version + private Long version2; - private class EntityWithMultipleVersionField{ + public Long getVersion1() { + return version1; + } - @Version - private Long version1; - @Version - private Long version2; + public void setVersion1(Long version1) { + this.version1 = version1; + } - public Long getVersion1() { - return version1; - } + public Long getVersion2() { + return version2; + } - public void setVersion1(Long version1) { - this.version1 = version1; - } - - public Long getVersion2() { - return version2; - } - - public void setVersion2(Long version2) { - this.version2 = version2; - } - } + public void setVersion2(Long version2) { + this.version2 = version2; + } + } } 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 0f76dad58..c7459e405 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 @@ -32,6 +32,7 @@ import static org.apache.commons.lang.RandomStringUtils.randomNumeric; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; + /** * @author Rizwan Idrees * @author Mohsin Husen @@ -40,661 +41,663 @@ import static org.junit.Assert.*; @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class CriteriaQueryTests { - @Resource - private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before(){ - elasticsearchTemplate.createIndex(SampleEntity.class); - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(matchAllQuery()); - elasticsearchTemplate.delete(deleteQuery,SampleEntity.class); - elasticsearchTemplate.refresh(SampleEntity.class, true); - } - - @Test - public void shouldPerformAndOperation(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some test message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - 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())); - } - - @Test - public void shouldPerformOrOperation(){ - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("test message"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - - indexQueries.add(indexQuery2); - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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))); - } - - @Test - public void shouldPerformAndOperationWithinCriteria(){ - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - indexQueries.add(indexQuery); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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))); - } - - - @Test - public void shouldPerformOrOperationWithinCriteria(){ - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - indexQueries.add(indexQuery); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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))); - } - - @Test - public void shouldPerformIsOperation() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - indexQueries.add(indexQuery); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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))); - } - - @Test - public void shouldPerformMultipleIsOperations() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("test message"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message").is("test message")); - //when - Page page = elasticsearchTemplate.queryForPage(criteriaQuery,SampleEntity.class); - //then - assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); - assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(2L))); - } - - @Test - public void shouldPerformEndsWithOperation() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("test message end"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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())); - } - - @Test - public void shouldPerformStartsWithOperation() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("start some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("test message"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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())); - } - - @Test - public void shouldPerformContainsOperation() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("contains some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("test message"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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())); - } - - @Test - public void shouldExecuteExpression() { - //given - //todo - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("elasticsearch search"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("test message"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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())); - } - - @Test - public void shouldExecuteCriteriaChain() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("some message search"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("test test message"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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())); - } - - @Test - public void shouldPerformIsNotOperation() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("bar"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("foo"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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")); - } - - @Test - public void shouldPerformBetweenOperation() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setRate(100); - sampleEntity1.setMessage("bar"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setRate(200); - sampleEntity2.setMessage("foo"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100,150)); - //when - SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); - //then - assertThat(sampleEntity,is(notNullValue())); - } - - @Test - public void shouldPerformBetweenOperationWithoutUpperBound() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setRate(300); - sampleEntity1.setMessage("bar"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setRate(400); - sampleEntity2.setMessage("foo"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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))); - } - - @Test - public void shouldPerformBetweenOperationWithoutLowerBound() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setRate(500); - sampleEntity1.setMessage("bar"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setRate(600); - sampleEntity2.setMessage("foo"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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))); - } - - @Test - public void shouldPerformLessThanEqualOperation() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setRate(700); - sampleEntity1.setMessage("bar"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setRate(800); - sampleEntity2.setMessage("foo"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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))); - } - - @Test - public void shouldPerformGreaterThanEquals() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setRate(900); - sampleEntity1.setMessage("bar"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setRate(1000); - sampleEntity2.setMessage("foo"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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))); - } - - @Test - public void shouldPerformBoostOperation() { - //given - List indexQueries = new ArrayList(); - //first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setRate(700); - sampleEntity1.setMessage("bar foo"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - //second document - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setRate(800); - sampleEntity2.setMessage("foo"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(documentId2); - indexQuery2.setObject(sampleEntity2); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class,true); - 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))); - } + @Resource + private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + elasticsearchTemplate.createIndex(SampleEntity.class); + DeleteQuery deleteQuery = new DeleteQuery(); + deleteQuery.setQuery(matchAllQuery()); + elasticsearchTemplate.delete(deleteQuery, SampleEntity.class); + elasticsearchTemplate.refresh(SampleEntity.class, true); + } + + @Test + public void shouldPerformAndOperation() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some test message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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())); + } + + @Test + public void shouldPerformOrOperation() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("test message"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + + indexQueries.add(indexQuery2); + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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))); + } + + @Test + public void shouldPerformAndOperationWithinCriteria() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + indexQueries.add(indexQuery); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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))); + } + + @Test + public void shouldPerformOrOperationWithinCriteria() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + indexQueries.add(indexQuery); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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))); + } + + @Test + public void shouldPerformIsOperation() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + indexQueries.add(indexQuery); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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))); + } + + @Test + public void shouldPerformMultipleIsOperations() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("test message"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message").is("test message")); + // when + Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then + assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); + assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(2L))); + } + + @Test + public void shouldPerformEndsWithOperation() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("test message end"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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())); + } + + @Test + public void shouldPerformStartsWithOperation() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("start some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("test message"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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())); + } + + @Test + public void shouldPerformContainsOperation() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("contains some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("test message"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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())); + } + + @Test + public void shouldExecuteExpression() { + // given + // todo + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("elasticsearch search"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("test message"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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())); + } + + @Test + public void shouldExecuteCriteriaChain() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("some message search"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("test test message"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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())); + } + + @Test + public void shouldPerformIsNotOperation() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("bar"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("foo"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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")); + } + + @Test + public void shouldPerformBetweenOperation() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setRate(100); + sampleEntity1.setMessage("bar"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setRate(200); + sampleEntity2.setMessage("foo"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100, 150)); + // when + SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); + // then + assertThat(sampleEntity, is(notNullValue())); + } + + @Test + public void shouldPerformBetweenOperationWithoutUpperBound() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setRate(300); + sampleEntity1.setMessage("bar"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setRate(400); + sampleEntity2.setMessage("foo"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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))); + } + + @Test + public void shouldPerformBetweenOperationWithoutLowerBound() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setRate(500); + sampleEntity1.setMessage("bar"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setRate(600); + sampleEntity2.setMessage("foo"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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))); + } + + @Test + public void shouldPerformLessThanEqualOperation() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setRate(700); + sampleEntity1.setMessage("bar"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setRate(800); + sampleEntity2.setMessage("foo"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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))); + } + + @Test + public void shouldPerformGreaterThanEquals() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setRate(900); + sampleEntity1.setMessage("bar"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setRate(1000); + sampleEntity2.setMessage("foo"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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))); + } + + @Test + public void shouldPerformBoostOperation() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setRate(700); + sampleEntity1.setMessage("bar foo"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setRate(800); + sampleEntity2.setMessage("foo"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(documentId2); + indexQuery2.setObject(sampleEntity2); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + 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))); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryTests.java index 20ca76252..2c70a0983 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryTests.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.repositories; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -38,6 +37,7 @@ import static org.apache.commons.lang.RandomStringUtils.randomNumeric; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; + /** * @author Rizwan Idrees * @author Mohsin Husen @@ -46,454 +46,450 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:custom-method-repository-test.xml") public class CustomMethodRepositoryTests { - @Resource - private SampleCustomMethodRepository repository; + @Resource + private SampleCustomMethodRepository repository; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; - @Before - public void before(){ - elasticsearchTemplate.createIndex(SampleEntity.class); - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(matchAllQuery()); - elasticsearchTemplate.delete(deleteQuery,SampleEntity.class); - elasticsearchTemplate.refresh(SampleEntity.class, true); - } + @Before + public void before() { + elasticsearchTemplate.createIndex(SampleEntity.class); + DeleteQuery deleteQuery = new DeleteQuery(); + deleteQuery.setQuery(matchAllQuery()); + elasticsearchTemplate.delete(deleteQuery, SampleEntity.class); + elasticsearchTemplate.refresh(SampleEntity.class, true); + } - @Test - public void shouldExecuteCustomMethod(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setMessage("some message"); - repository.save(sampleEntity); - //when - Page page = repository.findByType("test", new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); - } + @Test + public void shouldExecuteCustomMethod() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setMessage("some message"); + repository.save(sampleEntity); + // when + Page page = repository.findByType("test", new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + } - @Test - public void shouldExecuteCustomMethodForNot(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("some"); - sampleEntity.setMessage("some message"); - repository.save(sampleEntity); - //when - Page page = repository.findByTypeNot("test", new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodForNot() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("some"); + sampleEntity.setMessage("some message"); + repository.save(sampleEntity); + // when + Page page = repository.findByTypeNot("test", new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - @Test - public void shouldExecuteCustomMethodWithQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setMessage("customQuery"); - repository.save(sampleEntity); - //when - Page page = repository.findByMessage("customQuery", new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); - } + @Test + public void shouldExecuteCustomMethodWithQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setMessage("customQuery"); + repository.save(sampleEntity); + // when + Page page = repository.findByMessage("customQuery", new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); + } + @Test + public void shouldExecuteCustomMethodWithLessThan() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setRate(10); + sampleEntity.setMessage("some message"); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodWithLessThan(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setRate(10); - sampleEntity.setMessage("some message"); - repository.save(sampleEntity); + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setType("test"); + sampleEntity2.setRate(20); + sampleEntity2.setMessage("some message"); + repository.save(sampleEntity2); - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setType("test"); - sampleEntity2.setRate(20); - sampleEntity2.setMessage("some message"); - repository.save(sampleEntity2); + // when + Page page = repository.findByRateLessThan(10, new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //when - Page page = repository.findByRateLessThan(10, new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodWithBefore() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setRate(10); + sampleEntity.setMessage("some message"); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodWithBefore(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setRate(10); - sampleEntity.setMessage("some message"); - repository.save(sampleEntity); + // when + Page page = repository.findByRateBefore(10, new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //when - Page page = repository.findByRateBefore(10, new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodWithAfter() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setRate(10); + sampleEntity.setMessage("some message"); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodWithAfter(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setRate(10); - sampleEntity.setMessage("some message"); - repository.save(sampleEntity); + // when + Page page = repository.findByRateAfter(10, new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //when - Page page = repository.findByRateAfter(10, new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodWithLike() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setRate(10); + sampleEntity.setMessage("foo"); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodWithLike(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setRate(10); - sampleEntity.setMessage("foo"); - repository.save(sampleEntity); + // when + Page page = repository.findByMessageLike("fo", new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //when - Page page = repository.findByMessageLike("fo", new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodForStartingWith() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setRate(10); + sampleEntity.setMessage("foo"); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodForStartingWith(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setRate(10); - sampleEntity.setMessage("foo"); - repository.save(sampleEntity); + // when + Page page = repository.findByMessageStartingWith("fo", new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //when - Page page = repository.findByMessageStartingWith("fo", new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodForEndingWith() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setRate(10); + sampleEntity.setMessage("foo"); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodForEndingWith(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setRate(10); - sampleEntity.setMessage("foo"); - repository.save(sampleEntity); + // when + Page page = repository.findByMessageEndingWith("o", new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //when - Page page = repository.findByMessageEndingWith("o", new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodForContains() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setRate(10); + sampleEntity.setMessage("foo"); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodForContains(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setRate(10); - sampleEntity.setMessage("foo"); - repository.save(sampleEntity); + // when + Page page = repository.findByMessageContaining("fo", new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //when - Page page = repository.findByMessageContaining("fo", new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodForIn() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setMessage("foo"); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodForIn(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setMessage("foo"); - repository.save(sampleEntity); + // given + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setType("test"); + sampleEntity2.setMessage("bar"); + repository.save(sampleEntity2); - //given - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setType("test"); - sampleEntity2.setMessage("bar"); - repository.save(sampleEntity2); + List ids = Arrays.asList(documentId, documentId2); - List ids = Arrays.asList(documentId,documentId2); + // when + Page page = repository.findByIdIn(ids, new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(2L))); + } - //when - Page page = repository.findByIdIn(ids, new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(2L))); - } + @Test + public void shouldExecuteCustomMethodForNotIn() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setMessage("foo"); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodForNotIn(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setMessage("foo"); - repository.save(sampleEntity); + // given + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setType("test"); + sampleEntity2.setMessage("bar"); + repository.save(sampleEntity2); - //given - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setType("test"); - sampleEntity2.setMessage("bar"); - repository.save(sampleEntity2); + List ids = Arrays.asList(documentId); - List ids = Arrays.asList(documentId); + // when + Page page = repository.findByIdNotIn(ids, new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + assertThat(page.getContent().get(0).getId(), is(documentId2)); + } - //when - Page page = repository.findByIdNotIn(ids, new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - assertThat(page.getContent().get(0).getId(),is(documentId2)); - } + @Test + public void shouldExecuteCustomMethodForTrue() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setMessage("foo"); + sampleEntity.setAvailable(true); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodForTrue(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setMessage("foo"); - sampleEntity.setAvailable(true); - repository.save(sampleEntity); + // given + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setType("test"); + sampleEntity2.setMessage("bar"); + sampleEntity2.setAvailable(false); + repository.save(sampleEntity2); + // when + Page page = repository.findByAvailableTrue(new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //given - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setType("test"); - sampleEntity2.setMessage("bar"); - sampleEntity2.setAvailable(false); - repository.save(sampleEntity2); - //when - Page page = repository.findByAvailableTrue(new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodForFalse() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setMessage("foo"); + sampleEntity.setAvailable(true); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodForFalse(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setMessage("foo"); - sampleEntity.setAvailable(true); - repository.save(sampleEntity); + // given + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setType("test"); + sampleEntity2.setMessage("bar"); + sampleEntity2.setAvailable(false); + repository.save(sampleEntity2); + // when + Page page = repository.findByAvailableFalse(new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //given - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setType("test"); - sampleEntity2.setMessage("bar"); - sampleEntity2.setAvailable(false); - repository.save(sampleEntity2); - //when - Page page = repository.findByAvailableFalse(new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodForOrderBy() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("abc"); + sampleEntity.setMessage("test"); + sampleEntity.setAvailable(true); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodForOrderBy(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("abc"); - sampleEntity.setMessage("test"); - sampleEntity.setAvailable(true); - repository.save(sampleEntity); + // document 2 + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setType("xyz"); + sampleEntity2.setMessage("bar"); + sampleEntity2.setAvailable(false); + repository.save(sampleEntity2); - //document 2 - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setType("xyz"); - sampleEntity2.setMessage("bar"); - sampleEntity2.setAvailable(false); - repository.save(sampleEntity2); + // document 3 + String documentId3 = randomNumeric(5); + SampleEntity sampleEntity3 = new SampleEntity(); + sampleEntity3.setId(documentId3); + sampleEntity3.setType("def"); + sampleEntity3.setMessage("foo"); + sampleEntity3.setAvailable(false); + repository.save(sampleEntity3); - //document 3 - String documentId3 = randomNumeric(5); - SampleEntity sampleEntity3 = new SampleEntity(); - sampleEntity3.setId(documentId3); - sampleEntity3.setType("def"); - sampleEntity3.setMessage("foo"); - sampleEntity3.setAvailable(false); - repository.save(sampleEntity3); + // when + Page page = repository.findByMessageOrderByTypeAsc("foo", new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //when - Page page = repository.findByMessageOrderByTypeAsc("foo",new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldExecuteCustomMethodWithBooleanParameter() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setType("test"); + sampleEntity.setMessage("foo"); + sampleEntity.setAvailable(true); + repository.save(sampleEntity); - @Test - public void shouldExecuteCustomMethodWithBooleanParameter(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setType("test"); - sampleEntity.setMessage("foo"); - sampleEntity.setAvailable(true); - repository.save(sampleEntity); + // given + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setType("test"); + sampleEntity2.setMessage("bar"); + sampleEntity2.setAvailable(false); + repository.save(sampleEntity2); + // when + Page page = repository.findByAvailable(false, new PageRequest(0, 10)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getTotalElements(), is(equalTo(1L))); + } - //given - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setType("test"); - sampleEntity2.setMessage("bar"); - sampleEntity2.setAvailable(false); - repository.save(sampleEntity2); - //when - Page page = repository.findByAvailable(false, new PageRequest(0, 10)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getTotalElements(), is(equalTo(1L))); - } + @Test + public void shouldReturnPageableResultsWithQueryAnnotationExpectedPageSize() { + // given + for (int i = 0; i < 30; i++) { + String documentId = String.valueOf(i); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("message"); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); + } + // when + Page pageResult = repository.findByMessage("message", new PageRequest(0, 23, new Sort(new Sort.Order( + Sort.Direction.ASC, "message")))); + // then + assertThat(pageResult.getTotalElements(), is(equalTo(30L))); + assertThat(pageResult.getContent().size(), is(equalTo(23))); + } - @Test - public void shouldReturnPageableResultsWithQueryAnnotationExpectedPageSize() { - // given - for (int i = 0; i < 30; i++) { - String documentId = String.valueOf(i); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("message"); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); - } - // when - Page pageResult = repository.findByMessage("message", new PageRequest(0, 23, new Sort(new Sort.Order(Sort.Direction.ASC,"message")))); - // then - assertThat(pageResult.getTotalElements(), is(equalTo(30L))); - assertThat(pageResult.getContent().size(), is(equalTo(23))); - } + @Test + public void shouldReturnPageableResultsWithGivenSortingOrder() { + // given + String documentId = random(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("abc"); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); - @Test - public void shouldReturnPageableResultsWithGivenSortingOrder(){ - //given - String documentId = random(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("abc"); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); - - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("abd"); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity2); - - String documentId3 = randomNumeric(5); - SampleEntity sampleEntity3 = new SampleEntity(); - sampleEntity3.setId(documentId3); - sampleEntity3.setMessage("abe"); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity3); - //when - Page pageResult = repository.findByMessageContaining("a", new PageRequest(0, 23, new Sort(new Sort.Order(Sort.Direction.DESC,"message")))); - //then - assertThat(pageResult.getContent().isEmpty(),is(false)); - assertThat(pageResult.getContent().get(0).getMessage(),is(sampleEntity3.getMessage())); - } - - - @Test - public void shouldReturnListForMessage(){ - //given - String documentId = random(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("abc"); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); - - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("abd"); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity2); - - String documentId3 = randomNumeric(5); - SampleEntity sampleEntity3 = new SampleEntity(); - sampleEntity3.setId(documentId3); - 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)); - } + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("abd"); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity2); + String documentId3 = randomNumeric(5); + SampleEntity sampleEntity3 = new SampleEntity(); + sampleEntity3.setId(documentId3); + sampleEntity3.setMessage("abe"); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity3); + // when + Page pageResult = repository.findByMessageContaining("a", new PageRequest(0, 23, new Sort( + new Sort.Order(Sort.Direction.DESC, "message")))); + // then + assertThat(pageResult.getContent().isEmpty(), is(false)); + assertThat(pageResult.getContent().get(0).getMessage(), is(sampleEntity3.getMessage())); + } + @Test + public void shouldReturnListForMessage() { + // given + String documentId = random(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("abc"); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("abd"); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity2); + String documentId3 = randomNumeric(5); + SampleEntity sampleEntity3 = new SampleEntity(); + sampleEntity3.setId(documentId3); + 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)); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/DoubleIDRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/DoubleIDRepository.java index 663164f19..d6a296823 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/DoubleIDRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/DoubleIDRepository.java @@ -18,8 +18,6 @@ package org.springframework.data.elasticsearch.repositories; import org.springframework.data.elasticsearch.DoubleIDEntity; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; -public interface DoubleIDRepository extends ElasticsearchRepository { - - +public interface DoubleIDRepository extends ElasticsearchRepository { } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/IntegerIDRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/IntegerIDRepository.java index 090016c66..2d675af5e 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/IntegerIDRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/IntegerIDRepository.java @@ -18,6 +18,6 @@ package org.springframework.data.elasticsearch.repositories; import org.springframework.data.elasticsearch.IntegerIDEntity; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; -public interface IntegerIDRepository extends ElasticsearchRepository { +public interface IntegerIDRepository extends ElasticsearchRepository { } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/NonDocumentEntityRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/NonDocumentEntityRepository.java index feabf3d83..e78f14ab3 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/NonDocumentEntityRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/NonDocumentEntityRepository.java @@ -22,5 +22,5 @@ import org.springframework.data.elasticsearch.repository.ElasticsearchRepository * @author Rizwan Idrees * @author Mohsin Husen */ -public interface NonDocumentEntityRepository extends ElasticsearchRepository { +public interface NonDocumentEntityRepository extends ElasticsearchRepository { } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/SampleCustomMethodRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/SampleCustomMethodRepository.java index 5e1ccaf2c..c31d8d26a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/SampleCustomMethodRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/SampleCustomMethodRepository.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.repositories; - import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.SampleEntity; @@ -23,46 +22,47 @@ import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; + /** * @author Rizwan Idrees * @author Mohsin Husen */ -public interface SampleCustomMethodRepository extends ElasticsearchRepository { +public interface SampleCustomMethodRepository extends ElasticsearchRepository { - Page findByType(String type, Pageable pageable); + Page findByType(String type, Pageable pageable); - Page findByTypeNot(String type, Pageable pageable); + Page findByTypeNot(String type, Pageable pageable); - @Query("{\"bool\" : {\"must\" : {\"field\" : {\"message\" : \"?0\"}}}}") - Page findByMessage(String message, Pageable pageable); + @Query("{\"bool\" : {\"must\" : {\"field\" : {\"message\" : \"?0\"}}}}") + Page findByMessage(String message, Pageable pageable); - @Query("{\"bool\" : {\"must\" : {\"field\" : {\"message\" : \"?0\"}}}}") - List findByMessage(String message); + @Query("{\"bool\" : {\"must\" : {\"field\" : {\"message\" : \"?0\"}}}}") + List findByMessage(String message); - Page findByAvailable(boolean available, Pageable pageable); + Page findByAvailable(boolean available, Pageable pageable); - Page findByRateLessThan(int rate, Pageable pageable); + Page findByRateLessThan(int rate, Pageable pageable); - Page findByRateBefore(int rate, Pageable pageable); + Page findByRateBefore(int rate, Pageable pageable); - Page findByRateAfter(int rate, Pageable pageable); + Page findByRateAfter(int rate, Pageable pageable); - Page findByMessageLike(String message, Pageable pageable); + Page findByMessageLike(String message, Pageable pageable); - Page findByMessageStartingWith(String message, Pageable pageable); + Page findByMessageStartingWith(String message, Pageable pageable); - Page findByMessageEndingWith(String message, Pageable pageable); + Page findByMessageEndingWith(String message, Pageable pageable); - Page findByMessageContaining(String message, Pageable pageable); + Page findByMessageContaining(String message, Pageable pageable); - Page findByIdIn(List ids, Pageable pageable); + Page findByIdIn(List ids, Pageable pageable); - Page findByIdNotIn(List messages, Pageable pageable); + Page findByIdNotIn(List messages, Pageable pageable); - Page findByAvailableTrue(Pageable pageable); + Page findByAvailableTrue(Pageable pageable); - Page findByAvailableFalse(Pageable pageable); + Page findByAvailableFalse(Pageable pageable); - Page findByMessageOrderByTypeAsc(String message,Pageable pageable); + Page findByMessageOrderByTypeAsc(String message, Pageable pageable); } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/SampleElasticSearchBookRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/SampleElasticSearchBookRepository.java index 3545546bb..c590fcd8f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/SampleElasticSearchBookRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/SampleElasticSearchBookRepository.java @@ -24,5 +24,5 @@ import java.util.List; * @author Rizwan Idrees * @author Mohsin Husen */ -public interface SampleElasticSearchBookRepository extends ElasticsearchRepository { +public interface SampleElasticSearchBookRepository extends ElasticsearchRepository { } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/SampleElasticsearchRepository.java b/src/test/java/org/springframework/data/elasticsearch/repositories/SampleElasticsearchRepository.java index 8b0bbc29b..112045f05 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/SampleElasticsearchRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/SampleElasticsearchRepository.java @@ -17,10 +17,11 @@ package org.springframework.data.elasticsearch.repositories; import org.springframework.data.elasticsearch.SampleEntity; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; + /** * @author Rizwan Idrees * @author Mohsin Husen */ -public interface SampleElasticsearchRepository extends ElasticsearchRepository { +public interface SampleElasticsearchRepository extends ElasticsearchRepository { } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/DoubleIDRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/support/DoubleIDRepositoryTests.java index 695aa172e..355d5519e 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/DoubleIDRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/support/DoubleIDRepositoryTests.java @@ -38,51 +38,51 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:/simple-repository-test.xml") public class DoubleIDRepositoryTests { - @Resource - private DoubleIDRepository repository; + @Resource + private DoubleIDRepository repository; - @Before - public void before(){ - repository.deleteAll(); - } + @Before + public void before() { + repository.deleteAll(); + } - @Test - public void shouldDoBulkIndexDocument(){ - //given - Double documentId1 = RandomUtils.nextDouble(); - DoubleIDEntity sampleEntity1 = new DoubleIDEntity(); - sampleEntity1.setId(documentId1); - sampleEntity1.setMessage("some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); + @Test + public void shouldDoBulkIndexDocument() { + // given + Double documentId1 = RandomUtils.nextDouble(); + DoubleIDEntity sampleEntity1 = new DoubleIDEntity(); + sampleEntity1.setId(documentId1); + sampleEntity1.setMessage("some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); - Double documentId2 = RandomUtils.nextDouble(); - DoubleIDEntity sampleEntity2 = new DoubleIDEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("some message"); - sampleEntity2.setVersion(System.currentTimeMillis()); + Double documentId2 = RandomUtils.nextDouble(); + DoubleIDEntity sampleEntity2 = new DoubleIDEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("some message"); + sampleEntity2.setVersion(System.currentTimeMillis()); - //when - repository.save(Arrays.asList(sampleEntity1, sampleEntity2)); - //then - DoubleIDEntity entity1FromElasticSearch = repository.findOne(documentId1); - assertThat(entity1FromElasticSearch, is(notNullValue())); + // when + repository.save(Arrays.asList(sampleEntity1, sampleEntity2)); + // then + DoubleIDEntity entity1FromElasticSearch = repository.findOne(documentId1); + assertThat(entity1FromElasticSearch, is(notNullValue())); - DoubleIDEntity entity2FromElasticSearch = repository.findOne(documentId2); - assertThat(entity2FromElasticSearch, is(notNullValue())); - } + DoubleIDEntity entity2FromElasticSearch = repository.findOne(documentId2); + assertThat(entity2FromElasticSearch, is(notNullValue())); + } - @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 - DoubleIDEntity entityFromElasticSearch = repository.findOne(documentId); - assertThat(entityFromElasticSearch, is(notNullValue())); - } + @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 + DoubleIDEntity entityFromElasticSearch = repository.findOne(documentId); + assertThat(entityFromElasticSearch, is(notNullValue())); + } } 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 66993ca11..c150f4fdc 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 @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.repository.support; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -33,6 +32,7 @@ import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.core.support.DefaultRepositoryMetadata; import static org.mockito.Mockito.when; + /** * @author Rizwan Idrees * @author Mohsin Husen @@ -40,27 +40,25 @@ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ElasticsearchRepositoryFactoryTests { - @Mock - private ElasticsearchOperations operations; - private ElasticsearchConverter converter; - private ElasticsearchRepositoryFactory factory; - MappingContext, ElasticsearchPersistentProperty> mappingContext= new SimpleElasticsearchMappingContext(); + @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); - } + @Before + public void before() { + converter = new MappingElasticsearchConverter(mappingContext); + when(operations.getElasticsearchConverter()).thenReturn(converter); + factory = new ElasticsearchRepositoryFactory(operations); + } - - - @Test(expected = IllegalArgumentException.class) - public void shouldThrowExceptionGivenQueryDslRepository(){ - //given - RepositoryMetadata metadata = new DefaultRepositoryMetadata(QueryDslPredicateExecutor.class); - //when - factory.getRepositoryBaseClass(metadata); - } + @Test(expected = IllegalArgumentException.class) + public void shouldThrowExceptionGivenQueryDslRepository() { + // given + RepositoryMetadata metadata = new DefaultRepositoryMetadata(QueryDslPredicateExecutor.class); + // when + factory.getRepositoryBaseClass(metadata); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/IntegerIDRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/support/IntegerIDRepositoryTests.java index feac87476..f5013c67b 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/IntegerIDRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/support/IntegerIDRepositoryTests.java @@ -38,51 +38,51 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:/simple-repository-test.xml") public class IntegerIDRepositoryTests { - @Resource - private IntegerIDRepository repository; + @Resource + private IntegerIDRepository repository; - @Before - public void before(){ - repository.deleteAll(); - } + @Before + public void before() { + repository.deleteAll(); + } - @Test - public void shouldDoBulkIndexDocument(){ - //given - Integer documentId1 = RandomUtils.nextInt(); - IntegerIDEntity sampleEntity1 = new IntegerIDEntity(); - sampleEntity1.setId(documentId1); - sampleEntity1.setMessage("some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); + @Test + public void shouldDoBulkIndexDocument() { + // given + Integer documentId1 = RandomUtils.nextInt(); + IntegerIDEntity sampleEntity1 = new IntegerIDEntity(); + sampleEntity1.setId(documentId1); + sampleEntity1.setMessage("some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); - Integer documentId2 = RandomUtils.nextInt(); - IntegerIDEntity sampleEntity2 = new IntegerIDEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("some message"); - sampleEntity2.setVersion(System.currentTimeMillis()); + Integer documentId2 = RandomUtils.nextInt(); + IntegerIDEntity sampleEntity2 = new IntegerIDEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("some message"); + sampleEntity2.setVersion(System.currentTimeMillis()); - //when - repository.save(Arrays.asList(sampleEntity1, sampleEntity2)); - //then - IntegerIDEntity entity1FromElasticSearch = repository.findOne(documentId1); - assertThat(entity1FromElasticSearch, is(notNullValue())); + // when + repository.save(Arrays.asList(sampleEntity1, sampleEntity2)); + // then + IntegerIDEntity entity1FromElasticSearch = repository.findOne(documentId1); + assertThat(entity1FromElasticSearch, is(notNullValue())); - IntegerIDEntity entity2FromElasticSearch = repository.findOne(documentId2); - assertThat(entity2FromElasticSearch, is(notNullValue())); - } + IntegerIDEntity entity2FromElasticSearch = repository.findOne(documentId2); + assertThat(entity2FromElasticSearch, is(notNullValue())); + } - @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 - IntegerIDEntity entityFromElasticSearch = repository.findOne(documentId); - assertThat(entityFromElasticSearch, is(notNullValue())); - } + @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 + IntegerIDEntity entityFromElasticSearch = repository.findOne(documentId); + assertThat(entityFromElasticSearch, is(notNullValue())); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepositoryTests.java index 455bff24c..f148d472f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/support/SimpleElasticsearchRepositoryTests.java @@ -15,7 +15,6 @@ */ package org.springframework.data.elasticsearch.repository.support; - import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -49,380 +48,367 @@ import static org.junit.Assert.*; @ContextConfiguration("classpath:/simple-repository-test.xml") public class SimpleElasticsearchRepositoryTests { - @Resource - private SampleElasticsearchRepository repository; + @Resource + private SampleElasticsearchRepository repository; + @Before + public void before() { + repository.deleteAll(); + } - @Before - public void before(){ - repository.deleteAll(); - } + @Test + public void shouldDoBulkIndexDocument() { + // given + String documentId1 = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId1); + sampleEntity1.setMessage("some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); - @Test - public void shouldDoBulkIndexDocument(){ - //given - String documentId1 = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId1); - sampleEntity1.setMessage("some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("some message"); + sampleEntity2.setVersion(System.currentTimeMillis()); - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("some message"); - sampleEntity2.setVersion(System.currentTimeMillis()); + // when + repository.save(Arrays.asList(sampleEntity1, sampleEntity2)); + // then + SampleEntity entity1FromElasticSearch = repository.findOne(documentId1); + assertThat(entity1FromElasticSearch, is(notNullValue())); - //when - repository.save(Arrays.asList(sampleEntity1, sampleEntity2)); - //then - SampleEntity entity1FromElasticSearch = repository.findOne(documentId1); - assertThat(entity1FromElasticSearch, is(notNullValue())); + SampleEntity entity2FromElasticSearch = repository.findOne(documentId2); + assertThat(entity2FromElasticSearch, is(notNullValue())); + } - SampleEntity entity2FromElasticSearch = repository.findOne(documentId2); - assertThat(entity2FromElasticSearch, is(notNullValue())); - } + @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 + SampleEntity entityFromElasticSearch = repository.findOne(documentId); + assertThat(entityFromElasticSearch, is(notNullValue())); + } - @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 - SampleEntity entityFromElasticSearch = repository.findOne(documentId); - assertThat(entityFromElasticSearch, is(notNullValue())); - } + @Test + public void shouldFindDocumentById() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); + // when + SampleEntity entityFromElasticSearch = repository.findOne(documentId); + // then + assertThat(entityFromElasticSearch, is(notNullValue())); + assertThat(sampleEntity, is((equalTo(sampleEntity)))); + } - @Test - public void shouldFindDocumentById(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); - //when - SampleEntity entityFromElasticSearch = repository.findOne(documentId); - //then - assertThat(entityFromElasticSearch, is(notNullValue())); - assertThat(sampleEntity, is((equalTo(sampleEntity)))); - } + @Test + public void shouldReturnCountOfDocuments() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); + // when + Long count = repository.count(); + // then + assertThat(count, is(greaterThanOrEqualTo(1L))); + } - @Test - public void shouldReturnCountOfDocuments(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); - //when - Long count = repository.count(); - //then - assertThat(count, is(greaterThanOrEqualTo(1L))); - } + @Test + public void shouldFindAllDocuments() { + // when + Iterable results = repository.findAll(); + // then + assertThat(results, is(notNullValue())); + } - @Test - public void shouldFindAllDocuments(){ - //when - Iterable results = repository.findAll(); - //then - assertThat(results, is(notNullValue())); - } + @Test + public void shouldDeleteDocument() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); + // when + repository.delete(documentId); + // then + SampleEntity entityFromElasticSearch = repository.findOne(documentId); + assertThat(entityFromElasticSearch, is(nullValue())); + } - @Test - public void shouldDeleteDocument(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); - //when - repository.delete(documentId); - //then - SampleEntity entityFromElasticSearch = repository.findOne(documentId); - assertThat(entityFromElasticSearch, is(nullValue())); - } + @Test + public void shouldSearchDocumentsGivenSearchQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("some test message"); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); - @Test - public void shouldSearchDocumentsGivenSearchQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("some test message"); - sampleEntity.setVersion(System.currentTimeMillis()); - 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))); + } - 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))); - } + @Test + public void shouldSearchDocumentsGivenElasticsearchQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("hello world."); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); + // when + Page page = repository.search(termQuery("message", "world"), new PageRequest(0, 50)); + // then + assertThat(page, is(notNullValue())); + assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1))); + } - @Test - public void shouldSearchDocumentsGivenElasticsearchQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("hello world."); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); - //when - Page page = repository.search(termQuery("message", "world"), new PageRequest(0,50)); - //then - assertThat(page, is(notNullValue())); - assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1))); - } + @Test + @Ignore + public void shouldFindAllByIdQuery() { + // todo : find solution for findAll(Iterable ids) + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("hello world."); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); - @Test - @Ignore - public void shouldFindAllByIdQuery(){ - //todo : find solution for findAll(Iterable ids) - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("hello world."); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("hello world."); + sampleEntity2.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity2); - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("hello world."); - sampleEntity2.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity2); + // when + Iterable sampleEntities = repository.findAll(Arrays.asList(documentId, documentId2)); - //when - Iterable sampleEntities=repository.findAll(Arrays.asList(documentId,documentId2)); + // then + assertNotNull("sample entities cant be null..", sampleEntities); + } - //then - assertNotNull("sample entities cant be null..", sampleEntities); - } + @Test + public void shouldSaveIterableEntities() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId); + sampleEntity1.setMessage("hello world."); + sampleEntity1.setVersion(System.currentTimeMillis()); - @Test - public void shouldSaveIterableEntities(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId); - sampleEntity1.setMessage("hello world."); - sampleEntity1.setVersion(System.currentTimeMillis()); + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("hello world."); + sampleEntity2.setVersion(System.currentTimeMillis()); - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("hello world."); - sampleEntity2.setVersion(System.currentTimeMillis()); + Iterable sampleEntities = Arrays.asList(sampleEntity1, sampleEntity2); + // when + repository.save(sampleEntities); + // then + Page entities = repository.search(fieldQuery("id", documentId), new PageRequest(0, 50)); + assertNotNull(entities); + } - Iterable sampleEntities = Arrays.asList(sampleEntity1,sampleEntity2); - //when - repository.save(sampleEntities); - //then - Page entities = repository.search(fieldQuery("id", documentId), new PageRequest(0, 50)); - assertNotNull(entities); - } + @Test + public void shouldReturnTrueGivenDocumentWithIdExists() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("hello world."); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); - @Test - public void shouldReturnTrueGivenDocumentWithIdExists(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("hello world."); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); + // when + boolean exist = repository.exists(documentId); - //when - boolean exist = repository.exists(documentId); + // then + assertEquals(exist, true); + } - //then - assertEquals(exist, true); - } + @Test + public void shouldReturnResultsForGivenSearchQuery() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("hello world."); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); + // when + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build(); + Page sampleEntities = repository.search(searchQuery); + // then + assertThat(sampleEntities.getTotalElements(), equalTo(1L)); + } - @Test - public void shouldReturnResultsForGivenSearchQuery(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("hello world."); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); - //when - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(fieldQuery("id",documentId)) - .build(); - Page sampleEntities= repository.search(searchQuery); - //then - assertThat(sampleEntities.getTotalElements(), equalTo(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)); + } - @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)); - } + @Test + public void shouldDeleteEntity() { + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("hello world."); + sampleEntity.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity); + // when + repository.delete(sampleEntity); + // then + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build(); + Page sampleEntities = repository.search(searchQuery); + assertThat(sampleEntities.getTotalElements(), equalTo(0L)); + } - @Test - public void shouldDeleteEntity(){ - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("hello world."); - sampleEntity.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity); - //when - repository.delete(sampleEntity); - //then - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(fieldQuery("id", documentId)) - .build(); - Page sampleEntities= repository.search(searchQuery); - assertThat(sampleEntities.getTotalElements(),equalTo(0L)); - } + @Test + public void shouldReturnIterableEntities() { + // given + String documentId1 = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId1); + sampleEntity1.setMessage("hello world."); + sampleEntity1.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity1); - @Test - public void shouldReturnIterableEntities(){ - //given - String documentId1 = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId1); - sampleEntity1.setMessage("hello world."); - sampleEntity1.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity1); + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("hello world."); + sampleEntity2.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity2); - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("hello world."); - sampleEntity2.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity2); + // when + Iterable sampleEntities = repository.search(fieldQuery("id", documentId1)); + // then + assertNotNull("sample entities cant be null..", sampleEntities); + } - //when - Iterable sampleEntities = repository.search(fieldQuery("id",documentId1)); - //then - assertNotNull("sample entities cant be null..", sampleEntities); - } + @Test + public void shouldDeleteIterableEntities() { + // given + String documentId1 = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setId(documentId1); + sampleEntity1.setMessage("hello world."); + sampleEntity1.setVersion(System.currentTimeMillis()); - @Test - public void shouldDeleteIterableEntities(){ - //given - String documentId1 = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setId(documentId1); - sampleEntity1.setMessage("hello world."); - sampleEntity1.setVersion(System.currentTimeMillis()); + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("hello world."); + sampleEntity2.setVersion(System.currentTimeMillis()); + repository.save(sampleEntity2); - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("hello world."); - sampleEntity2.setVersion(System.currentTimeMillis()); - repository.save(sampleEntity2); + Iterable sampleEntities = Arrays.asList(sampleEntity2, sampleEntity2); + // when + repository.delete(sampleEntities); + // then + assertThat(repository.findOne(documentId1), is(nullValue())); + assertThat(repository.findOne(documentId2), is(nullValue())); + } - Iterable sampleEntities = Arrays.asList(sampleEntity2,sampleEntity2); - //when - repository.delete(sampleEntities); - //then - assertThat(repository.findOne(documentId1),is(nullValue())); - assertThat(repository.findOne(documentId2),is(nullValue())); - } + @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(fieldQuery("id", documentId), new PageRequest(0, 50)); + assertThat(entities.getTotalElements(), equalTo(1L)); + } - @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(fieldQuery("id", documentId), new PageRequest(0,50)); - assertThat(entities.getTotalElements(),equalTo(1L)); - } + @Test + public void shouldSortByGivenField() { + // todo + // given + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage("world"); + repository.save(sampleEntity); - @Test - public void shouldSortByGivenField(){ - //todo - //given - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage("world"); - repository.save(sampleEntity); + String documentId2 = randomNumeric(5); + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setId(documentId2); + sampleEntity2.setMessage("hello"); + repository.save(sampleEntity2); + // when + Iterable sampleEntities = repository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC, "message"))); + // then + assertThat(sampleEntities, is(notNullValue())); + } - String documentId2 = randomNumeric(5); - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setId(documentId2); - sampleEntity2.setMessage("hello"); - repository.save(sampleEntity2); - //when - Iterable sampleEntities=repository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC,"message"))); - //then - assertThat(sampleEntities,is(notNullValue())); - } + @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," + + " we want a painless setup and a completely free search schema, we want to be able to index data simply using JSON over HTTP, " + + "we want our search server to be always available, we want to be able to start with one machine and scale to hundreds, " + + "we want real-time search, we want simple multi-tenancy, and we want a solution that is built for the cloud."; - @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," + - " we want a painless setup and a completely free search schema, we want to be able to index data simply using JSON over HTTP, " + - "we want our search server to be always available, we want to be able to start with one machine and scale to hundreds, " + - "we want real-time search, we want simple multi-tenancy, and we want a solution that is built for the cloud."; + List sampleEntities = createSampleEntitiesWithMessage(sampleMessage, 30); + repository.save(sampleEntities); + // when + SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(new PageRequest(0, 5)).withFields("message") + .build(); + Page results = repository.searchSimilar(sampleEntities.get(0), searchQuery); + // then + assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L))); + } - List sampleEntities = createSampleEntitiesWithMessage(sampleMessage, 30); - repository.save(sampleEntities); - - //when - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withPageable(new PageRequest(0, 5)) - .withFields("message") - .build(); - Page results = repository.searchSimilar(sampleEntities.get(0), searchQuery); - - //then - assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L))); - } - - private static List createSampleEntitiesWithMessage(String message, int numberOfEntities){ - List sampleEntities = new ArrayList(); - for(int i = 0; i < numberOfEntities; i++){ - String documentId = randomNumeric(5); - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage(message); - sampleEntity.setRate(2); - sampleEntity.setVersion(System.currentTimeMillis()); - sampleEntities.add(sampleEntity); - } - return sampleEntities; - } + private static List createSampleEntitiesWithMessage(String message, int numberOfEntities) { + List sampleEntities = new ArrayList(); + for (int i = 0; i < numberOfEntities; i++) { + String documentId = randomNumeric(5); + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage(message); + sampleEntity.setRate(2); + sampleEntity.setVersion(System.currentTimeMillis()); + sampleEntities.add(sampleEntity); + } + return sampleEntities; + } } diff --git a/src/test/resources/custom-method-repository-test.xml b/src/test/resources/custom-method-repository-test.xml index 7e3a90d08..6d4eaecc8 100644 --- a/src/test/resources/custom-method-repository-test.xml +++ b/src/test/resources/custom-method-repository-test.xml @@ -1,18 +1,20 @@ - + - - - + + + - + \ No newline at end of file diff --git a/src/test/resources/elasticsearch-template-test.xml b/src/test/resources/elasticsearch-template-test.xml index 0b6d3c367..c793b4809 100644 --- a/src/test/resources/elasticsearch-template-test.xml +++ b/src/test/resources/elasticsearch-template-test.xml @@ -1,14 +1,15 @@ - + - - - + + + \ No newline at end of file diff --git a/src/test/resources/infrastructure.xml b/src/test/resources/infrastructure.xml index 0d98dc975..747841218 100644 --- a/src/test/resources/infrastructure.xml +++ b/src/test/resources/infrastructure.xml @@ -1,10 +1,11 @@ - + \ No newline at end of file diff --git a/src/test/resources/org/springframework/data/elasticsearch/config/namespace.xml b/src/test/resources/org/springframework/data/elasticsearch/config/namespace.xml index 52d0d6d66..e16874b6e 100644 --- a/src/test/resources/org/springframework/data/elasticsearch/config/namespace.xml +++ b/src/test/resources/org/springframework/data/elasticsearch/config/namespace.xml @@ -5,15 +5,18 @@ xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + - - - + + + - + - + \ No newline at end of file diff --git a/src/test/resources/repository-non-document-entity.xml b/src/test/resources/repository-non-document-entity.xml index 30305f75f..85002d6b6 100644 --- a/src/test/resources/repository-non-document-entity.xml +++ b/src/test/resources/repository-non-document-entity.xml @@ -1,16 +1,17 @@ - + - - - + + + - + \ No newline at end of file diff --git a/src/test/resources/repository-test-nested-object.xml b/src/test/resources/repository-test-nested-object.xml index 30305f75f..85002d6b6 100644 --- a/src/test/resources/repository-test-nested-object.xml +++ b/src/test/resources/repository-test-nested-object.xml @@ -1,16 +1,17 @@ - + - - - + + + - + \ No newline at end of file diff --git a/src/test/resources/simple-repository-test.xml b/src/test/resources/simple-repository-test.xml index f120fc576..6d4eaecc8 100644 --- a/src/test/resources/simple-repository-test.xml +++ b/src/test/resources/simple-repository-test.xml @@ -1,18 +1,20 @@ - + - - - + + + - + \ No newline at end of file