diff --git a/README.md b/README.md index 9da07b465..2eb873e7b 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ Searching entities using Elasticsearch Template Indexing a single document with Repository ```java - @Resource + @Autowired private SampleElasticsearchRepository repository; String documentId = "123456"; @@ -147,7 +147,7 @@ Indexing a single document with Repository Indexing multiple Document(bulk index) using Repository ```java - @Resource + @Autowired private SampleElasticsearchRepository repository; String documentId = "123456"; @@ -371,6 +371,11 @@ Here are some ways for you to get involved in the community: Before we accept a non-trivial patch or pull request we will need you to sign the [contributor's agreement](https://support.springsource.com/spring_committer_signup). Signing the contributor's agreement does not grant anyone commit rights to the main repository, but it does mean that we can accept your contributions, and you will get an author credit if we do. Active contributors might be asked to join the core team, and given the ability to merge pull requests. + +Code formatting for [Eclipse and Intellij](https://github.com/spring-projects/spring-data-build/tree/master/etc/ide) + +[More information about contributing to Spring Data](https://github.com/spring-projects/spring-data-build/blob/master/CONTRIBUTING.md) + ### Contact Details * Rizwan Idrees (rizwan.idrees@biomedcentral.com) diff --git a/formatting.xml b/formatting.xml deleted file mode 100644 index b60c70a4e..000000000 --- a/formatting.xml +++ /dev/null @@ -1,820 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/pom.xml b/pom.xml index cff16b8af..ced57a14f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,6 @@ - + 4.0.0 org.springframework.data @@ -152,13 +153,13 @@ - - spring-plugins-release - http://repo.spring.io/plugins-release - - + + spring-plugins-release + http://repo.spring.io/plugins-release + + - + 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 diff --git a/src/docbkx/index.xml b/src/docbkx/index.xml index 05f60dde7..d5aff1fcd 100644 --- a/src/docbkx/index.xml +++ b/src/docbkx/index.xml @@ -1,62 +1,62 @@ + "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd"> - - Spring Data Elasticsearch - - - BioMed Central - Development Team - - - - - Copies of this document may be made for your own use and for - distribution to others, provided that you do not - charge any fee for - such copies and further provided that each copy - contains this - Copyright Notice, whether - distributed in print or electronically. - - + + Spring Data Elasticsearch + + + BioMed Central + Development Team + + + + + Copies of this document may be made for your own use and for + distribution to others, provided that you do not + charge any fee for + such copies and further provided that each copy + contains this + Copyright Notice, whether + distributed in print or electronically. + + - - 2013 - The original author(s) - - + + 2013 + The original author(s) + + - + - + - - Reference Documentation + + Reference Documentation - - - + + + - - - + + + - - Appendix - - - - - - - + + Appendix + + + + + + + \ No newline at end of file diff --git a/src/docbkx/preface.xml b/src/docbkx/preface.xml index 2872ded1c..a45737445 100644 --- a/src/docbkx/preface.xml +++ b/src/docbkx/preface.xml @@ -1,39 +1,40 @@ + "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd"> - Preface - The Spring Data Elasticsearch project applies core Spring - concepts to - the - 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. - -
- Project Metadata - - - - Version Control - - git://github.com/BioMedCentralLtd/spring-data-elasticsearch.git - - - - -
-
- Requirements - - Requires - Elasticsearch - 0.20.2 and above or optional dependency or not even that if you are - using Embedded Node Client - -
+ Preface + The Spring Data Elasticsearch project applies core Spring + concepts to + the + 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. + +
+ Project Metadata + + + + Version Control - + + git://github.com/BioMedCentralLtd/spring-data-elasticsearch.git + + + + +
+
+ Requirements + + Requires + Elasticsearch + 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 ee3460570..f983dd7e9 100644 --- a/src/docbkx/reference/data-elasticsearch.xml +++ b/src/docbkx/reference/data-elasticsearch.xml @@ -1,487 +1,508 @@ + "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd"> - Elasticsearch Repositories - - This chapter includes details of the Elasticsearch repository - implementation. - - -
- Introduction + Elasticsearch Repositories + + This chapter includes details of the Elasticsearch repository + implementation. + + +
+ Introduction -
- Spring Namespace +
+ Spring Namespace - - The Spring Data Elasticsearch module contains a custom namespace - allowing - definition of repository beans as well as elements for - instantiating - a - ElasticsearchServer - . - + + The Spring Data Elasticsearch module contains a custom namespace + allowing + definition of repository beans as well as elements for + instantiating + a + ElasticsearchServer + . + - - Using the - repositories - element looks up Spring Data repositories as described in - - . - + + Using the + repositories + element looks up Spring Data repositories as described in + + . + - - Setting up Elasticsearch repositories using Namespace - <?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" -xsi:schemaLocation="http://www.springframework.org/schema/beans -http://www.springframework.org/schema/beans/spring-beans-3.1.xsd -http://www.springframework.org/schema/data/elasticsearch -http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd"> + + Setting up Elasticsearch repositories using Namespace + <?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" + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans-3.1.xsd + http://www.springframework.org/schema/data/elasticsearch + http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd"> -<elasticsearch:repositories base-package="com.acme.repositories" /> -</beans> - + <elasticsearch:repositories base-package="com.acme.repositories" /> + </beans> + - - Using the - Transport Client - or - Node Client - element registers an instance of - Elasticsearch Server - in the context. + + Using the + Transport Client + or + Node Client + element registers an instance of + Elasticsearch Server + in the context. - - Transport Client using Namespace - <?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" -xsi:schemaLocation="http://www.springframework.org/schema/beans -http://www.springframework.org/schema/beans/spring-beans-3.1.xsd -http://www.springframework.org/schema/data/elasticsearch -http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd"> + + Transport Client using Namespace + <?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" + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans-3.1.xsd + http://www.springframework.org/schema/data/elasticsearch + http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd"> -<elasticsearch:transport-client id="client" cluster-nodes="localhost:9300,someip:9300" /> -</beans> - + <elasticsearch:transport-client id="client" cluster-nodes="localhost:9300,someip:9300" /> + </beans> + - - Node Client using Namespace - <?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" -xsi:schemaLocation="http://www.springframework.org/schema/beans -http://www.springframework.org/schema/beans/spring-beans-3.1.xsd -http://www.springframework.org/schema/data/elasticsearch -http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd"> + + Node Client using Namespace + <?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" + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans-3.1.xsd + http://www.springframework.org/schema/data/elasticsearch + http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd"> -<elasticsearch:node-client id="client" local="true"" /> -</beans> - - -
-
- Annotation based configuration - 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 - - -@Configuration -@EnableElasticsearchRepositories(basePackages = "org/springframework/data/elasticsearch/repositories") -static class Config { + <elasticsearch:node-client id="client" local="true"" /> + </beans> + + +
+
+ Annotation based configuration + 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 + + + @Configuration + @EnableElasticsearchRepositories(basePackages = + "org/springframework/data/elasticsearch/repositories") + static class Config { -@Bean -public ElasticsearchOperations elasticsearchTemplate() { -return new ElasticsearchTemplate(nodeBuilder().local(true).node().client()); - } -} - - The configuration above sets up an - Embedded Elasticsearch Server - which is used by the - ElasticsearchTemplate - . Spring Data Elasticsearch Repositories are activated using the - @EnableElasticsearchRepositories - annotation, which - essentially carries the same attributes as the XML - namespace does. If no - base package is configured, it will use the - one - the configuration class - resides in. - - -
-
- Elasticsearch Repositores using CDI - The Spring Data Elasticsearch repositories can also be set up - using CDI - functionality. - - - Spring Data Elasticsearch repositories using JavaConfig - - class ElasticsearchTemplateProducer { + @Bean + public ElasticsearchOperations elasticsearchTemplate() { + return new ElasticsearchTemplate(nodeBuilder().local(true).node().client()); + } + } + + + The configuration above sets up an + Embedded Elasticsearch Server + which is used by the + ElasticsearchTemplate + . Spring Data Elasticsearch Repositories are activated using the + @EnableElasticsearchRepositories + annotation, which + essentially carries the same attributes as the XML + namespace does. If no + base package is configured, it will use the + one + the configuration class + resides in. + + +
+
+ Elasticsearch Repositores using CDI + The Spring Data Elasticsearch repositories can also be set up + using CDI + functionality. + + + Spring Data Elasticsearch repositories using JavaConfig + + class ElasticsearchTemplateProducer { -@Produces -@ApplicationScoped -public ElasticsearchOperations createElasticsearchTemplate() { - return new ElasticsearchTemplate(nodeBuilder().local(true).node().client()); - } -} + @Produces + @ApplicationScoped + public ElasticsearchOperations createElasticsearchTemplate() { + return new ElasticsearchTemplate(nodeBuilder().local(true).node().client()); + } + } -class ProductService { + class ProductService { -private ProductRepository repository; + private ProductRepository repository; -public Page<Product> findAvailableBookByName(String name, Pageable pageable) { - return repository.findByAvailableTrueAndNameStartingWith(name, pageable); -} + public Page<Product> findAvailableBookByName(String name, Pageable pageable) { + return repository.findByAvailableTrueAndNameStartingWith(name, pageable); + } -@Inject -public void setRepository(ProductRepository repository) { - this.repository = repository; - } -} - -
-
-
- Query methods -
- Query lookup strategies - - The Elasticsearch module supports all basic query building - feature as String,Abstract,Criteria or - have - it being derived from the - method name. - + @Inject + public void setRepository(ProductRepository repository) { + this.repository = repository; + } + } + + +
+
+
+ Query methods +
+ Query lookup strategies + + The Elasticsearch module supports all basic query building + feature as String,Abstract,Criteria or + have + it being derived from the + method name. + - - Declared queries - - Deriving the query from the method name is not always sufficient - and/or may result in unreadable method names. In this case one - might make either use of - @Query - annotation (see - - ). - - -
+ + Declared queries + + Deriving the query from the method name is not always sufficient + and/or may result in unreadable method names. In this case one + might make either use of + @Query + annotation (see + + ). + + +
-
- Query creation +
+ Query creation - - Generally the query creation mechanism for Elasticsearch works as - described - in - - . Here's a short example - of what a Elasticsearch query method - translates into: - - Query creation from method names - public interface BookRepository extends Repository<Book, String> { - List<Book> findByNameAndPrice(String name, Integer price); -} - - The method name above will be translated into the following - Elasticsearch json query - - + + Generally the query creation mechanism for Elasticsearch works as + described + in + + . Here's a short example + of what a Elasticsearch query method + translates into: + + Query creation from method names + public interface BookRepository extends Repository<Book, String> + { + List<Book> findByNameAndPrice(String name, Integer price); + } + + + The method name above will be translated into the following + Elasticsearch json query + + { "bool" : { "must" : [ { "field" : {"name" : "?"} }, { "field" : {"price" : "?"} } - ] } } - - - - A list of supported keywords for Elasticsearch is shown below. - - Supported keywords inside method names - - - - - - - Keyword - Sample - Elasticsearch Query String - - - - - - And - - - findByNameAndPrice - - - {"bool" : {"must" : [ {"field" : {"name" : "?"}}, - {"field" : {"price" : "?"}} ]}} - - - - - Or - - - findByNameOrPrice - - - {"bool" : {"should" : [ {"field" : {"name" : "?"}}, - {"field" : {"price" : "?"}} ]}} - - - - - Is - - - findByName - - - {"bool" : {"must" : {"field" : {"name" : "?"}}}} - - - - - Not - - - findByNameNot - - - {"bool" : {"must_not" : {"field" : {"name" : "?"}}}} - - - - - - Between - - - findByPriceBetween - - - {"bool" : {"must" : {"range" : {"price" : {"from" : - ?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}} - - - - - - LessThanEqual - - - findByPriceLessThan - - - {"bool" : {"must" : {"range" : {"price" : {"from" : - null,"to" : ?,"include_lower" : true,"include_upper" : - true}}}}} - - - - - GreaterThanEqual - - - findByPriceGreaterThan - - - {"bool" : {"must" : {"range" : {"price" : {"from" : - ?,"to" : null,"include_lower" : true,"include_upper" : - true}}}}} - - - - - Before - - - findByPriceBefore - - - {"bool" : {"must" : {"range" : {"price" : {"from" : - null,"to" : ?,"include_lower" : true,"include_upper" : - true}}}}} - - - - - After - - - findByPriceAfter - - - {"bool" : {"must" : {"range" : {"price" : {"from" : - ?,"to" : null,"include_lower" : true,"include_upper" : - true}}}}} - - - - - Like - - - findByNameLike - - - {"bool" : {"must" : {"field" : {"name" : {"query" : - "?*","analyze_wildcard" : true}}}}} - - - - - StartingWith - - - findByNameStartingWith - - - {"bool" : {"must" : {"field" : {"name" : {"query" : - "?*","analyze_wildcard" : true}}}}} - - - - - EndingWith - - - findByNameEndingWith - - - {"bool" : {"must" : {"field" : {"name" : {"query" : - "*?","analyze_wildcard" : true}}}}} - - - - - Contains/Containing - - - findByNameContaining - - - {"bool" : {"must" : {"field" : {"name" : {"query" : - "*?*","analyze_wildcard" : true}}}}} - - - - - In - - - findByNameIn(Collection<String>names) - - - {"bool" : {"must" : {"bool" : {"should" : [ {"field" : - {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}} - - - - - NotIn - - - findByNameNotIn(Collection<String>names) - - - {"bool" : {"must_not" : {"bool" : {"should" : {"field" : - {"name" : "?"}}}}}} - - - - - Near - - - findByStoreNear - - - Not Supported Yet ! - - - - - True - - - findByAvailableTrue - - - {"bool" : {"must" : {"field" : {"available" : true}}}} - - - - - - False - - - findByAvailableFalse - - - {"bool" : {"must" : {"field" : {"available" : false}}}} - - - - - - OrderBy - - - findByAvailableTrueOrderByNameDesc - - - {"sort" : [{ "name" : {"order" : "desc"} }],"bool" : - {"must" : {"field" : {"available" : true}}}} - - - - -
-
-
-
- Using @Query Annotation - - - Declare query at the method using the - <interfacename>@Query</interfacename> - annotation. - + ] } } + + + + + A list of supported keywords for Elasticsearch is shown below. + + Supported keywords inside method names + + + + + + + Keyword + Sample + Elasticsearch Query String + + + + + + And + + + findByNameAndPrice + + + {"bool" : {"must" : [ {"field" : {"name" : "?"}}, + {"field" : {"price" : "?"}} ]}} + + + + + + Or + + + findByNameOrPrice + + + {"bool" : {"should" : [ {"field" : {"name" : "?"}}, + {"field" : {"price" : "?"}} ]}} + + + + + + Is + + + findByName + + + {"bool" : {"must" : {"field" : {"name" : "?"}}}} + + + + + Not + + + findByNameNot + + + {"bool" : {"must_not" : {"field" : {"name" : "?"}}}} + + + + + + Between + + + findByPriceBetween + + + {"bool" : {"must" : {"range" : {"price" : {"from" : + ?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}} + + + + + + LessThanEqual + + + findByPriceLessThan + + + {"bool" : {"must" : {"range" : {"price" : {"from" : + null,"to" : ?,"include_lower" : true,"include_upper" : + true}}}}} + + + + + + GreaterThanEqual + + + findByPriceGreaterThan + + + {"bool" : {"must" : {"range" : {"price" : {"from" : + ?,"to" : null,"include_lower" : true,"include_upper" : + true}}}}} + + + + + + Before + + + findByPriceBefore + + + {"bool" : {"must" : {"range" : {"price" : {"from" : + null,"to" : ?,"include_lower" : true,"include_upper" : + true}}}}} + + + + + + After + + + findByPriceAfter + + + {"bool" : {"must" : {"range" : {"price" : {"from" : + ?,"to" : null,"include_lower" : true,"include_upper" : + true}}}}} + + + + + + Like + + + findByNameLike + + + {"bool" : {"must" : {"field" : {"name" : {"query" : + "?*","analyze_wildcard" : true}}}}} + + + + + + StartingWith + + + findByNameStartingWith + + + {"bool" : {"must" : {"field" : {"name" : {"query" : + "?*","analyze_wildcard" : true}}}}} + + + + + + EndingWith + + + findByNameEndingWith + + + {"bool" : {"must" : {"field" : {"name" : {"query" : + "*?","analyze_wildcard" : true}}}}} + + + + + + Contains/Containing + + + findByNameContaining + + + {"bool" : {"must" : {"field" : {"name" : {"query" : + "*?*","analyze_wildcard" : true}}}}} + + + + + + In + + + findByNameIn(Collection<String>names) + + + {"bool" : {"must" : {"bool" : {"should" : [ {"field" : + {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}} + + + + + + NotIn + + + findByNameNotIn(Collection<String>names) + + + {"bool" : {"must_not" : {"bool" : {"should" : {"field" : + {"name" : "?"}}}}}} + + + + + + Near + + + findByStoreNear + + + Not Supported Yet ! + + + + + True + + + findByAvailableTrue + + + {"bool" : {"must" : {"field" : {"available" : true}}}} + + + + + + False + + + findByAvailableFalse + + + {"bool" : {"must" : {"field" : {"available" : false}}}} + + + + + + OrderBy + + + findByAvailableTrueOrderByNameDesc + + + {"sort" : [{ "name" : {"order" : "desc"} }],"bool" : + {"must" : {"field" : {"available" : true}}}} + + + + + +
+
+
+
+ Using @Query Annotation + + + Declare query at the method using the + <interfacename>@Query</interfacename> + annotation. + - public interface BookRepository extends ElasticsearchRepository<Book, String> { - @Query("{"bool" : {"must" : {"field" : {"name" : "?0"}}}}") - Page<Book> findByName(String name,Pageable pageable); -} - -
+ public interface BookRepository extends ElasticsearchRepository<Book, + String> { + @Query("{"bool" : {"must" : {"field" : {"name" : "?0"}}}}") + Page<Book> findByName(String name,Pageable pageable); + } + + +
-
+
\ No newline at end of file diff --git a/src/docbkx/reference/elasticsearch-misc.xml b/src/docbkx/reference/elasticsearch-misc.xml index 78aece686..78096a523 100644 --- a/src/docbkx/reference/elasticsearch-misc.xml +++ b/src/docbkx/reference/elasticsearch-misc.xml @@ -1,85 +1,88 @@ + "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd"> - Miscellaneous Elasticsearch Operation Support - - - This chapter covers additional support for Elasticsearch operations - that cannot be directly accessed via the repository - interface. - It is - recommended to add those operations as custom - implementation as - described in - - . - - -
- Filter Builder - - Filter Builder improves query speed. - - - -private ElasticsearchTemplate elasticsearchTemplate; -SearchQuery searchQuery = new NativeSearchQueryBuilder() -.withQuery(matchAllQuery()) -.withFilter(boolFilter().must(termFilter("id", documentId))) -.build(); -Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); - - -
-
- 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") -.withTypes("test-type") -.withPageable(new PageRequest(0,1)) -.build(); -String scrollId = elasticsearchTemplate.scan(searchQuery,1000,false); -List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>(); -boolean hasRecords = true; -while (hasRecords){ -Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L , new ResultsMapper<SampleEntity>() { -@Override -public Page<SampleEntity> mapResults(SearchResponse response) { -List<SampleEntity> chunk = new ArrayList<SampleEntity>(); -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<SampleEntity>(chunk); -} - }); - if(page != null) { - sampleEntities.addAll(page.getContent()); - hasRecords = page.hasNextPage(); - } - else{ - hasRecords = false; - } - } -} - -
+ Miscellaneous Elasticsearch Operation Support + + + This chapter covers additional support for Elasticsearch operations + that cannot be directly accessed via the repository + interface. + It is + recommended to add those operations as custom + implementation as + described in + + . + + +
+ Filter Builder + + Filter Builder improves query speed. + + + + private ElasticsearchTemplate elasticsearchTemplate; + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(matchAllQuery()) + .withFilter(boolFilter().must(termFilter("id", documentId))) + .build(); + Page<SampleEntity> sampleEntities = + elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); + + +
+
+ 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") + .withTypes("test-type") + .withPageable(new PageRequest(0,1)) + .build(); + String scrollId = elasticsearchTemplate.scan(searchQuery,1000,false); + List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>(); + boolean hasRecords = true; + while (hasRecords){ + Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L , new ResultsMapper<SampleEntity>() + { + @Override + public Page<SampleEntity> mapResults(SearchResponse response) { + List<SampleEntity> chunk = new ArrayList<SampleEntity>(); + 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<SampleEntity>(chunk); + } + }); + if(page != null) { + sampleEntities.addAll(page.getContent()); + hasRecords = page.hasNextPage(); + } + else{ + hasRecords = false; + } + } + } + + +
\ No newline at end of file diff --git a/src/docbkx/reference/repositories.xml b/src/docbkx/reference/repositories.xml index b473c297e..25206728d 100644 --- a/src/docbkx/reference/repositories.xml +++ b/src/docbkx/reference/repositories.xml @@ -2,89 +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); @@ -100,109 +100,116 @@ boolean exists(ID primaryKey); // … 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 - Page<User> users = repository.findAll(new PageRequest(1, 20)); -
+ 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" @@ -215,87 +222,89 @@ </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; 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); } @@ -303,308 +312,314 @@ interface UserRepository extends MyBaseRepository<User, Long> { 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 - User - s by their email address. - -
-
- -
- Defining query methods - -
- 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. - - - - 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 - - - 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 - - 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) - - - 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 - - - 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 - - - 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. - - -
- 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 - Person - s have - Address - es - with - ZipCode - s. In that case a method name - of - - - 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 - ). - - - - 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); + } -
-
+ -
- Special parameter handling + + 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. + +
+
- 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. - +
+ Defining query methods - - Using Pageable and Sort in query methods +
+ Query lookup strategies - Page<User> findByLastname(String lastname, Pageable pageable); + 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: + + + + 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 + + . + + + + + 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. + + + + + 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. + + +
+ +
+ 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 + . + + + + Query creation from method names + + + 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. + + +
+ 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 + Person + s have + Address + es + with + ZipCode + s. In that case a method name + of + + + 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 + ). + + + + 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); + +
+
+ +
+ 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. + + + + Using Pageable and Sort in query methods + + Page<User> findByLastname(String lastname, Pageable pageable); List<User> findByLastname(String lastname, Sort sort); - List<User> findByLastname(String lastname, Pageable pageable); - + 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" @@ -617,109 +632,110 @@ </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 { @@ -727,232 +743,240 @@ public EntityManagerFactory entityManagerFactory() { // … } - } - + } + + - - 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 - UserRepository repository = factory.getRepository(UserRepository.class); - -
-
-
+ 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 - - - 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. - - + + - - Changes to the your basic repository interface + + Implementation of custom repository functionality - - public interface UserRepository extends CrudRepository<User, Long>, UserRepositoryCustom { + + class UserRepositoryImpl implements UserRepositoryCustom { - // Declare query methods here - } - Let your standard repository interface extend the custom - one. This makes CRUD and custom functionality available to - clients. - - + 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. + + - - Configuration + + Changes to the your basic repository interface - - 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 - . - + + public interface UserRepository extends CrudRepository<User, Long>, + UserRepositoryCustom { - - Configuration example + // Declare query methods here + } + + Let your standard repository interface extend the custom + one. This makes CRUD and custom functionality available to + clients. + + - - <repositories base-package="com.acme.repository" /> + + Configuration - <repositories base-package="com.acme.repository" repository-impl-postfix="FooBar" /> - - + + 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 + . + - - 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 - . - - + + Configuration example - - Manual wiring + + <repositories base-package="com.acme.repository" /> - 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. - + <repositories base-package="com.acme.repository" repository-impl-postfix="FooBar" + /> + + - - Manual wiring of custom implementations (I) + + 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 + . + + - <repositories base-package="com.acme.repository" /> + + 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. + + + + Manual wiring of custom implementations (I) + + <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> { + + + public interface MyRepository<T, ID extends Serializable> + extends JpaRepository<T, ID> { - void sharedCustomMethod(ID 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> { @@ -969,32 +993,34 @@ public void sharedCustomMethod(ID id) { // 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> + + public class MyRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends + Serializable> extends JpaRepositoryFactoryBean<R, T, I> { protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { @@ -1002,7 +1028,8 @@ return new MyRepositoryFactory(entityManager); } - private static class MyRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory { + private static class MyRepositoryFactory<T, I extends Serializable> extends + JpaRepositoryFactory { private EntityManager entityManager; @@ -1024,49 +1051,50 @@ return MyRepository.class; } } - } - + } + + - - 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 { @@ -1085,41 +1113,43 @@ // Populate model return "user"; } - } + } + - - 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 - 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 - + + 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"> @@ -1129,12 +1159,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 { @@ -1145,33 +1175,34 @@ // Populate model 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 - 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: - + + 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"> @@ -1182,13 +1213,13 @@ </list> </property> </bean> - -
+ +
-
- Web pagination +
+ Web pagination - @Controller + @Controller @RequestMapping("/users") public class UserController { @@ -1202,24 +1233,25 @@ model.addAttribute("users", userService.getUsers(pageable)); return "users"; } - } + } + - - 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" /> @@ -1227,11 +1259,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 { @@ -1241,168 +1273,170 @@ model.addAttribute("users", userDao.readAll(pageable)); return "users"; } - } + } + - - 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 - 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: - + + 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" } ] - + "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" @@ -1414,33 +1448,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" @@ -1452,12 +1486,13 @@ http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd"> - <repository:unmarshaller-populator location="classpath:data.json" unmarshaller-ref="unmarshaller" /> + <repository:unmarshaller-populator location="classpath:data.json" unmarshaller-ref="unmarshaller" + /> <oxm:jaxb2-marshaller contextPath="com.acme" /> </beans> - -
-
+ +
+
\ 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 ba64746c4..b3b0ddb20 100644 --- a/src/main/java/org/springframework/data/elasticsearch/ElasticsearchException.java +++ b/src/main/java/org/springframework/data/elasticsearch/ElasticsearchException.java @@ -19,7 +19,7 @@ import java.util.Map; /** * ElasticsearchException - * + * * @author Rizwan Idrees * @author Mohsin Husen */ diff --git a/src/main/java/org/springframework/data/elasticsearch/annotations/DateFormat.java b/src/main/java/org/springframework/data/elasticsearch/annotations/DateFormat.java index 55ed5d9ed..056dc1482 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/DateFormat.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/DateFormat.java @@ -17,16 +17,15 @@ package org.springframework.data.elasticsearch.annotations; /** * @author Jakub Vavrik - * - * Values based on reference doc - http://www.elasticsearch.org/guide/reference/mapping/date-format/ + * Values based on reference doc - http://www.elasticsearch.org/guide/reference/mapping/date-format/ */ public enum DateFormat { - none, custom, basic_date, basic_date_time, basic_date_time_no_millis, basic_ordinal_date, basic_ordinal_date_time, - basic_ordinal_date_time_no_millis, basic_time, basic_time_no_millis, basic_t_time, basic_t_time_no_millis, - basic_week_date, basic_week_date_time, basic_week_date_time_no_millis, date, date_hour, date_hour_minute, - date_hour_minute_second, date_hour_minute_second_fraction, date_hour_minute_second_millis, date_optional_time, - date_time, date_time_no_millis, hour, hour_minute, hour_minute_second, hour_minute_second_fraction, - hour_minute_second_millis, ordinal_date, ordinal_date_time, ordinal_date_time_no_millis, time, time_no_millis, - t_time, t_time_no_millis, week_date, week_date_time, weekDateTimeNoMillis, week_year, weekyearWeek, - weekyearWeekDay, year, year_month, year_month_day + none, custom, basic_date, basic_date_time, basic_date_time_no_millis, basic_ordinal_date, basic_ordinal_date_time, + basic_ordinal_date_time_no_millis, basic_time, basic_time_no_millis, basic_t_time, basic_t_time_no_millis, + basic_week_date, basic_week_date_time, basic_week_date_time_no_millis, date, date_hour, date_hour_minute, + date_hour_minute_second, date_hour_minute_second_fraction, date_hour_minute_second_millis, date_optional_time, + date_time, date_time_no_millis, hour, hour_minute, hour_minute_second, hour_minute_second_fraction, + hour_minute_second_millis, ordinal_date, ordinal_date_time, ordinal_date_time_no_millis, time, time_no_millis, + t_time, t_time_no_millis, week_date, week_date_time, weekDateTimeNoMillis, week_year, weekyearWeek, + weekyearWeekDay, year, year_month, year_month_day } 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 4299759f4..ef32e7e38 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/Document.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/Document.java @@ -15,13 +15,13 @@ */ package org.springframework.data.elasticsearch.annotations; -import org.springframework.data.annotation.Persistent; - import java.lang.annotation.*; +import org.springframework.data.annotation.Persistent; + /** * Document - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -29,7 +29,7 @@ import java.lang.annotation.*; @Persistent @Inherited @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE }) +@Target({ElementType.TYPE}) public @interface Document { String indexName(); 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 727d213a9..708fa8b0d 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/Field.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/Field.java @@ -29,20 +29,19 @@ import java.lang.annotation.*; @Documented public @interface Field { - FieldType type() default FieldType.Auto; + FieldType type() default FieldType.Auto; - FieldIndex index() default FieldIndex.analyzed; + FieldIndex index() default FieldIndex.analyzed; - DateFormat format() default DateFormat.none; + DateFormat format() default DateFormat.none; - String pattern() default ""; + String pattern() default ""; - boolean store() default false; + boolean store() default false; - String searchAnalyzer() default ""; + String searchAnalyzer() default ""; - String indexAnalyzer() default ""; - - String [] ignoreFields() default {}; + String indexAnalyzer() default ""; + String[] ignoreFields() default {}; } diff --git a/src/main/java/org/springframework/data/elasticsearch/annotations/FieldIndex.java b/src/main/java/org/springframework/data/elasticsearch/annotations/FieldIndex.java index deeff821d..9eee6423b 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/FieldIndex.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/FieldIndex.java @@ -20,5 +20,5 @@ package org.springframework.data.elasticsearch.annotations; * @author Mohsin Husen */ public enum FieldIndex { - not_analyzed, analyzed + not_analyzed, analyzed } diff --git a/src/main/java/org/springframework/data/elasticsearch/annotations/FieldType.java b/src/main/java/org/springframework/data/elasticsearch/annotations/FieldType.java index a8a6860d8..38062bfa6 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/FieldType.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/FieldType.java @@ -21,5 +21,5 @@ package org.springframework.data.elasticsearch.annotations; * @author Artur Konczak */ public enum FieldType { - String, Integer, Long, Date, Float, Double, Boolean, Object, Auto, Nested + String, Integer, Long, Date, Float, Double, Boolean, Object, Auto, Nested } diff --git a/src/main/java/org/springframework/data/elasticsearch/annotations/MultiField.java b/src/main/java/org/springframework/data/elasticsearch/annotations/MultiField.java index 54e865d73..41c781e80 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/MultiField.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/MultiField.java @@ -28,7 +28,7 @@ import java.lang.annotation.*; @Documented public @interface MultiField { - public Field mainField(); + public Field mainField(); - public NestedField[] otherFields() default {}; + public NestedField[] otherFields() default {}; } diff --git a/src/main/java/org/springframework/data/elasticsearch/annotations/NestedField.java b/src/main/java/org/springframework/data/elasticsearch/annotations/NestedField.java index 45a64f177..7a7f001f8 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/NestedField.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/NestedField.java @@ -27,15 +27,15 @@ import java.lang.annotation.Target; @Target(ElementType.FIELD) public @interface NestedField { - String dotSuffix(); + String dotSuffix(); - FieldType type(); + FieldType type(); - FieldIndex index() default FieldIndex.analyzed; + FieldIndex index() default FieldIndex.analyzed; - boolean store() default false; + boolean store() default false; - String searchAnalyzer() default ""; + String searchAnalyzer() default ""; - String indexAnalyzer() default ""; + String indexAnalyzer() default ""; } diff --git a/src/main/java/org/springframework/data/elasticsearch/annotations/Parent.java b/src/main/java/org/springframework/data/elasticsearch/annotations/Parent.java index a0208ad7b..940e6f04f 100644 --- a/src/main/java/org/springframework/data/elasticsearch/annotations/Parent.java +++ b/src/main/java/org/springframework/data/elasticsearch/annotations/Parent.java @@ -21,7 +21,7 @@ import org.springframework.data.annotation.Persistent; /** * Parent - * + * * @author Philipp Jardas */ @@ -30,5 +30,6 @@ import org.springframework.data.annotation.Persistent; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Parent { + String type(); } 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 cc78366f5..3c91cdf29 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 */ @@ -31,16 +31,15 @@ public @interface Query { /** * 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 ""; - } 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 c90f952c0..8caa15841 100644 --- a/src/main/java/org/springframework/data/elasticsearch/client/NodeClientFactoryBean.java +++ b/src/main/java/org/springframework/data/elasticsearch/client/NodeClientFactoryBean.java @@ -15,6 +15,8 @@ */ package org.springframework.data.elasticsearch.client; +import static org.elasticsearch.node.NodeBuilder.*; + import org.elasticsearch.client.Client; import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.settings.ImmutableSettings; @@ -24,11 +26,9 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; -import static org.elasticsearch.node.NodeBuilder.nodeBuilder; - /** * NodeClientFactoryBean - * + * * @author Rizwan Idrees * @author Mohsin Husen */ 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 bd3294f26..6d03216ee 100644 --- a/src/main/java/org/springframework/data/elasticsearch/client/TransportClientFactoryBean.java +++ b/src/main/java/org/springframework/data/elasticsearch/client/TransportClientFactoryBean.java @@ -15,6 +15,11 @@ */ package org.springframework.data.elasticsearch.client; +import static org.apache.commons.lang.StringUtils.*; +import static org.elasticsearch.common.settings.ImmutableSettings.*; + +import java.util.Properties; + import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.InetSocketTransportAddress; @@ -25,11 +30,6 @@ import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; -import java.util.Properties; - -import static org.apache.commons.lang.StringUtils.*; -import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; - /** * TransportClientFactoryBean * @@ -40,114 +40,114 @@ import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilde public class TransportClientFactoryBean implements FactoryBean, InitializingBean, DisposableBean { - private static final Logger logger = LoggerFactory.getLogger(TransportClientFactoryBean.class); - private String clusterNodes; - private String clusterName; - private Boolean clientTransportSniff; - private Boolean clientIgnoreClusterName = Boolean.FALSE; - private String clientPingTimeout = "5s"; - private String clientNodesSamplerInterval = "5s"; - private TransportClient client; - private Properties properties; - static final String COLON = ":"; - static final String COMMA = ","; + private static final Logger logger = LoggerFactory.getLogger(TransportClientFactoryBean.class); + private String clusterNodes; + private String clusterName; + private Boolean clientTransportSniff; + private Boolean clientIgnoreClusterName = Boolean.FALSE; + private String clientPingTimeout = "5s"; + private String clientNodesSamplerInterval = "5s"; + private TransportClient client; + private Properties properties; + static final String COLON = ":"; + static final String COMMA = ","; - @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.hasText(clusterNodes, "[Assertion failed] clusterNodes settings missing."); - for (String clusterNode : split(clusterNodes,COMMA)) { - 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.hasText(clusterNodes, "[Assertion failed] clusterNodes settings missing."); + for (String clusterNode : split(clusterNodes, COMMA)) { + 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("cluster.name", clusterName) - .put("client.transport.sniff", clientTransportSniff) - .put("client.transport.ignore_cluster_name", clientIgnoreClusterName) - .put("client.transport.ping_timeout", clientPingTimeout) - .put("client.transport.nodes_sampler_interval", clientNodesSamplerInterval) - .build(); - } + private Settings settings() { + if (properties != null) { + return settingsBuilder().put(properties).build(); + } + return settingsBuilder() + .put("cluster.name", clusterName) + .put("client.transport.sniff", clientTransportSniff) + .put("client.transport.ignore_cluster_name", clientIgnoreClusterName) + .put("client.transport.ping_timeout", clientPingTimeout) + .put("client.transport.nodes_sampler_interval", clientNodesSamplerInterval) + .build(); + } - public void setClusterNodes(String clusterNodes) { - this.clusterNodes = clusterNodes; - } + public void setClusterNodes(String clusterNodes) { + this.clusterNodes = clusterNodes; + } - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } - public void setClientTransportSniff(Boolean clientTransportSniff) { - this.clientTransportSniff = clientTransportSniff; - } + public void setClientTransportSniff(Boolean clientTransportSniff) { + this.clientTransportSniff = clientTransportSniff; + } - public String getClientNodesSamplerInterval() { - return clientNodesSamplerInterval; - } + public String getClientNodesSamplerInterval() { + return clientNodesSamplerInterval; + } - public void setClientNodesSamplerInterval(String clientNodesSamplerInterval) { - this.clientNodesSamplerInterval = clientNodesSamplerInterval; - } + public void setClientNodesSamplerInterval(String clientNodesSamplerInterval) { + this.clientNodesSamplerInterval = clientNodesSamplerInterval; + } - public String getClientPingTimeout() { - return clientPingTimeout; - } + public String getClientPingTimeout() { + return clientPingTimeout; + } - public void setClientPingTimeout(String clientPingTimeout) { - this.clientPingTimeout = clientPingTimeout; - } + public void setClientPingTimeout(String clientPingTimeout) { + this.clientPingTimeout = clientPingTimeout; + } - public Boolean getClientIgnoreClusterName() { - return clientIgnoreClusterName; - } + public Boolean getClientIgnoreClusterName() { + return clientIgnoreClusterName; + } - public void setClientIgnoreClusterName(Boolean clientIgnoreClusterName) { - this.clientIgnoreClusterName = clientIgnoreClusterName; - } + public void setClientIgnoreClusterName(Boolean clientIgnoreClusterName) { + this.clientIgnoreClusterName = clientIgnoreClusterName; + } - 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 011ed164f..bfb65686a 100644 --- a/src/main/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandler.java +++ b/src/main/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandler.java @@ -22,7 +22,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi /** * ElasticsearchNamespaceHandler - * + * * @author Rizwan Idrees * @author Mohsin Husen */ 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 387032fcd..909ccfbbc 100644 --- a/src/main/java/org/springframework/data/elasticsearch/config/NodeClientBeanDefinitionParser.java +++ b/src/main/java/org/springframework/data/elasticsearch/config/NodeClientBeanDefinitionParser.java @@ -25,7 +25,7 @@ import org.w3c.dom.Element; /** * NodeClientBeanDefinitionParser - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -46,7 +46,7 @@ public class NodeClientBeanDefinitionParser extends AbstractBeanDefinitionParser } private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source, - ParserContext context) { + 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 b00451637..54679fa30 100644 --- a/src/main/java/org/springframework/data/elasticsearch/config/TransportClientBeanDefinitionParser.java +++ b/src/main/java/org/springframework/data/elasticsearch/config/TransportClientBeanDefinitionParser.java @@ -22,11 +22,9 @@ import org.springframework.beans.factory.xml.ParserContext; import org.springframework.data.elasticsearch.client.TransportClientFactoryBean; import org.w3c.dom.Element; -import static org.apache.commons.lang.StringUtils.split; - /** * TransportClientBeanDefinitionParser - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -42,15 +40,15 @@ public class TransportClientBeanDefinitionParser extends AbstractBeanDefinitionP private void setConfigurations(Element element, BeanDefinitionBuilder builder) { builder.addPropertyValue("clusterNodes", element.getAttribute("cluster-nodes")); - builder.addPropertyValue("clusterName", element.getAttribute("cluster-name")); - builder.addPropertyValue("clientTransportSniff", Boolean.valueOf(element.getAttribute("client-transport-sniff"))); - builder.addPropertyValue("clientIgnoreClusterName", Boolean.valueOf(element.getAttribute("client-transport-ignore-cluster-name"))); - builder.addPropertyValue("clientPingTimeout", element.getAttribute("client-transport-ping-timeout")); - builder.addPropertyValue("clientNodesSamplerInterval", element.getAttribute("client-transport-nodes-sampler-interval")); + builder.addPropertyValue("clusterName", element.getAttribute("cluster-name")); + builder.addPropertyValue("clientTransportSniff", Boolean.valueOf(element.getAttribute("client-transport-sniff"))); + builder.addPropertyValue("clientIgnoreClusterName", Boolean.valueOf(element.getAttribute("client-transport-ignore-cluster-name"))); + builder.addPropertyValue("clientPingTimeout", element.getAttribute("client-transport-ping-timeout")); + builder.addPropertyValue("clientNodesSamplerInterval", element.getAttribute("client-transport-nodes-sampler-interval")); } private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source, - ParserContext context) { + ParserContext context) { AbstractBeanDefinition definition = builder.getBeanDefinition(); definition.setSource(context.extractSource(source)); return definition; diff --git a/src/main/java/org/springframework/data/elasticsearch/core/AbstractResultMapper.java b/src/main/java/org/springframework/data/elasticsearch/core/AbstractResultMapper.java index 30d507a5d..0f8a16829 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/AbstractResultMapper.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/AbstractResultMapper.java @@ -15,36 +15,36 @@ */ package org.springframework.data.elasticsearch.core; -import org.springframework.data.elasticsearch.ElasticsearchException; +import static org.apache.commons.lang.StringUtils.*; import java.io.IOException; -import static org.apache.commons.lang.StringUtils.isBlank; +import org.springframework.data.elasticsearch.ElasticsearchException; /** * @author Artur Konczak */ public abstract class AbstractResultMapper implements ResultsMapper { - private EntityMapper entityMapper; + private EntityMapper entityMapper; - public AbstractResultMapper(EntityMapper entityMapper) { - this.entityMapper = entityMapper; - } + public AbstractResultMapper(EntityMapper entityMapper) { + this.entityMapper = entityMapper; + } - public T mapEntity(String source, Class clazz) { - if (isBlank(source)) { - return null; - } - try { - return entityMapper.mapToObject(source, clazz); - } catch (IOException e) { - throw new ElasticsearchException("failed to map source [ " + source + "] to class " + clazz.getSimpleName(), e); - } - } + public T mapEntity(String source, Class clazz) { + if (isBlank(source)) { + return null; + } + try { + return entityMapper.mapToObject(source, clazz); + } catch (IOException e) { + throw new ElasticsearchException("failed to map source [ " + source + "] to class " + clazz.getSimpleName(), e); + } + } - @Override - public EntityMapper getEntityMapper() { - return this.entityMapper; - } + @Override + public EntityMapper getEntityMapper() { + return this.entityMapper; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/CriteriaFilterProcessor.java b/src/main/java/org/springframework/data/elasticsearch/core/CriteriaFilterProcessor.java index 5f9c26ae1..fde394713 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/CriteriaFilterProcessor.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/CriteriaFilterProcessor.java @@ -15,19 +15,21 @@ */ package org.springframework.data.elasticsearch.core; -import org.elasticsearch.index.query.*; -import org.springframework.data.elasticsearch.core.geo.GeoBox; -import org.springframework.data.elasticsearch.core.geo.GeoPoint; -import org.springframework.data.elasticsearch.core.query.Criteria; -import org.springframework.util.Assert; +import static org.elasticsearch.index.query.FilterBuilders.*; +import static org.springframework.data.elasticsearch.core.query.Criteria.*; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; -import static org.elasticsearch.index.query.FilterBuilders.*; -import static org.springframework.data.elasticsearch.core.query.Criteria.OperationKey; +import org.elasticsearch.index.query.FilterBuilder; +import org.elasticsearch.index.query.GeoBoundingBoxFilterBuilder; +import org.elasticsearch.index.query.GeoDistanceFilterBuilder; +import org.springframework.data.elasticsearch.core.geo.GeoBox; +import org.springframework.data.elasticsearch.core.geo.GeoPoint; +import org.springframework.data.elasticsearch.core.query.Criteria; +import org.springframework.util.Assert; /** * CriteriaFilterProcessor @@ -37,160 +39,158 @@ import static org.springframework.data.elasticsearch.core.query.Criteria.Operati class CriteriaFilterProcessor { - FilterBuilder createFilterFromCriteria(Criteria criteria) { - List fbList = new LinkedList(); - FilterBuilder filter = null; + FilterBuilder createFilterFromCriteria(Criteria criteria) { + List fbList = new LinkedList(); + FilterBuilder filter = null; - ListIterator chainIterator = criteria.getCriteriaChain().listIterator(); + ListIterator chainIterator = criteria.getCriteriaChain().listIterator(); - while (chainIterator.hasNext()) { - FilterBuilder fb = null; - Criteria chainedCriteria = chainIterator.next(); - if (chainedCriteria.isOr()) { - fb = orFilter(createFilterFragmentForCriteria(chainedCriteria).toArray(new FilterBuilder[]{})); - fbList.add(fb); - } else if (chainedCriteria.isNegating()) { - List negationFilters = buildNegationFilter(criteria.getField().getName(), criteria.getFilterCriteriaEntries().iterator()); + while (chainIterator.hasNext()) { + FilterBuilder fb = null; + Criteria chainedCriteria = chainIterator.next(); + if (chainedCriteria.isOr()) { + fb = orFilter(createFilterFragmentForCriteria(chainedCriteria).toArray(new FilterBuilder[]{})); + fbList.add(fb); + } else if (chainedCriteria.isNegating()) { + List negationFilters = buildNegationFilter(criteria.getField().getName(), criteria.getFilterCriteriaEntries().iterator()); - if (!negationFilters.isEmpty()) { - fbList.addAll(negationFilters); - } - } else { - fbList.addAll(createFilterFragmentForCriteria(chainedCriteria)); - } - } + if (!negationFilters.isEmpty()) { + fbList.addAll(negationFilters); + } + } else { + fbList.addAll(createFilterFragmentForCriteria(chainedCriteria)); + } + } - if (!fbList.isEmpty()) { - if (fbList.size() == 1) { - filter = fbList.get(0); - } else { - filter = andFilter(fbList.toArray(new FilterBuilder[]{})); - } - } + if (!fbList.isEmpty()) { + if (fbList.size() == 1) { + filter = fbList.get(0); + } else { + filter = andFilter(fbList.toArray(new FilterBuilder[]{})); + } + } - return filter; - } + return filter; + } - private List createFilterFragmentForCriteria(Criteria chainedCriteria) { - Iterator it = chainedCriteria.getFilterCriteriaEntries().iterator(); - List filterList = new LinkedList(); + private List createFilterFragmentForCriteria(Criteria chainedCriteria) { + Iterator it = chainedCriteria.getFilterCriteriaEntries().iterator(); + List filterList = new LinkedList(); - String fieldName = chainedCriteria.getField().getName(); - Assert.notNull(fieldName, "Unknown field"); - FilterBuilder filter = null; + String fieldName = chainedCriteria.getField().getName(); + Assert.notNull(fieldName, "Unknown field"); + FilterBuilder filter = null; - while (it.hasNext()) { - Criteria.CriteriaEntry entry = it.next(); - filter = processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName); - filterList.add(filter); - } + while (it.hasNext()) { + Criteria.CriteriaEntry entry = it.next(); + filter = processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName); + filterList.add(filter); + } - return filterList; - } + return filterList; + } - private FilterBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) { - if (value == null) { - return null; - } - FilterBuilder filter = null; + private FilterBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) { + if (value == null) { + return null; + } + FilterBuilder filter = null; - switch (key) { - case WITHIN: { - filter = geoDistanceFilter(fieldName); + switch (key) { + case WITHIN: { + filter = geoDistanceFilter(fieldName); - Assert.isTrue(value instanceof Object[], "Value of a geo distance filter should be an array of two values."); - Object[] valArray = (Object[]) value; - Assert.noNullElements(valArray, "Geo distance filter takes 2 not null elements array as parameter."); - Assert.isTrue(valArray.length == 2, "Geo distance filter takes a 2-elements array as parameter."); - Assert.isTrue(valArray[0] instanceof GeoPoint || valArray[0] instanceof String, "First element of a geo distance filter must be a GeoLocation or String"); - Assert.isTrue(valArray[1] instanceof String, "Second element of a geo distance filter must be a String"); + Assert.isTrue(value instanceof Object[], "Value of a geo distance filter should be an array of two values."); + Object[] valArray = (Object[]) value; + Assert.noNullElements(valArray, "Geo distance filter takes 2 not null elements array as parameter."); + Assert.isTrue(valArray.length == 2, "Geo distance filter takes a 2-elements array as parameter."); + Assert.isTrue(valArray[0] instanceof GeoPoint || valArray[0] instanceof String, "First element of a geo distance filter must be a GeoLocation or String"); + Assert.isTrue(valArray[1] instanceof String, "Second element of a geo distance filter must be a String"); - String dist = (String) valArray[1]; - if (valArray[0] instanceof GeoPoint) { - GeoPoint loc = (GeoPoint) valArray[0]; - ((GeoDistanceFilterBuilder) filter).lat(loc.getLat()).lon(loc.getLon()).distance(dist); - } else { - String loc = (String) valArray[0]; - if (loc.contains(",")) { - String c[] = loc.split(","); - ((GeoDistanceFilterBuilder) filter).lat(Double.parseDouble(c[0])).lon(Double.parseDouble(c[1])).distance(dist); - } else { - ((GeoDistanceFilterBuilder) filter).geohash(loc).distance(dist); - } + String dist = (String) valArray[1]; + if (valArray[0] instanceof GeoPoint) { + GeoPoint loc = (GeoPoint) valArray[0]; + ((GeoDistanceFilterBuilder) filter).lat(loc.getLat()).lon(loc.getLon()).distance(dist); + } else { + String loc = (String) valArray[0]; + if (loc.contains(",")) { + String c[] = loc.split(","); + ((GeoDistanceFilterBuilder) filter).lat(Double.parseDouble(c[0])).lon(Double.parseDouble(c[1])).distance(dist); + } else { + ((GeoDistanceFilterBuilder) filter).geohash(loc).distance(dist); + } + } - } + break; + } - break; - } + case BBOX: { + filter = geoBoundingBoxFilter(fieldName); - case BBOX: { - filter = geoBoundingBoxFilter(fieldName); + Assert.isTrue(value instanceof Object[], "Value of a boundedBy filter should be an array of one or two values."); + Object[] valArray = (Object[]) value; + Assert.noNullElements(valArray, "Geo boundedBy filter takes a not null element array as parameter."); - Assert.isTrue(value instanceof Object[], "Value of a boundedBy filter should be an array of one or two values."); - Object[] valArray = (Object[]) value; - Assert.noNullElements(valArray, "Geo boundedBy filter takes a not null element array as parameter."); + if (valArray.length == 1) { + //GeoEnvelop + oneParameterBBox((GeoBoundingBoxFilterBuilder) filter, valArray[0]); + } else if (valArray.length == 2) { + //2x GeoPoint + //2x String + twoParameterBBox((GeoBoundingBoxFilterBuilder) filter, valArray); + } else { + //error + Assert.isTrue(false, "Geo distance filter takes a 1-elements array(GeoBox) or 2-elements array(GeoPoints or Strings(format lat,lon or geohash))."); + } + break; + } + } - if (valArray.length == 1) { - //GeoEnvelop - oneParameterBBox((GeoBoundingBoxFilterBuilder) filter, valArray[0]); - } else if (valArray.length == 2) { - //2x GeoPoint - //2x String - twoParameterBBox((GeoBoundingBoxFilterBuilder) filter, valArray); - } else { - //error - Assert.isTrue(false, "Geo distance filter takes a 1-elements array(GeoBox) or 2-elements array(GeoPoints or Strings(format lat,lon or geohash))."); - } - break; - } + return filter; + } - } + private void oneParameterBBox(GeoBoundingBoxFilterBuilder filter, Object value) { + Assert.isTrue(value instanceof GeoBox, "single-element of boundedBy filter must be type of GeoBox"); + GeoBox geoBBox = (GeoBox) value; + filter.topLeft(geoBBox.getTopLeft().getLat(), geoBBox.getTopLeft().getLon()); + filter.bottomRight(geoBBox.getBottomRight().getLat(), geoBBox.getBottomRight().getLon()); + } - return filter; - } + private static boolean isType(Object[] array, Class clazz) { + for (Object o : array) { + if (!clazz.isInstance(o)) { + return false; + } + } + return true; + } - private void oneParameterBBox(GeoBoundingBoxFilterBuilder filter, Object value) { - Assert.isTrue(value instanceof GeoBox, "single-element of boundedBy filter must be type of GeoBox"); - GeoBox geoBBox = (GeoBox) value; - filter.topLeft(geoBBox.getTopLeft().getLat(), geoBBox.getTopLeft().getLon()); - filter.bottomRight(geoBBox.getBottomRight().getLat(), geoBBox.getBottomRight().getLon()); - } + private void twoParameterBBox(GeoBoundingBoxFilterBuilder filter, Object[] values) { + Assert.isTrue(isType(values, GeoPoint.class) || isType(values, String.class), " both elements of boundedBy filter must be type of GeoPoint or String(format lat,lon or geohash)"); + if (values[0] instanceof GeoPoint) { + GeoPoint topLeft = (GeoPoint) values[0]; + GeoPoint bottomRight = (GeoPoint) values[1]; + filter.topLeft(topLeft.getLat(), topLeft.getLon()); + filter.bottomRight(bottomRight.getLat(), bottomRight.getLon()); + } else { + String topLeft = (String) values[0]; + String bottomRight = (String) values[1]; + filter.topLeft(topLeft); + filter.bottomRight(bottomRight); + } + } - private static boolean isType(Object[] array, Class clazz) { - for (Object o : array) { - if (!clazz.isInstance(o)) { - return false; - } - } - return true; - } + private List buildNegationFilter(String fieldName, Iterator it) { + List notFilterList = new LinkedList(); - private void twoParameterBBox(GeoBoundingBoxFilterBuilder filter, Object[] values) { - Assert.isTrue(isType(values, GeoPoint.class) || isType(values, String.class), " both elements of boundedBy filter must be type of GeoPoint or String(format lat,lon or geohash)"); - if (values[0] instanceof GeoPoint) { - GeoPoint topLeft = (GeoPoint) values[0]; - GeoPoint bottomRight = (GeoPoint) values[1]; - filter.topLeft(topLeft.getLat(), topLeft.getLon()); - filter.bottomRight(bottomRight.getLat(), bottomRight.getLon()); - } else { - String topLeft = (String) values[0]; - String bottomRight = (String) values[1]; - filter.topLeft(topLeft); - filter.bottomRight(bottomRight); - } - } + while (it.hasNext()) { + Criteria.CriteriaEntry criteriaEntry = it.next(); + FilterBuilder notFilter = notFilter(processCriteriaEntry(criteriaEntry.getKey(), criteriaEntry.getValue(), fieldName)); + notFilterList.add(notFilter); + } - private List buildNegationFilter(String fieldName, Iterator it) { - List notFilterList = new LinkedList(); - - while (it.hasNext()) { - Criteria.CriteriaEntry criteriaEntry = it.next(); - FilterBuilder notFilter = notFilter(processCriteriaEntry(criteriaEntry.getKey(), criteriaEntry.getValue(), fieldName)); - notFilterList.add(notFilter); - } - - return notFilterList; - } + return notFilterList; + } } 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 d33259183..ba61a8316 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/CriteriaQueryProcessor.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/CriteriaQueryProcessor.java @@ -15,23 +15,23 @@ */ package org.springframework.data.elasticsearch.core; -import org.elasticsearch.index.query.BoolQueryBuilder; -import org.elasticsearch.index.query.BoostableQueryBuilder; -import org.elasticsearch.index.query.QueryBuilder; -import org.springframework.data.elasticsearch.core.query.Criteria; -import org.springframework.util.Assert; +import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.springframework.data.elasticsearch.core.query.Criteria.*; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.springframework.data.elasticsearch.core.query.Criteria.OperationKey; +import org.elasticsearch.index.query.BoolQueryBuilder; +import org.elasticsearch.index.query.BoostableQueryBuilder; +import org.elasticsearch.index.query.QueryBuilder; +import org.springframework.data.elasticsearch.core.query.Criteria; +import org.springframework.util.Assert; /** * CriteriaQueryProcessor - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Franck Marchand @@ -39,136 +39,133 @@ import static org.springframework.data.elasticsearch.core.query.Criteria.Operati class CriteriaQueryProcessor { - QueryBuilder createQueryFromCriteria(Criteria criteria) { - if(criteria == null) - return null; + QueryBuilder createQueryFromCriteria(Criteria criteria) { + if (criteria == null) + return null; - List shouldQueryBuilderList = new LinkedList(); - List mustNotQueryBuilderList = new LinkedList(); - List mustQueryBuilderList = new LinkedList(); + List shouldQueryBuilderList = new LinkedList(); + List mustNotQueryBuilderList = new LinkedList(); + List mustQueryBuilderList = new LinkedList(); + + ListIterator chainIterator = criteria.getCriteriaChain().listIterator(); + while (chainIterator.hasNext()) { + Criteria chainedCriteria = chainIterator.next(); + QueryBuilder queryFragmentForCriteria = createQueryFragmentForCriteria(chainedCriteria); + + if (queryFragmentForCriteria != null) { + if (chainedCriteria.isOr()) { + shouldQueryBuilderList.add(queryFragmentForCriteria); + } else if (chainedCriteria.isNegating()) { + mustNotQueryBuilderList.add(queryFragmentForCriteria); + } else { + mustQueryBuilderList.add(queryFragmentForCriteria); + } + } + } + + BoolQueryBuilder query = null; + + if (!shouldQueryBuilderList.isEmpty() || !mustNotQueryBuilderList.isEmpty() || !mustQueryBuilderList.isEmpty()) { + + query = boolQuery(); + + for (QueryBuilder qb : shouldQueryBuilderList) { + query.should(qb); + } + for (QueryBuilder qb : mustNotQueryBuilderList) { + query.mustNot(qb); + } + for (QueryBuilder qb : mustQueryBuilderList) { + query.must(qb); + } + } + + return query; + } - ListIterator chainIterator = criteria.getCriteriaChain().listIterator(); - while (chainIterator.hasNext()) { - Criteria chainedCriteria = chainIterator.next(); - QueryBuilder queryFragmentForCriteria = createQueryFragmentForCriteria(chainedCriteria); + private QueryBuilder createQueryFragmentForCriteria(Criteria chainedCriteria) { + if (chainedCriteria.getQueryCriteriaEntries().isEmpty()) + return null; - if(queryFragmentForCriteria!=null) { - if(chainedCriteria.isOr()){ - shouldQueryBuilderList.add(queryFragmentForCriteria); - }else if(chainedCriteria.isNegating()){ - mustNotQueryBuilderList.add(queryFragmentForCriteria); - }else{ - mustQueryBuilderList.add(queryFragmentForCriteria); - } - } - } + Iterator it = chainedCriteria.getQueryCriteriaEntries().iterator(); + boolean singeEntryCriteria = (chainedCriteria.getQueryCriteriaEntries().size() == 1); - BoolQueryBuilder query = null; + String fieldName = chainedCriteria.getField().getName(); + Assert.notNull(fieldName, "Unknown field"); + QueryBuilder query = null; - if(!shouldQueryBuilderList.isEmpty() || !mustNotQueryBuilderList.isEmpty() || !mustQueryBuilderList.isEmpty()) { + 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)); + } + } - query = boolQuery(); - - for(QueryBuilder qb : shouldQueryBuilderList) { - query.should(qb); - } - for(QueryBuilder qb : mustNotQueryBuilderList) { - query.mustNot(qb); - } - for(QueryBuilder qb : mustQueryBuilderList) { - query.must(qb); - } - } - - return query; - } + addBoost(query, chainedCriteria.getBoost()); + return query; + } - private QueryBuilder createQueryFragmentForCriteria(Criteria chainedCriteria) { - if(chainedCriteria.getQueryCriteriaEntries().isEmpty()) - return null; + private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) { + if (value == null) { + return null; + } + QueryBuilder query = null; - Iterator it = chainedCriteria.getQueryCriteriaEntries().iterator(); - boolean singeEntryCriteria = (chainedCriteria.getQueryCriteriaEntries().size() == 1); + 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; + } - String fieldName = chainedCriteria.getField().getName(); - Assert.notNull(fieldName,"Unknown field"); - QueryBuilder query = null; + 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)); - } - } - - addBoost(query, chainedCriteria.getBoost()); - return query; - } - - - private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) { - if (value == null) { - return null; - } - QueryBuilder query = null; - - 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 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); + } + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/DefaultEntityMapper.java b/src/main/java/org/springframework/data/elasticsearch/core/DefaultEntityMapper.java index 5d87a4474..828f17a45 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/DefaultEntityMapper.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/DefaultEntityMapper.java @@ -15,11 +15,11 @@ */ package org.springframework.data.elasticsearch.core; +import java.io.IOException; + import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; -import java.io.IOException; - /** * DocumentMapper using jackson * @@ -28,20 +28,20 @@ import java.io.IOException; */ public class DefaultEntityMapper implements EntityMapper { - private ObjectMapper objectMapper; + private ObjectMapper objectMapper; - public DefaultEntityMapper() { - objectMapper = new ObjectMapper(); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - } + public DefaultEntityMapper() { + objectMapper = new ObjectMapper(); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } - @Override - public String mapToString(Object object) throws IOException { - return objectMapper.writeValueAsString(object); - } + @Override + public String mapToString(Object object) throws IOException { + return objectMapper.writeValueAsString(object); + } - @Override - public T mapToObject(String source, Class clazz) throws IOException { - return objectMapper.readValue(source, clazz); - } + @Override + public T mapToObject(String source, Class clazz) throws IOException { + return objectMapper.readValue(source, clazz); + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/DefaultResultMapper.java b/src/main/java/org/springframework/data/elasticsearch/core/DefaultResultMapper.java index 4cdc75a3d..399e3565b 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/DefaultResultMapper.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/DefaultResultMapper.java @@ -16,6 +16,14 @@ package org.springframework.data.elasticsearch.core; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.Method; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.base.Strings; @@ -34,115 +42,107 @@ import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersiste import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.context.MappingContext; -import java.lang.reflect.Method; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - /** * @author Artur Konczak */ public class DefaultResultMapper extends AbstractResultMapper { - private MappingContext, ElasticsearchPersistentProperty> mappingContext; - - public DefaultResultMapper(){ - super(new DefaultEntityMapper()); - } - - public DefaultResultMapper(MappingContext, ElasticsearchPersistentProperty> mappingContext){ - super(new DefaultEntityMapper()); - this.mappingContext = mappingContext; - } + private MappingContext, ElasticsearchPersistentProperty> mappingContext; - public DefaultResultMapper(EntityMapper entityMapper) { - super(entityMapper); - } + public DefaultResultMapper() { + super(new DefaultEntityMapper()); + } - @Override - public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { - long totalHits = response.getHits().totalHits(); - List results = new ArrayList(); - for (SearchHit hit : response.getHits()) { - if (hit != null) { - T result = null; - if (!Strings.isNullOrEmpty(hit.sourceAsString())) { - result = mapEntity(hit.sourceAsString(), clazz); - } else { - result = mapEntity(hit.getFields().values(), clazz); - } - setPersistentEntityId(result, hit.getId(), clazz); - results.add(result); - } - } - List facets = new ArrayList(); - if (response.getFacets() != null) { - for (Facet facet : response.getFacets()) { - FacetResult facetResult = DefaultFacetMapper.parse(facet); - if (facetResult != null) { - facets.add(facetResult); - } - } - } + public DefaultResultMapper(MappingContext, ElasticsearchPersistentProperty> mappingContext) { + super(new DefaultEntityMapper()); + this.mappingContext = mappingContext; + } - return new FacetedPageImpl(results, pageable, totalHits, facets); - } + public DefaultResultMapper(EntityMapper entityMapper) { + super(entityMapper); + } - private T mapEntity(Collection values, Class clazz) { - return mapEntity(buildJSONFromFields(values), clazz); - } + @Override + public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { + long totalHits = response.getHits().totalHits(); + List results = new ArrayList(); + for (SearchHit hit : response.getHits()) { + if (hit != null) { + T result = null; + if (!Strings.isNullOrEmpty(hit.sourceAsString())) { + result = mapEntity(hit.sourceAsString(), clazz); + } else { + result = mapEntity(hit.getFields().values(), clazz); + } + setPersistentEntityId(result, hit.getId(), clazz); + results.add(result); + } + } + List facets = new ArrayList(); + if (response.getFacets() != null) { + for (Facet facet : response.getFacets()) { + FacetResult facetResult = DefaultFacetMapper.parse(facet); + if (facetResult != null) { + facets.add(facetResult); + } + } + } - private String buildJSONFromFields(Collection values) { - JsonFactory nodeFactory = new JsonFactory(); - try { - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8); - generator.writeStartObject(); - for (SearchHitField value : values) { - if (value.getValues().size() > 1) { - generator.writeArrayFieldStart(value.getName()); - for (Object val : value.getValues()) { - generator.writeObject(val); - } - generator.writeEndArray(); - } else { - generator.writeObjectField(value.getName(), value.getValue()); - } - } - generator.writeEndObject(); - generator.flush(); - return new String(stream.toByteArray(), Charset.forName("UTF-8")); - } catch (IOException e) { - return null; - } - } + return new FacetedPageImpl(results, pageable, totalHits, facets); + } - @Override - public T mapResult(GetResponse response, Class clazz) { - T result = mapEntity(response.getSourceAsString(),clazz); - if (result != null){ - setPersistentEntityId(result, response.getId(), clazz); - } - return result; - } - - private void setPersistentEntityId(T result, String id, Class clazz) { - if (mappingContext != null && clazz.isAnnotationPresent(Document.class)){ - PersistentProperty idProperty = mappingContext.getPersistentEntity(clazz).getIdProperty(); - // Only deal with String because ES generated Ids are strings ! - if (idProperty != null && idProperty.getType().isAssignableFrom(String.class)){ - Method setter = idProperty.getSetter(); - if (setter != null){ - try{ - setter.invoke(result, id); - } catch (Throwable t) { - t.printStackTrace(); - } - } - } - } - } + private T mapEntity(Collection values, Class clazz) { + return mapEntity(buildJSONFromFields(values), clazz); + } + + private String buildJSONFromFields(Collection values) { + JsonFactory nodeFactory = new JsonFactory(); + try { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + JsonGenerator generator = nodeFactory.createGenerator(stream, JsonEncoding.UTF8); + generator.writeStartObject(); + for (SearchHitField value : values) { + if (value.getValues().size() > 1) { + generator.writeArrayFieldStart(value.getName()); + for (Object val : value.getValues()) { + generator.writeObject(val); + } + generator.writeEndArray(); + } else { + generator.writeObjectField(value.getName(), value.getValue()); + } + } + generator.writeEndObject(); + generator.flush(); + return new String(stream.toByteArray(), Charset.forName("UTF-8")); + } catch (IOException e) { + return null; + } + } + + @Override + public T mapResult(GetResponse response, Class clazz) { + T result = mapEntity(response.getSourceAsString(), clazz); + if (result != null) { + setPersistentEntityId(result, response.getId(), clazz); + } + return result; + } + + private void setPersistentEntityId(T result, String id, Class clazz) { + if (mappingContext != null && clazz.isAnnotationPresent(Document.class)) { + PersistentProperty idProperty = mappingContext.getPersistentEntity(clazz).getIdProperty(); + // Only deal with String because ES generated Ids are strings ! + if (idProperty != null && idProperty.getType().isAssignableFrom(String.class)) { + Method setter = idProperty.getSetter(); + if (setter != null) { + try { + setter.invoke(result, id); + } catch (Throwable t) { + t.printStackTrace(); + } + } + } + } + } } 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 f8290353f..b10fc2ad4 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchOperations.java @@ -15,17 +15,17 @@ */ package org.springframework.data.elasticsearch.core; +import java.util.List; +import java.util.Set; + import org.elasticsearch.action.update.UpdateResponse; import org.springframework.data.domain.Page; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.query.*; -import java.util.List; -import java.util.Set; - /** * ElasticsearchOperations - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -38,7 +38,7 @@ public interface ElasticsearchOperations { /** * Create an index for a class - * + * * @param clazz * @param */ @@ -46,7 +46,7 @@ public interface ElasticsearchOperations { /** * Create mapping for a class - * + * * @param clazz * @param */ @@ -54,26 +54,26 @@ public interface ElasticsearchOperations { /** * 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 using custom mapper - * - * @param query - * @param clazz - * @param mapper - * @return the first matching object - */ - T queryForObject(GetQuery query, Class clazz, GetResultMapper mapper); + /** + * Execute the query against elasticsearch and return the first returned object using custom mapper + * + * @param query + * @param clazz + * @param mapper + * @return the first matching object + */ + T queryForObject(GetQuery query, Class clazz, GetResultMapper mapper); /** * Execute the query against elasticsearch and return the first returned object - * + * * @param query * @param clazz * @return the first matching object @@ -82,7 +82,7 @@ public interface ElasticsearchOperations { /** * Execute the query against elasticsearch and return the first returned object - * + * * @param query * @param clazz * @return the first matching object @@ -91,25 +91,25 @@ public interface ElasticsearchOperations { /** * Execute the query against elasticsearch and return result as {@link Page} - * + * * @param query * @param clazz * @return */ FacetedPage queryForPage(SearchQuery query, Class clazz); - /** - * Execute the query against elasticsearch and return result as {@link Page} using custom mapper - * - * @param query - * @param clazz - * @return - */ - FacetedPage queryForPage(SearchQuery query, Class clazz, SearchResultMapper mapper); + /** + * Execute the query against elasticsearch and return result as {@link Page} using custom mapper + * + * @param query + * @param clazz + * @return + */ + FacetedPage queryForPage(SearchQuery query, Class clazz, SearchResultMapper mapper); /** * Execute the query against elasticsearch and return result as {@link Page} - * + * * @param query * @param clazz * @return @@ -118,25 +118,25 @@ public interface ElasticsearchOperations { /** * Execute the query against elasticsearch and return result as {@link Page} - * + * * @param query * @param clazz * @return */ FacetedPage queryForPage(StringQuery query, Class clazz); - /** - * Execute the query against elasticsearch and return result as {@link Page} using custom mapper - * - * @param query - * @param clazz - * @return - */ - FacetedPage queryForPage(StringQuery query, Class clazz, SearchResultMapper mapper); + /** + * Execute the query against elasticsearch and return result as {@link Page} using custom mapper + * + * @param query + * @param clazz + * @return + */ + FacetedPage queryForPage(StringQuery query, Class clazz, SearchResultMapper mapper); /** * Execute the criteria query against elasticsearch and return result as {@link List} - * + * * @param query * @param clazz * @param @@ -146,7 +146,7 @@ public interface ElasticsearchOperations { /** * Execute the string query against elasticsearch and return result as {@link List} - * + * * @param query * @param clazz * @param @@ -154,19 +154,19 @@ public interface ElasticsearchOperations { */ List queryForList(StringQuery query, Class clazz); - /** - * Execute the search query against elasticsearch and return result as {@link List} - * - * @param query - * @param clazz - * @param - * @return - */ - List queryForList(SearchQuery query, Class clazz); + /** + * Execute the search query against elasticsearch and return result as {@link List} + * + * @param query + * @param clazz + * @param + * @return + */ + List queryForList(SearchQuery query, Class clazz); /** * Execute the query against elasticsearch and return ids - * + * * @param query * @return */ @@ -174,7 +174,7 @@ public interface ElasticsearchOperations { /** * return number of elements found by for given query - * + * * @param query * @param clazz * @return @@ -183,30 +183,30 @@ public interface ElasticsearchOperations { /** * Index an object. Will do save or update - * + * * @param query * @return returns the document id */ String index(IndexQuery query); - /** - * Partial update of the document - * - * @param updateQuery - * @return - */ - UpdateResponse update(UpdateQuery updateQuery); + /** + * Partial update of the document + * + * @param updateQuery + * @return + */ + UpdateResponse update(UpdateQuery updateQuery); /** * Bulk index all objects. Will do save or update - * + * * @param queries */ void bulkIndex(List queries); /** * Delete the one object with provided id - * + * * @param indexName * @param type * @param id @@ -216,7 +216,7 @@ public interface ElasticsearchOperations { /** * Delete the one object with provided id - * + * * @param clazz * @param id * @return documentId of the document deleted @@ -225,18 +225,18 @@ public interface ElasticsearchOperations { /** * Delete all records matching the query - * + * * @param clazz * @param query */ void delete(DeleteQuery query, Class clazz); /** - * Delete all records matching the query - * - * @param query - */ - void delete(DeleteQuery query); + * Delete all records matching the query + * + * @param query + */ + void delete(DeleteQuery query); /** * Deletes an index for given entity @@ -248,34 +248,34 @@ public interface ElasticsearchOperations { boolean deleteIndex(Class clazz); /** - * Deletes a type in an index - * - * @param index - * @param type - */ - void deleteType(String index, String type); + * Deletes a type in an index + * + * @param index + * @param type + */ + void deleteType(String index, String type); /** * check if index is exists - * + * * @param clazz * @param * @return */ boolean indexExists(Class clazz); - /** - * check if type is exists in an index - * - * @param index - * @param type - * @return - */ - boolean typeExists(String index, String type); + /** + * check if type is exists in an index + * + * @param index + * @param type + * @return + */ + boolean typeExists(String index, String type); /** * refresh the index - * + * * @param indexName * @param waitForOperation */ @@ -283,7 +283,7 @@ public interface ElasticsearchOperations { /** * refresh the index - * + * * @param clazz * @param waitForOperation */ @@ -291,7 +291,7 @@ public interface ElasticsearchOperations { /** * Returns scroll id for scan query - * + * * @param query * @param scrollTimeInMillis * @param noFields @@ -301,7 +301,7 @@ public interface ElasticsearchOperations { /** * Scrolls the results for give scroll id - * + * * @param scrollId * @param scrollTimeInMillis * @param clazz @@ -310,20 +310,20 @@ public interface ElasticsearchOperations { */ Page scroll(String scrollId, long scrollTimeInMillis, Class clazz); - /** - * Scrolls the results for give scroll id using custom result mapper - * - * @param scrollId - * @param scrollTimeInMillis - * @param mapper - * @param - * @return - */ - Page scroll(String scrollId, long scrollTimeInMillis, SearchResultMapper mapper); + /** + * Scrolls the results for give scroll id using custom result mapper + * + * @param scrollId + * @param scrollTimeInMillis + * @param mapper + * @param + * @return + */ + Page scroll(String scrollId, long scrollTimeInMillis, SearchResultMapper mapper); /** * more like this query to search for documents that are "like" a specific document. - * + * * @param query * @param clazz * @param @@ -331,27 +331,27 @@ public interface ElasticsearchOperations { */ Page moreLikeThis(MoreLikeThisQuery query, Class clazz); - /** - * adding new alias - * - * @param query - * @return - */ - Boolean addAlias(AliasQuery query); + /** + * adding new alias + * + * @param query + * @return + */ + Boolean addAlias(AliasQuery query); - /** - * removing previously created alias - * - * @param query - * @return - */ - Boolean removeAlias(AliasQuery query); + /** + * removing previously created alias + * + * @param query + * @return + */ + Boolean removeAlias(AliasQuery query); - /** - * get all the alias pointing to specified index - * - * @param indexName - * @return - */ - Set queryForAlias(String indexName); + /** + * get all the alias pointing to specified index + * + * @param indexName + * @return + */ + Set queryForAlias(String indexName); } 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 eafa5423b..221918673 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplate.java @@ -15,6 +15,18 @@ */ package org.springframework.data.elasticsearch.core; +import static org.apache.commons.collections.CollectionUtils.isNotEmpty; +import static org.apache.commons.lang.StringUtils.*; +import static org.elasticsearch.action.search.SearchType.*; +import static org.elasticsearch.client.Requests.*; +import static org.elasticsearch.common.collect.Sets.*; +import static org.elasticsearch.index.VersionType.*; +import static org.springframework.data.elasticsearch.core.MappingBuilder.*; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.util.*; + import org.apache.commons.collections.CollectionUtils; import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest; import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequestBuilder; @@ -59,21 +71,6 @@ import org.springframework.data.elasticsearch.core.query.*; import org.springframework.data.mapping.PersistentProperty; import org.springframework.util.Assert; -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.*; - -import static org.apache.commons.collections.CollectionUtils.isNotEmpty; -import static org.apache.commons.lang.StringUtils.isBlank; -import static org.apache.commons.lang.StringUtils.isNotBlank; -import static org.elasticsearch.action.search.SearchType.DFS_QUERY_THEN_FETCH; -import static org.elasticsearch.action.search.SearchType.SCAN; -import static org.elasticsearch.client.Requests.indicesExistsRequest; -import static org.elasticsearch.client.Requests.refreshRequest; -import static org.elasticsearch.common.collect.Sets.newHashSet; -import static org.elasticsearch.index.VersionType.EXTERNAL; -import static org.springframework.data.elasticsearch.core.MappingBuilder.buildMapping; - /** * ElasticsearchTemplate * @@ -84,610 +81,608 @@ import static org.springframework.data.elasticsearch.core.MappingBuilder.buildMa public class ElasticsearchTemplate implements ElasticsearchOperations { - private Client client; - private ElasticsearchConverter elasticsearchConverter; - private ResultsMapper resultsMapper; - - public ElasticsearchTemplate(Client client) { - this(client, null, null); - } - - public ElasticsearchTemplate(Client client, EntityMapper entityMapper) { - this(client, null, new DefaultResultMapper(entityMapper)); - } - - public ElasticsearchTemplate(Client client, ResultsMapper resultsMapper) { - this(client, null, resultsMapper); - } - - public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter) { - this(client, elasticsearchConverter, null); - } - - public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter, ResultsMapper resultsMapper) { - this.client = client; - this.elasticsearchConverter = (elasticsearchConverter == null) ? new MappingElasticsearchConverter( - new SimpleElasticsearchMappingContext()) : elasticsearchConverter; - this.resultsMapper = (resultsMapper == null) ? new DefaultResultMapper(this.elasticsearchConverter.getMappingContext()) : resultsMapper; - } - - @Override - public boolean createIndex(Class 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()); - - try { - XContentBuilder xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(), persistentEntity - .getIdProperty().getFieldName(), persistentEntity.getParentType()); - 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 T queryForObject(GetQuery query, Class clazz) { - return queryForObject(query, clazz, resultsMapper); - } - - @Override - public T queryForObject(GetQuery query, Class clazz, GetResultMapper mapper) { - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - GetResponse response = client - .prepareGet(persistentEntity.getIndexName(), persistentEntity.getIndexType(), query.getId()).execute() - .actionGet(); - - T entity = mapper.mapResult(response, clazz); - return entity; - } - - @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 FacetedPage queryForPage(SearchQuery query, Class clazz) { - return queryForPage(query, clazz, resultsMapper); - } - - @Override - public FacetedPage queryForPage(SearchQuery query, Class clazz, SearchResultMapper mapper) { - SearchResponse response = doSearch(prepareSearch(query, clazz), query); - return mapper.mapResults(response, clazz, query.getPageable()); - } - - @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(SearchQuery 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 Page queryForPage(CriteriaQuery criteriaQuery, Class clazz) { - QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria()); - FilterBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria()); - SearchRequestBuilder searchRequestBuilder = prepareSearch(criteriaQuery, clazz); - - if (elasticsearchQuery != null) { - searchRequestBuilder.setQuery(elasticsearchQuery); - } else { - searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery()); - } - - if(criteriaQuery.getMinScore()>0){ - searchRequestBuilder.setMinScore(criteriaQuery.getMinScore()); - } - - if (elasticsearchFilter != null) - searchRequestBuilder.setFilter(elasticsearchFilter); - - SearchResponse response = searchRequestBuilder - .execute().actionGet(); - return resultsMapper.mapResults(response, clazz, criteriaQuery.getPageable()); - } - - @Override - public FacetedPage queryForPage(StringQuery query, Class clazz) { - return queryForPage(query, clazz, resultsMapper); - } - - @Override - public FacetedPage queryForPage(StringQuery query, Class clazz, SearchResultMapper mapper) { - SearchResponse response = prepareSearch(query, clazz).setQuery(query.getSource()).execute().actionGet(); - return mapper.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 String index(IndexQuery query) { - String documentId = prepareIndex(query).execute().actionGet().getId(); - // We should call this because we are not going through a mapper. - if (query.getObject() != null){ - setPersistentEntityId(query.getObject(), documentId); - } - return documentId; - } - - @Override - public UpdateResponse update(UpdateQuery query) { - String indexName = isNotBlank(query.getIndexName()) ? query.getIndexName() : getPersistentEntityFor(query.getClazz()).getIndexName(); - String type = isNotBlank(query.getType()) ? query.getType() : getPersistentEntityFor(query.getClazz()).getIndexType(); - Assert.notNull(indexName, "No index defined for Query"); - Assert.notNull(type, "No type define for Query"); - Assert.notNull(query.getId(), "No Id define for Query"); - Assert.notNull(query.getIndexRequest(), "No IndexRequest define for Query"); - UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate(indexName, type, query.getId()); - if (query.DoUpsert()) { - updateRequestBuilder.setDocAsUpsert(true) - .setUpsert(query.getIndexRequest()).setDoc(query.getIndexRequest()); - } else { - updateRequestBuilder.setDoc(query.getIndexRequest()); - } - return updateRequestBuilder.execute().actionGet(); - } - - - @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 typeExists(String index, String type) { - return client.admin().cluster().prepareState().execute().actionGet() - .getState().metaData().index(index).mappings().containsKey(type); - } - - @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 void deleteType(String index, String type) { - ImmutableOpenMap mappings = client.admin().cluster().prepareState().execute().actionGet() - .getState().metaData().index(index).mappings(); - if (mappings.containsKey(type)) { - client.admin().indices().deleteMapping(new DeleteMappingRequest(index).type(type)).actionGet(); - } - } - - @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 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) { - Assert.notNull(deleteQuery.getIndex(), "No index defined for Query"); - Assert.notNull(deleteQuery.getType(), "No type define for Query"); - client.prepareDeleteByQuery(deleteQuery.getIndex()).setTypes(deleteQuery.getType()) - .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"); - - 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 (noFields) { - requestBuilder.setNoFields(); - } - return requestBuilder.execute().actionGet().getScrollId(); - } - - @Override - public Page scroll(String scrollId, long scrollTimeInMillis, Class clazz) { - SearchResponse response = client.prepareSearchScroll(scrollId) - .setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute().actionGet(); - return resultsMapper.mapResults(response, clazz, null); - } - - @Override - public Page scroll(String scrollId, long scrollTimeInMillis, SearchResultMapper mapper) { - SearchResponse response = client.prepareSearchScroll(scrollId) - .setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute().actionGet(); - return mapper.mapResults(response, null, null); - } - - @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"); - - 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 (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 resultsMapper.mapResults(response, clazz, query.getPageable()); - } - - private SearchResponse doSearch(SearchRequestBuilder searchRequest, SearchQuery searchQuery) { - if (searchQuery.getFilter() != null) { - searchRequest.setFilter(searchQuery.getFilter()); - } - - if (searchQuery.getElasticsearchSort() != null) { - searchRequest.addSort(searchQuery.getElasticsearchSort()); - } - - if (CollectionUtils.isNotEmpty(searchQuery.getFacets())) { - for (FacetRequest facetRequest : searchQuery.getFacets()) { - FacetBuilder facet = facetRequest.getFacet(); - if (facetRequest.applyQueryFilter() && searchQuery.getFilter() != null) { - facet.facetFilter(searchQuery.getFilter()); - } - searchRequest.addFacet(facet); - } - } - - if (searchQuery.getHighlightFields() != null) { - for (HighlightBuilder.Field highlightField : searchQuery.getHighlightFields()) { - searchRequest.addHighlightedField(highlightField); - } - } - - return searchRequest.setQuery(searchQuery.getQuery()).execute().actionGet(); - } - - 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 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 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"); - - 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.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); - } - } - - if(query.getMinScore()>0){ - searchRequestBuilder.setMinScore(query.getMinScore()); - } - return searchRequestBuilder; - } - - 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(); - - IndexRequestBuilder indexRequestBuilder = null; - - if (query.getObject() != null) { - // If we have a query id and a document id, do not ask ES to generate one. - String entityId = getPersistentEntityId(query.getObject()); - if (query.getId() != null && entityId != null){ - indexRequestBuilder = client.prepareIndex(indexName, type, query.getId()); - } else { - indexRequestBuilder = client.prepareIndex(indexName, type); - } - indexRequestBuilder.setSource(resultsMapper.getEntityMapper().mapToString(query.getObject())); - } else if (query.getSource() != null) { - indexRequestBuilder = client.prepareIndex(indexName, type, query.getId()).setSource(query.getSource()); - } else { - throw new ElasticsearchException("object or source is null, failed to index the document [id: " + query.getId() + "]"); - } - if (query.getVersion() != null) { - indexRequestBuilder.setVersion(query.getVersion()); - indexRequestBuilder.setVersionType(EXTERNAL); - } - - if (query.getParentId() != null) { - indexRequestBuilder.setParent(query.getParentId()); - } - - return indexRequestBuilder; - } catch (IOException e) { - throw new ElasticsearchException("failed to index the document [id: " + query.getId() + "]", e); - } - } - - @Override - public void refresh(String indexName, boolean waitForOperation) { - client.admin().indices().refresh(refreshRequest(indexName).force(waitForOperation)).actionGet(); - } - - @Override - public void refresh(Class clazz, boolean waitForOperation) { - ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); - client.admin().indices() - .refresh(refreshRequest(persistentEntity.getIndexName()).force(waitForOperation)).actionGet(); - } - - @Override - public Boolean addAlias(AliasQuery query) { - Assert.notNull(query.getIndexName(), "No index defined for Alias"); - Assert.notNull(query.getAliasName(), "No alias defined"); - IndicesAliasesRequestBuilder indicesAliasesRequestBuilder = null; - if(query.getFilterBuilder() != null) { - indicesAliasesRequestBuilder = client.admin().indices().prepareAliases().addAlias(query.getIndexName(), query.getAliasName(), query.getFilterBuilder()); - } else if(query.getFilter() != null) { - indicesAliasesRequestBuilder = client.admin().indices().prepareAliases().addAlias(query.getIndexName(), query.getAliasName(), query.getFilter()); - } else { - indicesAliasesRequestBuilder = client.admin().indices().prepareAliases().addAlias(query.getIndexName(), query.getAliasName()); - } - return indicesAliasesRequestBuilder.execute().actionGet().isAcknowledged(); - } - - @Override - public Boolean removeAlias(AliasQuery query) { - Assert.notNull(query.getIndexName(), "No index defined for Alias"); - Assert.notNull(query.getAliasName(), "No alias defined"); - return client.admin().indices().prepareAliases().removeAlias(query.getIndexName(), query.getAliasName()) - .execute().actionGet().isAcknowledged(); - } - - @Override - public Set queryForAlias(String indexName) { - ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest() - .filterRoutingTable(true) - .filterNodes(true) - .filteredIndices(indexName); - Iterator iterator = client.admin().cluster().state(clusterStateRequest).actionGet().getState().getMetaData().aliases().keysIt(); - return newHashSet(iterator); - } - - 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 getPersistentEntityId(Object entity){ - PersistentProperty idProperty = getPersistentEntityFor(entity.getClass()).getIdProperty(); - if (idProperty != null){ - Method getter = idProperty.getGetter(); - if (getter != null){ - try{ - Object id = getter.invoke(entity); - if (id != null){ - return String.valueOf(id); - } - - } catch (Throwable t){ - t.printStackTrace(); - } - } - } - return null; - } - - private void setPersistentEntityId(Object entity, String id){ - PersistentProperty idProperty = getPersistentEntityFor(entity.getClass()).getIdProperty(); - // Only deal with String because ES generated Ids are strings ! - if (idProperty != null && idProperty.getType().isAssignableFrom(String.class)){ - Method setter = idProperty.getSetter(); - if (setter != null){ - try{ - setter.invoke(entity, id); - } catch (Throwable t) { - t.printStackTrace(); - } - } - } - } - - private String[] retrieveIndexNameFromPersistentEntity(Class clazz) { - return new String[]{getPersistentEntityFor(clazz).getIndexName()}; - } - - 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 static String[] toArray(List values) { - String[] valuesAsArray = new String[values.size()]; - return values.toArray(valuesAsArray); - - } - - protected ResultsMapper getResultsMapper() { - return resultsMapper; - } + private Client client; + private ElasticsearchConverter elasticsearchConverter; + private ResultsMapper resultsMapper; + + public ElasticsearchTemplate(Client client) { + this(client, null, null); + } + + public ElasticsearchTemplate(Client client, EntityMapper entityMapper) { + this(client, null, new DefaultResultMapper(entityMapper)); + } + + public ElasticsearchTemplate(Client client, ResultsMapper resultsMapper) { + this(client, null, resultsMapper); + } + + public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter) { + this(client, elasticsearchConverter, null); + } + + public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter, ResultsMapper resultsMapper) { + this.client = client; + this.elasticsearchConverter = (elasticsearchConverter == null) ? new MappingElasticsearchConverter( + new SimpleElasticsearchMappingContext()) : elasticsearchConverter; + this.resultsMapper = (resultsMapper == null) ? new DefaultResultMapper(this.elasticsearchConverter.getMappingContext()) : resultsMapper; + } + + @Override + public boolean createIndex(Class 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()); + + try { + XContentBuilder xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(), persistentEntity + .getIdProperty().getFieldName(), persistentEntity.getParentType()); + 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 T queryForObject(GetQuery query, Class clazz) { + return queryForObject(query, clazz, resultsMapper); + } + + @Override + public T queryForObject(GetQuery query, Class clazz, GetResultMapper mapper) { + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + GetResponse response = client + .prepareGet(persistentEntity.getIndexName(), persistentEntity.getIndexType(), query.getId()).execute() + .actionGet(); + + T entity = mapper.mapResult(response, clazz); + return entity; + } + + @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 FacetedPage queryForPage(SearchQuery query, Class clazz) { + return queryForPage(query, clazz, resultsMapper); + } + + @Override + public FacetedPage queryForPage(SearchQuery query, Class clazz, SearchResultMapper mapper) { + SearchResponse response = doSearch(prepareSearch(query, clazz), query); + return mapper.mapResults(response, clazz, query.getPageable()); + } + + @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(SearchQuery 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 Page queryForPage(CriteriaQuery criteriaQuery, Class clazz) { + QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria()); + FilterBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria()); + SearchRequestBuilder searchRequestBuilder = prepareSearch(criteriaQuery, clazz); + + if (elasticsearchQuery != null) { + searchRequestBuilder.setQuery(elasticsearchQuery); + } else { + searchRequestBuilder.setQuery(QueryBuilders.matchAllQuery()); + } + + if (criteriaQuery.getMinScore() > 0) { + searchRequestBuilder.setMinScore(criteriaQuery.getMinScore()); + } + + if (elasticsearchFilter != null) + searchRequestBuilder.setFilter(elasticsearchFilter); + + SearchResponse response = searchRequestBuilder + .execute().actionGet(); + return resultsMapper.mapResults(response, clazz, criteriaQuery.getPageable()); + } + + @Override + public FacetedPage queryForPage(StringQuery query, Class clazz) { + return queryForPage(query, clazz, resultsMapper); + } + + @Override + public FacetedPage queryForPage(StringQuery query, Class clazz, SearchResultMapper mapper) { + SearchResponse response = prepareSearch(query, clazz).setQuery(query.getSource()).execute().actionGet(); + return mapper.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 String index(IndexQuery query) { + String documentId = prepareIndex(query).execute().actionGet().getId(); + // We should call this because we are not going through a mapper. + if (query.getObject() != null) { + setPersistentEntityId(query.getObject(), documentId); + } + return documentId; + } + + @Override + public UpdateResponse update(UpdateQuery query) { + String indexName = isNotBlank(query.getIndexName()) ? query.getIndexName() : getPersistentEntityFor(query.getClazz()).getIndexName(); + String type = isNotBlank(query.getType()) ? query.getType() : getPersistentEntityFor(query.getClazz()).getIndexType(); + Assert.notNull(indexName, "No index defined for Query"); + Assert.notNull(type, "No type define for Query"); + Assert.notNull(query.getId(), "No Id define for Query"); + Assert.notNull(query.getIndexRequest(), "No IndexRequest define for Query"); + UpdateRequestBuilder updateRequestBuilder = client.prepareUpdate(indexName, type, query.getId()); + if (query.DoUpsert()) { + updateRequestBuilder.setDocAsUpsert(true) + .setUpsert(query.getIndexRequest()).setDoc(query.getIndexRequest()); + } else { + updateRequestBuilder.setDoc(query.getIndexRequest()); + } + return updateRequestBuilder.execute().actionGet(); + } + + + @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 typeExists(String index, String type) { + return client.admin().cluster().prepareState().execute().actionGet() + .getState().metaData().index(index).mappings().containsKey(type); + } + + @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 void deleteType(String index, String type) { + ImmutableOpenMap mappings = client.admin().cluster().prepareState().execute().actionGet() + .getState().metaData().index(index).mappings(); + if (mappings.containsKey(type)) { + client.admin().indices().deleteMapping(new DeleteMappingRequest(index).type(type)).actionGet(); + } + } + + @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 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) { + Assert.notNull(deleteQuery.getIndex(), "No index defined for Query"); + Assert.notNull(deleteQuery.getType(), "No type define for Query"); + client.prepareDeleteByQuery(deleteQuery.getIndex()).setTypes(deleteQuery.getType()) + .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"); + + 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 (noFields) { + requestBuilder.setNoFields(); + } + return requestBuilder.execute().actionGet().getScrollId(); + } + + @Override + public Page scroll(String scrollId, long scrollTimeInMillis, Class clazz) { + SearchResponse response = client.prepareSearchScroll(scrollId) + .setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute().actionGet(); + return resultsMapper.mapResults(response, clazz, null); + } + + @Override + public Page scroll(String scrollId, long scrollTimeInMillis, SearchResultMapper mapper) { + SearchResponse response = client.prepareSearchScroll(scrollId) + .setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute().actionGet(); + return mapper.mapResults(response, null, null); + } + + @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"); + + 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 (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 resultsMapper.mapResults(response, clazz, query.getPageable()); + } + + private SearchResponse doSearch(SearchRequestBuilder searchRequest, SearchQuery searchQuery) { + if (searchQuery.getFilter() != null) { + searchRequest.setFilter(searchQuery.getFilter()); + } + + if (searchQuery.getElasticsearchSort() != null) { + searchRequest.addSort(searchQuery.getElasticsearchSort()); + } + + if (CollectionUtils.isNotEmpty(searchQuery.getFacets())) { + for (FacetRequest facetRequest : searchQuery.getFacets()) { + FacetBuilder facet = facetRequest.getFacet(); + if (facetRequest.applyQueryFilter() && searchQuery.getFilter() != null) { + facet.facetFilter(searchQuery.getFilter()); + } + searchRequest.addFacet(facet); + } + } + + if (searchQuery.getHighlightFields() != null) { + for (HighlightBuilder.Field highlightField : searchQuery.getHighlightFields()) { + searchRequest.addHighlightedField(highlightField); + } + } + + return searchRequest.setQuery(searchQuery.getQuery()).execute().actionGet(); + } + + 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 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 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"); + + 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.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); + } + } + + if (query.getMinScore() > 0) { + searchRequestBuilder.setMinScore(query.getMinScore()); + } + return searchRequestBuilder; + } + + 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(); + + IndexRequestBuilder indexRequestBuilder = null; + + if (query.getObject() != null) { + // If we have a query id and a document id, do not ask ES to generate one. + String entityId = getPersistentEntityId(query.getObject()); + if (query.getId() != null && entityId != null) { + indexRequestBuilder = client.prepareIndex(indexName, type, query.getId()); + } else { + indexRequestBuilder = client.prepareIndex(indexName, type); + } + indexRequestBuilder.setSource(resultsMapper.getEntityMapper().mapToString(query.getObject())); + } else if (query.getSource() != null) { + indexRequestBuilder = client.prepareIndex(indexName, type, query.getId()).setSource(query.getSource()); + } else { + throw new ElasticsearchException("object or source is null, failed to index the document [id: " + query.getId() + "]"); + } + if (query.getVersion() != null) { + indexRequestBuilder.setVersion(query.getVersion()); + indexRequestBuilder.setVersionType(EXTERNAL); + } + + if (query.getParentId() != null) { + indexRequestBuilder.setParent(query.getParentId()); + } + + return indexRequestBuilder; + } catch (IOException e) { + throw new ElasticsearchException("failed to index the document [id: " + query.getId() + "]", e); + } + } + + @Override + public void refresh(String indexName, boolean waitForOperation) { + client.admin().indices().refresh(refreshRequest(indexName).force(waitForOperation)).actionGet(); + } + + @Override + public void refresh(Class clazz, boolean waitForOperation) { + ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz); + client.admin().indices() + .refresh(refreshRequest(persistentEntity.getIndexName()).force(waitForOperation)).actionGet(); + } + + @Override + public Boolean addAlias(AliasQuery query) { + Assert.notNull(query.getIndexName(), "No index defined for Alias"); + Assert.notNull(query.getAliasName(), "No alias defined"); + IndicesAliasesRequestBuilder indicesAliasesRequestBuilder = null; + if (query.getFilterBuilder() != null) { + indicesAliasesRequestBuilder = client.admin().indices().prepareAliases().addAlias(query.getIndexName(), query.getAliasName(), query.getFilterBuilder()); + } else if (query.getFilter() != null) { + indicesAliasesRequestBuilder = client.admin().indices().prepareAliases().addAlias(query.getIndexName(), query.getAliasName(), query.getFilter()); + } else { + indicesAliasesRequestBuilder = client.admin().indices().prepareAliases().addAlias(query.getIndexName(), query.getAliasName()); + } + return indicesAliasesRequestBuilder.execute().actionGet().isAcknowledged(); + } + + @Override + public Boolean removeAlias(AliasQuery query) { + Assert.notNull(query.getIndexName(), "No index defined for Alias"); + Assert.notNull(query.getAliasName(), "No alias defined"); + return client.admin().indices().prepareAliases().removeAlias(query.getIndexName(), query.getAliasName()) + .execute().actionGet().isAcknowledged(); + } + + @Override + public Set queryForAlias(String indexName) { + ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest() + .filterRoutingTable(true) + .filterNodes(true) + .filteredIndices(indexName); + Iterator iterator = client.admin().cluster().state(clusterStateRequest).actionGet().getState().getMetaData().aliases().keysIt(); + return newHashSet(iterator); + } + + 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 getPersistentEntityId(Object entity) { + PersistentProperty idProperty = getPersistentEntityFor(entity.getClass()).getIdProperty(); + if (idProperty != null) { + Method getter = idProperty.getGetter(); + if (getter != null) { + try { + Object id = getter.invoke(entity); + if (id != null) { + return String.valueOf(id); + } + } catch (Throwable t) { + t.printStackTrace(); + } + } + } + return null; + } + + private void setPersistentEntityId(Object entity, String id) { + PersistentProperty idProperty = getPersistentEntityFor(entity.getClass()).getIdProperty(); + // Only deal with String because ES generated Ids are strings ! + if (idProperty != null && idProperty.getType().isAssignableFrom(String.class)) { + Method setter = idProperty.getSetter(); + if (setter != null) { + try { + setter.invoke(entity, id); + } catch (Throwable t) { + t.printStackTrace(); + } + } + } + } + + private String[] retrieveIndexNameFromPersistentEntity(Class clazz) { + return new String[]{getPersistentEntityFor(clazz).getIndexName()}; + } + + 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 static String[] toArray(List values) { + String[] valuesAsArray = new String[values.size()]; + return values.toArray(valuesAsArray); + } + + protected ResultsMapper getResultsMapper() { + return resultsMapper; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/EntityMapper.java b/src/main/java/org/springframework/data/elasticsearch/core/EntityMapper.java index 5d00817c1..d3d5ac914 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/EntityMapper.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/EntityMapper.java @@ -26,7 +26,7 @@ import java.io.IOException; */ public interface EntityMapper { - public String mapToString(Object object) throws IOException; + public String mapToString(Object object) throws IOException; - public T mapToObject(String source, Class clazz) throws IOException; + public T mapToObject(String source, Class clazz) throws IOException; } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/FacetedPage.java b/src/main/java/org/springframework/data/elasticsearch/core/FacetedPage.java index 8165b518b..af4164cfa 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/FacetedPage.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/FacetedPage.java @@ -15,13 +15,12 @@ */ package org.springframework.data.elasticsearch.core; +import java.util.List; + import org.springframework.data.domain.Page; import org.springframework.data.elasticsearch.core.facet.FacetResult; -import java.util.List; - /** - * * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak @@ -29,10 +28,9 @@ import java.util.List; */ public interface FacetedPage extends Page { - boolean hasFacets(); + boolean hasFacets(); - List getFacets(); - - FacetResult getFacet(String name); + List getFacets(); + FacetResult getFacet(String name); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/FacetedPageImpl.java b/src/main/java/org/springframework/data/elasticsearch/core/FacetedPageImpl.java index db327e678..353f98960 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/FacetedPageImpl.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/FacetedPageImpl.java @@ -15,15 +15,15 @@ */ package org.springframework.data.elasticsearch.core; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.apache.commons.collections.CollectionUtils; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.facet.FacetResult; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * Container for query result and facet results * @@ -34,37 +34,37 @@ import java.util.Map; */ public class FacetedPageImpl extends PageImpl implements FacetedPage { - private List facets; - private Map mapOfFacets = new HashMap(); + private List facets; + private Map mapOfFacets = new HashMap(); - public FacetedPageImpl(List content) { - super(content); - } + public FacetedPageImpl(List content) { + super(content); + } - public FacetedPageImpl(List content, Pageable pageable, long total) { - super(content, pageable, total); - } + public FacetedPageImpl(List content, Pageable pageable, long total) { + super(content, pageable, total); + } - public FacetedPageImpl(List content, Pageable pageable, long total, List facets) { - super(content, pageable, total); - this.facets = facets; - for (FacetResult facet : facets) { - mapOfFacets.put(facet.getName(), facet); - } - } + public FacetedPageImpl(List content, Pageable pageable, long total, List facets) { + super(content, pageable, total); + this.facets = facets; + for (FacetResult facet : facets) { + mapOfFacets.put(facet.getName(), facet); + } + } - @Override - public boolean hasFacets() { - return CollectionUtils.isNotEmpty(facets); - } + @Override + public boolean hasFacets() { + return CollectionUtils.isNotEmpty(facets); + } - @Override - public List getFacets() { - return facets; - } + @Override + public List getFacets() { + return facets; + } - @Override - public FacetResult getFacet(String name) { - return mapOfFacets.get(name); - } + @Override + public FacetResult getFacet(String name) { + return mapOfFacets.get(name); + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/GetResultMapper.java b/src/main/java/org/springframework/data/elasticsearch/core/GetResultMapper.java index cc150e15e..58fb05838 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/GetResultMapper.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/GetResultMapper.java @@ -23,6 +23,5 @@ import org.elasticsearch.action.get.GetResponse; */ public interface GetResultMapper { - T mapResult(GetResponse response, Class clazz); - + T mapResult(GetResponse response, Class clazz); } 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 1b6ad6f3a..65fb86d75 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/MappingBuilder.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/MappingBuilder.java @@ -15,6 +15,14 @@ */ package org.springframework.data.elasticsearch.core; +import static org.apache.commons.lang.StringUtils.*; +import static org.elasticsearch.common.xcontent.XContentFactory.*; +import static org.springframework.util.StringUtils.*; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Map; + import org.elasticsearch.common.xcontent.XContentBuilder; import org.springframework.core.GenericCollectionTypeResolver; import org.springframework.data.annotation.Transient; @@ -25,15 +33,6 @@ import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.util.ClassTypeInformation; import org.springframework.data.util.TypeInformation; -import java.io.IOException; -import java.util.Arrays; -import java.util.Map; - -import static org.apache.commons.lang.StringUtils.EMPTY; -import static org.apache.commons.lang.StringUtils.isNotBlank; -import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.springframework.util.StringUtils.hasText; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -42,269 +41,267 @@ import static org.springframework.util.StringUtils.hasText; class MappingBuilder { - public static final String FIELD_STORE = "store"; - public static final String FIELD_TYPE = "type"; - public static final String FIELD_INDEX = "index"; - public static final String FIELD_FORMAT = "format"; - public static final String FIELD_SEARCH_ANALYZER = "search_analyzer"; - public static final String FIELD_INDEX_ANALYZER = "index_analyzer"; - public static final String FIELD_PROPERTIES = "properties"; - public static final String FIELD_PARENT = "_parent"; + public static final String FIELD_STORE = "store"; + public static final String FIELD_TYPE = "type"; + public static final String FIELD_INDEX = "index"; + public static final String FIELD_FORMAT = "format"; + public static final String FIELD_SEARCH_ANALYZER = "search_analyzer"; + public static final String FIELD_INDEX_ANALYZER = "index_analyzer"; + public static final String FIELD_PROPERTIES = "properties"; + public static final String FIELD_PARENT = "_parent"; - public static final String INDEX_VALUE_NOT_ANALYZED = "not_analyzed"; - public static final String TYPE_VALUE_STRING = "string"; - public static final String TYPE_VALUE_GEO_POINT = "geo_point"; + public static final String INDEX_VALUE_NOT_ANALYZED = "not_analyzed"; + public static final String TYPE_VALUE_STRING = "string"; + public static final String TYPE_VALUE_GEO_POINT = "geo_point"; - 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, String parentType) throws IOException { + static XContentBuilder buildMapping(Class clazz, String indexType, String idFieldName, String parentType) throws IOException { - XContentBuilder mapping = jsonBuilder().startObject().startObject(indexType); - // Parent - if (hasText(parentType)) { - mapping.startObject(FIELD_PARENT).field(FIELD_TYPE,parentType).endObject(); - } + XContentBuilder mapping = jsonBuilder().startObject().startObject(indexType); + // Parent + if (hasText(parentType)) { + mapping.startObject(FIELD_PARENT).field(FIELD_TYPE, parentType).endObject(); + } - // Properties - XContentBuilder xContentBuilder = mapping.startObject(FIELD_PROPERTIES); + // Properties + XContentBuilder xContentBuilder = mapping.startObject(FIELD_PROPERTIES); - mapEntity(xContentBuilder, clazz, true, idFieldName, EMPTY, false); + mapEntity(xContentBuilder, clazz, true, idFieldName, EMPTY, false); - return xContentBuilder.endObject().endObject().endObject(); - } + return xContentBuilder.endObject().endObject().endObject(); + } - private static void mapEntity(XContentBuilder xContentBuilder, Class clazz, boolean isRootObject, String idFieldName, - String nestedObjectFieldName, boolean nestedAnnotaion) throws IOException { + private static void mapEntity(XContentBuilder xContentBuilder, Class clazz, boolean isRootObject, String idFieldName, + String nestedObjectFieldName, boolean nestedAnnotaion) throws IOException { - java.lang.reflect.Field[] fields = clazz.getDeclaredFields(); + java.lang.reflect.Field[] fields = clazz.getDeclaredFields(); - if (!isRootObject && (isAnyPropertyAnnotatedAsField(fields) || nestedAnnotaion)) { - String type = FieldType.Object.toString().toLowerCase(); - if(nestedAnnotaion){ - type = FieldType.Nested.toString().toLowerCase(); - } - xContentBuilder.startObject(nestedObjectFieldName).field(FIELD_TYPE, type).startObject(FIELD_PROPERTIES); - } + if (!isRootObject && (isAnyPropertyAnnotatedAsField(fields) || nestedAnnotaion)) { + String type = FieldType.Object.toString().toLowerCase(); + if (nestedAnnotaion) { + type = FieldType.Nested.toString().toLowerCase(); + } + xContentBuilder.startObject(nestedObjectFieldName).field(FIELD_TYPE, type).startObject(FIELD_PROPERTIES); + } - for (java.lang.reflect.Field field : fields) { + for (java.lang.reflect.Field field : fields) { - if (field.isAnnotationPresent(Transient.class) || isInIgnoreFields(field)) { - continue; - } - - boolean isGeoField = isGeoField(field); + if (field.isAnnotationPresent(Transient.class) || isInIgnoreFields(field)) { + continue; + } - Field singleField = field.getAnnotation(Field.class); - if (!isGeoField && isEntity(field) && !isAnnotated(field)) { - if(singleField == null){ - continue; - } - boolean nestedField = isNestedField(field); - mapEntity(xContentBuilder, getFieldType(field), false, EMPTY, field.getName(), nestedField); - if(nestedField){ - continue; - } - } + boolean isGeoField = isGeoField(field); - MultiField multiField = field.getAnnotation(MultiField.class); + Field singleField = field.getAnnotation(Field.class); + if (!isGeoField && isEntity(field) && !isAnnotated(field)) { + if (singleField == null) { + continue; + } + boolean nestedField = isNestedField(field); + mapEntity(xContentBuilder, getFieldType(field), false, EMPTY, field.getName(), nestedField); + if (nestedField) { + continue; + } + } - if (isGeoField) { - applyGeoPointFieldMapping(xContentBuilder, field); - } + MultiField multiField = field.getAnnotation(MultiField.class); - if (isRootObject && singleField != null && isIdField(field, idFieldName)) { - applyDefaultIdFieldMapping(xContentBuilder, field); - } else if (multiField != null) { - addMultiFieldMapping(xContentBuilder, field, multiField); - } else if (singleField != null) { - addSingleFieldMapping(xContentBuilder, field, singleField); - } - } + if (isGeoField) { + applyGeoPointFieldMapping(xContentBuilder, field); + } - if (!isRootObject && isAnyPropertyAnnotatedAsField(fields)) { - xContentBuilder.endObject().endObject(); - } + if (isRootObject && singleField != null && isIdField(field, idFieldName)) { + applyDefaultIdFieldMapping(xContentBuilder, field); + } else if (multiField != null) { + addMultiFieldMapping(xContentBuilder, field, multiField); + } else if (singleField != null) { + addSingleFieldMapping(xContentBuilder, field, singleField); + } + } - } + if (!isRootObject && isAnyPropertyAnnotatedAsField(fields)) { + xContentBuilder.endObject().endObject(); + } + } - private static boolean isAnnotated(java.lang.reflect.Field field) { - return field.getAnnotation(Field.class)==null && field.getAnnotation(MultiField.class)==null && field.getAnnotation(GeoPointField.class)==null; - } + private static boolean isAnnotated(java.lang.reflect.Field field) { + return field.getAnnotation(Field.class) == null && field.getAnnotation(MultiField.class) == null && field.getAnnotation(GeoPointField.class) == null; + } - private static void applyGeoPointFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field) throws IOException { - xContentBuilder.startObject(field.getName()); - xContentBuilder.field(FIELD_TYPE, TYPE_VALUE_GEO_POINT) - .endObject(); - } + private static void applyGeoPointFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field) throws IOException { + xContentBuilder.startObject(field.getName()); + xContentBuilder.field(FIELD_TYPE, TYPE_VALUE_GEO_POINT) + .endObject(); + } - private static void applyDefaultIdFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field) - throws IOException { - xContentBuilder.startObject(field.getName()) - .field(FIELD_TYPE, TYPE_VALUE_STRING) - .field(FIELD_INDEX, INDEX_VALUE_NOT_ANALYZED); - xContentBuilder.endObject(); - } + private static void applyDefaultIdFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field) + throws IOException { + xContentBuilder.startObject(field.getName()) + .field(FIELD_TYPE, TYPE_VALUE_STRING) + .field(FIELD_INDEX, INDEX_VALUE_NOT_ANALYZED); + xContentBuilder.endObject(); + } - /** - * Apply mapping for a single @Field annotation - * - * @param xContentBuilder - * @param field - * @param fieldAnnotation - * @throws IOException - */ - private static void addSingleFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field, - Field fieldAnnotation) throws IOException { - xContentBuilder.startObject(field.getName()); - xContentBuilder.field(FIELD_STORE, fieldAnnotation.store()); - if (FieldType.Auto != fieldAnnotation.type()) { - xContentBuilder.field(FIELD_TYPE, fieldAnnotation.type().name().toLowerCase()); - if (FieldType.Date == fieldAnnotation.type() && DateFormat.none != fieldAnnotation.format()) { - xContentBuilder.field(FIELD_FORMAT, DateFormat.custom == fieldAnnotation.format() - ? fieldAnnotation.pattern() : fieldAnnotation.format()); - } - } - if (FieldIndex.not_analyzed == fieldAnnotation.index()) { - xContentBuilder.field(FIELD_INDEX, fieldAnnotation.index().name().toLowerCase()); - } - if (isNotBlank(fieldAnnotation.searchAnalyzer())) { - xContentBuilder.field(FIELD_SEARCH_ANALYZER, fieldAnnotation.searchAnalyzer()); - } - if (isNotBlank(fieldAnnotation.indexAnalyzer())) { - xContentBuilder.field(FIELD_INDEX_ANALYZER, fieldAnnotation.indexAnalyzer()); - } - xContentBuilder.endObject(); - } + /** + * Apply mapping for a single @Field annotation + * + * @param xContentBuilder + * @param field + * @param fieldAnnotation + * @throws IOException + */ + private static void addSingleFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field, + Field fieldAnnotation) throws IOException { + xContentBuilder.startObject(field.getName()); + xContentBuilder.field(FIELD_STORE, fieldAnnotation.store()); + if (FieldType.Auto != fieldAnnotation.type()) { + xContentBuilder.field(FIELD_TYPE, fieldAnnotation.type().name().toLowerCase()); + if (FieldType.Date == fieldAnnotation.type() && DateFormat.none != fieldAnnotation.format()) { + xContentBuilder.field(FIELD_FORMAT, DateFormat.custom == fieldAnnotation.format() + ? fieldAnnotation.pattern() : fieldAnnotation.format()); + } + } + if (FieldIndex.not_analyzed == fieldAnnotation.index()) { + xContentBuilder.field(FIELD_INDEX, fieldAnnotation.index().name().toLowerCase()); + } + if (isNotBlank(fieldAnnotation.searchAnalyzer())) { + xContentBuilder.field(FIELD_SEARCH_ANALYZER, fieldAnnotation.searchAnalyzer()); + } + if (isNotBlank(fieldAnnotation.indexAnalyzer())) { + xContentBuilder.field(FIELD_INDEX_ANALYZER, fieldAnnotation.indexAnalyzer()); + } + xContentBuilder.endObject(); + } - /** - * Apply mapping for a single nested @Field annotation - * - * @param builder - * @param field - * @param annotation - * @throws IOException - */ - private static void addNestedFieldMapping(XContentBuilder builder, java.lang.reflect.Field field, - NestedField annotation) throws IOException { - builder.startObject(field.getName() + "." + annotation.dotSuffix()); - builder.field(FIELD_STORE, annotation.store()); - if (FieldType.Auto != annotation.type()) { - builder.field(FIELD_TYPE, annotation.type().name().toLowerCase()); - } - if (FieldIndex.not_analyzed == annotation.index()) { - builder.field(FIELD_INDEX, annotation.index().name().toLowerCase()); - } - if (isNotBlank(annotation.searchAnalyzer())) { - builder.field(FIELD_SEARCH_ANALYZER, annotation.searchAnalyzer()); - } - if (isNotBlank(annotation.indexAnalyzer())) { - builder.field(FIELD_INDEX_ANALYZER, annotation.indexAnalyzer()); - } - builder.endObject(); - } + /** + * Apply mapping for a single nested @Field annotation + * + * @param builder + * @param field + * @param annotation + * @throws IOException + */ + private static void addNestedFieldMapping(XContentBuilder builder, java.lang.reflect.Field field, + NestedField annotation) throws IOException { + builder.startObject(field.getName() + "." + annotation.dotSuffix()); + builder.field(FIELD_STORE, annotation.store()); + if (FieldType.Auto != annotation.type()) { + builder.field(FIELD_TYPE, annotation.type().name().toLowerCase()); + } + if (FieldIndex.not_analyzed == annotation.index()) { + builder.field(FIELD_INDEX, annotation.index().name().toLowerCase()); + } + if (isNotBlank(annotation.searchAnalyzer())) { + builder.field(FIELD_SEARCH_ANALYZER, annotation.searchAnalyzer()); + } + if (isNotBlank(annotation.indexAnalyzer())) { + builder.field(FIELD_INDEX_ANALYZER, annotation.indexAnalyzer()); + } + builder.endObject(); + } - /** - * Multi field mappings for string type fields, support for sorts and facets - * - * @param builder - * @param field - * @param annotation - * @throws IOException - */ - private static void addMultiFieldMapping(XContentBuilder builder, java.lang.reflect.Field field, - MultiField annotation) throws IOException { - builder.startObject(field.getName()); - builder.field(FIELD_TYPE, "multi_field"); - builder.startObject("fields"); - //add standard field - addSingleFieldMapping(builder, field, annotation.mainField()); - for (NestedField nestedField : annotation.otherFields()) { - addNestedFieldMapping(builder, field, nestedField); - } - builder.endObject(); - builder.endObject(); - } + /** + * Multi field mappings for string type fields, support for sorts and facets + * + * @param builder + * @param field + * @param annotation + * @throws IOException + */ + private static void addMultiFieldMapping(XContentBuilder builder, java.lang.reflect.Field field, + MultiField annotation) throws IOException { + builder.startObject(field.getName()); + builder.field(FIELD_TYPE, "multi_field"); + builder.startObject("fields"); + //add standard field + addSingleFieldMapping(builder, field, annotation.mainField()); + for (NestedField nestedField : annotation.otherFields()) { + addNestedFieldMapping(builder, field, nestedField); + } + builder.endObject(); + builder.endObject(); + } - /** - * Facet field for string type, for other types we don't need it(long, int, double, float) - * - * @param builder - * @param field - * @param annotation - * @throws IOException - */ - private static void addFacetMapping(XContentBuilder builder, java.lang.reflect.Field field, Field annotation) throws IOException { - builder.startObject(FacetRequest.FIELD_UNTOUCHED) - .field(FIELD_TYPE, TYPE_VALUE_STRING) - .field(FIELD_INDEX, INDEX_VALUE_NOT_ANALYZED) - .field(FIELD_STORE, true); - builder.endObject(); - } + /** + * Facet field for string type, for other types we don't need it(long, int, double, float) + * + * @param builder + * @param field + * @param annotation + * @throws IOException + */ + private static void addFacetMapping(XContentBuilder builder, java.lang.reflect.Field field, Field annotation) throws IOException { + builder.startObject(FacetRequest.FIELD_UNTOUCHED) + .field(FIELD_TYPE, TYPE_VALUE_STRING) + .field(FIELD_INDEX, INDEX_VALUE_NOT_ANALYZED) + .field(FIELD_STORE, true); + builder.endObject(); + } - /** - * Sort field for string type, for other types we don't need it(long, int, double, float) - * value of the field should be converted to lowercase and not analise - * - * @param builder - * @param field - * @param annotation - * @throws IOException - */ - private static void addSortMapping(XContentBuilder builder, java.lang.reflect.Field field, Field annotation) throws IOException { - builder.startObject(FacetRequest.FIELD_SORT) - .field(FIELD_TYPE, TYPE_VALUE_STRING) - .field(FIELD_INDEX, "keyword") - .field(FIELD_STORE, true); - builder.endObject(); - } + /** + * Sort field for string type, for other types we don't need it(long, int, double, float) + * value of the field should be converted to lowercase and not analise + * + * @param builder + * @param field + * @param annotation + * @throws IOException + */ + private static void addSortMapping(XContentBuilder builder, java.lang.reflect.Field field, Field annotation) throws IOException { + builder.startObject(FacetRequest.FIELD_SORT) + .field(FIELD_TYPE, TYPE_VALUE_STRING) + .field(FIELD_INDEX, "keyword") + .field(FIELD_STORE, true); + builder.endObject(); + } - protected static boolean isEntity(java.lang.reflect.Field field) { - TypeInformation typeInformation = ClassTypeInformation.from(field.getType()); - Class clazz = getFieldType(field); - boolean isComplexType = !SIMPLE_TYPE_HOLDER.isSimpleType(clazz); - return isComplexType && !Map.class.isAssignableFrom(typeInformation.getType()); - } + protected static boolean isEntity(java.lang.reflect.Field field) { + TypeInformation typeInformation = ClassTypeInformation.from(field.getType()); + Class clazz = getFieldType(field); + boolean isComplexType = !SIMPLE_TYPE_HOLDER.isSimpleType(clazz); + return isComplexType && !Map.class.isAssignableFrom(typeInformation.getType()); + } - protected static Class getFieldType(java.lang.reflect.Field field) { - Class clazz = field.getType(); - TypeInformation typeInformation = ClassTypeInformation.from(clazz); - if (typeInformation.isCollectionLike()) { - clazz = GenericCollectionTypeResolver.getCollectionFieldType(field) != null ? GenericCollectionTypeResolver.getCollectionFieldType(field) : typeInformation.getComponentType().getType(); - } - return clazz; - } + protected static Class getFieldType(java.lang.reflect.Field field) { + Class clazz = field.getType(); + TypeInformation typeInformation = ClassTypeInformation.from(clazz); + if (typeInformation.isCollectionLike()) { + clazz = GenericCollectionTypeResolver.getCollectionFieldType(field) != null ? GenericCollectionTypeResolver.getCollectionFieldType(field) : typeInformation.getComponentType().getType(); + } + return clazz; + } - 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()); + } - private static boolean isInIgnoreFields(java.lang.reflect.Field field) { - Field fieldAnnotation = field.getAnnotation(Field.class); - if ( null != fieldAnnotation ) { - String [] ignoreFields = fieldAnnotation.ignoreFields(); - return Arrays.asList(ignoreFields).contains(field.getName()); - } - return false; - } + private static boolean isInIgnoreFields(java.lang.reflect.Field field) { + Field fieldAnnotation = field.getAnnotation(Field.class); + if (null != fieldAnnotation) { + String[] ignoreFields = fieldAnnotation.ignoreFields(); + return Arrays.asList(ignoreFields).contains(field.getName()); + } + return false; + } - private static boolean isNestedField(java.lang.reflect.Field field) { - Field fieldAnnotation = field.getAnnotation(Field.class); - return fieldAnnotation != null && (FieldType.Nested == fieldAnnotation.type() || FieldType.Object == fieldAnnotation.type()); - } - - private static boolean isGeoField(java.lang.reflect.Field field) { - return field.getType() == GeoPoint.class || field.getAnnotation(GeoPointField.class) != null; - } + private static boolean isNestedField(java.lang.reflect.Field field) { + Field fieldAnnotation = field.getAnnotation(Field.class); + return fieldAnnotation != null && (FieldType.Nested == fieldAnnotation.type() || FieldType.Object == fieldAnnotation.type()); + } + private static boolean isGeoField(java.lang.reflect.Field field) { + return field.getType() == GeoPoint.class || field.getAnnotation(GeoPointField.class) != null; + } } 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 327a4a849..27d4ea8ab 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/ResultsMapper.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/ResultsMapper.java @@ -25,6 +25,5 @@ package org.springframework.data.elasticsearch.core; public interface ResultsMapper extends SearchResultMapper, GetResultMapper { - EntityMapper getEntityMapper(); - + EntityMapper getEntityMapper(); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/SearchResultMapper.java b/src/main/java/org/springframework/data/elasticsearch/core/SearchResultMapper.java index 22791877e..d93d90ba1 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/SearchResultMapper.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/SearchResultMapper.java @@ -23,6 +23,5 @@ import org.springframework.data.domain.Pageable; */ public interface SearchResultMapper { - FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable); - + FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable); } 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 ba2c10106..fe5c154b0 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 @@ -15,6 +15,8 @@ */ package org.springframework.data.elasticsearch.core.convert; +import java.util.Date; + import org.joda.time.DateTimeZone; import org.joda.time.LocalDateTime; import org.joda.time.ReadableInstant; @@ -22,11 +24,9 @@ import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import org.springframework.core.convert.converter.Converter; -import java.util.Date; - /** * DateTimeConverters - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -74,5 +74,4 @@ public final class DateTimeConverters { } } - } 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 802999ef6..2a3c89e10 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 @@ -22,7 +22,7 @@ import org.springframework.data.mapping.context.MappingContext; /** * ElasticsearchConverter - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -31,16 +31,15 @@ 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.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 5ef0003c6..c3579e35e 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 @@ -28,7 +28,7 @@ import org.springframework.util.Assert; /** * MappingElasticsearchConverter - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -62,5 +62,4 @@ public class MappingElasticsearchConverter implements ElasticsearchConverter, Ap public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } - } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/AbstractFacetRequest.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/AbstractFacetRequest.java index 853778bdf..569b0e325 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/AbstractFacetRequest.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/AbstractFacetRequest.java @@ -22,24 +22,24 @@ import org.springframework.util.Assert; */ public abstract class AbstractFacetRequest implements FacetRequest { - private String name; - private boolean applyQueryFilter; + private String name; + private boolean applyQueryFilter; - public AbstractFacetRequest(String name) { - Assert.hasText(name, "Facet can't be null or empty !!!"); - this.name = name; - } + public AbstractFacetRequest(String name) { + Assert.hasText(name, "Facet can't be null or empty !!!"); + this.name = name; + } - protected String getName(){ - return name; - } + protected String getName() { + return name; + } - public void setApplyQueryFilter(boolean applyQueryFilter) { - this.applyQueryFilter = applyQueryFilter; - } + public void setApplyQueryFilter(boolean applyQueryFilter) { + this.applyQueryFilter = applyQueryFilter; + } - @Override - public boolean applyQueryFilter() { - return applyQueryFilter; - } + @Override + public boolean applyQueryFilter() { + return applyQueryFilter; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/AbstactFacetResult.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/AbstractFacetResult.java similarity index 63% rename from src/main/java/org/springframework/data/elasticsearch/core/facet/AbstactFacetResult.java rename to src/main/java/org/springframework/data/elasticsearch/core/facet/AbstractFacetResult.java index d1f7ea436..02294d508 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/AbstactFacetResult.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/AbstractFacetResult.java @@ -23,24 +23,24 @@ import org.springframework.util.Assert; * @author Artur Konczak * @author Jonathan Yan */ -public class AbstactFacetResult implements FacetResult { +public class AbstractFacetResult implements FacetResult { - private final String name; - private final FacetType type; + private final String name; + private final FacetType type; - protected AbstactFacetResult(String name, FacetType type) { - Assert.hasText(name, "Facet name can't be null and should have a value"); - this.name = name; - this.type = type; - } + protected AbstractFacetResult(String name, FacetType type) { + Assert.hasText(name, "Facet name can't be null and should have a value"); + this.name = name; + this.type = type; + } - @Override - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public FacetType getType() { - return type; - } + @Override + public FacetType getType() { + return type; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/DefaultFacetMapper.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/DefaultFacetMapper.java index 9889b2bb5..8f82ecd80 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/DefaultFacetMapper.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/DefaultFacetMapper.java @@ -15,6 +15,9 @@ */ package org.springframework.data.elasticsearch.core.facet; +import java.util.ArrayList; +import java.util.List; + import org.elasticsearch.search.facet.Facet; import org.elasticsearch.search.facet.histogram.HistogramFacet; import org.elasticsearch.search.facet.range.RangeFacet; @@ -22,61 +25,57 @@ import org.elasticsearch.search.facet.statistical.StatisticalFacet; import org.elasticsearch.search.facet.terms.TermsFacet; import org.springframework.data.elasticsearch.core.facet.result.*; -import java.util.ArrayList; -import java.util.List; - /** * @author Artur Konczak * @author Petar Tahchiev */ public class DefaultFacetMapper { - public static FacetResult parse(Facet facet) { - if (facet instanceof TermsFacet) { - return parseTerm((TermsFacet) facet); - } + public static FacetResult parse(Facet facet) { + if (facet instanceof TermsFacet) { + return parseTerm((TermsFacet) facet); + } - if (facet instanceof RangeFacet) { - return parseRange((RangeFacet) facet); - } + if (facet instanceof RangeFacet) { + return parseRange((RangeFacet) facet); + } - if (facet instanceof StatisticalFacet) { - return parseStatistical((StatisticalFacet) facet); - } + if (facet instanceof StatisticalFacet) { + return parseStatistical((StatisticalFacet) facet); + } - if (facet instanceof HistogramFacet) { - return parseHistogram((HistogramFacet) facet); - } + if (facet instanceof HistogramFacet) { + return parseHistogram((HistogramFacet) facet); + } - return null; - } + return null; + } - private static FacetResult parseTerm(TermsFacet facet) { - List entries = new ArrayList(); - for (TermsFacet.Entry entry : facet.getEntries()) { - entries.add(new Term(entry.getTerm().toString(), entry.getCount())); - } - return new TermResult(facet.getName(), entries); - } + private static FacetResult parseTerm(TermsFacet facet) { + List entries = new ArrayList(); + for (TermsFacet.Entry entry : facet.getEntries()) { + entries.add(new Term(entry.getTerm().toString(), entry.getCount())); + } + return new TermResult(facet.getName(), entries); + } - private static FacetResult parseRange(RangeFacet facet) { - List entries = new ArrayList(); - for (RangeFacet.Entry entry : facet.getEntries()) { - entries.add(new Range(entry.getFrom() == Double.NEGATIVE_INFINITY ? null : entry.getFrom(), entry.getTo() == Double.POSITIVE_INFINITY ? null : entry.getTo(), entry.getCount(), entry.getTotal(), entry.getTotalCount(), entry.getMin(), entry.getMax())); - } - return new RangeResult(facet.getName(), entries); - } + private static FacetResult parseRange(RangeFacet facet) { + List entries = new ArrayList(); + for (RangeFacet.Entry entry : facet.getEntries()) { + entries.add(new Range(entry.getFrom() == Double.NEGATIVE_INFINITY ? null : entry.getFrom(), entry.getTo() == Double.POSITIVE_INFINITY ? null : entry.getTo(), entry.getCount(), entry.getTotal(), entry.getTotalCount(), entry.getMin(), entry.getMax())); + } + return new RangeResult(facet.getName(), entries); + } - private static FacetResult parseStatistical(StatisticalFacet facet) { - return new StatisticalResult(facet.getName(), facet.getCount(), facet.getMax(), facet.getMin(), facet.getMean(), facet.getStdDeviation(), facet.getSumOfSquares(), facet.getTotal(), facet.getVariance()); - } - - private static FacetResult parseHistogram(HistogramFacet facet) { - List entries = new ArrayList(); - for (HistogramFacet.Entry entry : facet.getEntries()) { - entries.add(new IntervalUnit(entry.getKey(), entry.getCount(), entry.getTotalCount(), entry.getTotal(), entry.getMean(), entry.getMin(), entry.getMax())); - } - return new HistogramResult(facet.getName(), entries); - } + private static FacetResult parseStatistical(StatisticalFacet facet) { + return new StatisticalResult(facet.getName(), facet.getCount(), facet.getMax(), facet.getMin(), facet.getMean(), facet.getStdDeviation(), facet.getSumOfSquares(), facet.getTotal(), facet.getVariance()); + } + private static FacetResult parseHistogram(HistogramFacet facet) { + List entries = new ArrayList(); + for (HistogramFacet.Entry entry : facet.getEntries()) { + entries.add(new IntervalUnit(entry.getKey(), entry.getCount(), entry.getTotalCount(), entry.getTotal(), entry.getMean(), entry.getMin(), entry.getMax())); + } + return new HistogramResult(facet.getName(), entries); + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetRequest.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetRequest.java index 583924ed2..a15a0a6b0 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetRequest.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetRequest.java @@ -22,11 +22,10 @@ import org.elasticsearch.search.facet.FacetBuilder; */ public interface FacetRequest { - public static final String FIELD_UNTOUCHED = "untouched"; - public static final String FIELD_SORT = "sort"; + public static final String FIELD_UNTOUCHED = "untouched"; + public static final String FIELD_SORT = "sort"; - FacetBuilder getFacet(); - - boolean applyQueryFilter(); + FacetBuilder getFacet(); + boolean applyQueryFilter(); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetResult.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetResult.java index 678cafeea..eac98b010 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetResult.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetResult.java @@ -22,12 +22,10 @@ package org.springframework.data.elasticsearch.core.facet; * @author Mohsin Husen * @author Artur Konczak * @author Jonathan Yan - * */ public interface FacetResult { - String getName(); - - FacetType getType(); + String getName(); + FacetType getType(); } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetType.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetType.java index b4e61ad6b..c913ee107 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetType.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/FacetType.java @@ -21,6 +21,6 @@ package org.springframework.data.elasticsearch.core.facet; */ public enum FacetType { - term, range, histogram, statistical + term, range, histogram, statistical } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/HistogramFacetRequest.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/HistogramFacetRequest.java index b76f6c182..32033d649 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/HistogramFacetRequest.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/HistogramFacetRequest.java @@ -15,6 +15,8 @@ */ package org.springframework.data.elasticsearch.core.facet.request; +import java.util.concurrent.TimeUnit; + import org.apache.commons.lang.StringUtils; import org.elasticsearch.search.facet.FacetBuilder; import org.elasticsearch.search.facet.FacetBuilders; @@ -22,48 +24,46 @@ import org.elasticsearch.search.facet.histogram.HistogramFacetBuilder; import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest; import org.springframework.util.Assert; -import java.util.concurrent.TimeUnit; - /** * @author Artur Konczak * @author Mohsin Husen */ public class HistogramFacetRequest extends AbstractFacetRequest { - private String field; - private long interval; - private TimeUnit timeUnit; + private String field; + private long interval; + private TimeUnit timeUnit; - public HistogramFacetRequest(String name) { - super(name); - } + public HistogramFacetRequest(String name) { + super(name); + } - public void setField(String field) { - this.field = field; - } + public void setField(String field) { + this.field = field; + } - public void setInterval(long interval) { - this.interval = interval; - } + public void setInterval(long interval) { + this.interval = interval; + } - public void setTimeUnit(TimeUnit timeUnit) { - this.timeUnit = timeUnit; - } + public void setTimeUnit(TimeUnit timeUnit) { + this.timeUnit = timeUnit; + } - public FacetBuilder getFacet() { - Assert.notNull(getName(), "Facet name can't be a null !!!"); - Assert.isTrue(StringUtils.isNotBlank(field), "Please select field on which to build the facet !!!"); - Assert.isTrue(interval > 0, "Please provide interval as positive value greater them zero !!!"); + public FacetBuilder getFacet() { + Assert.notNull(getName(), "Facet name can't be a null !!!"); + Assert.isTrue(StringUtils.isNotBlank(field), "Please select field on which to build the facet !!!"); + Assert.isTrue(interval > 0, "Please provide interval as positive value greater them zero !!!"); - HistogramFacetBuilder builder = FacetBuilders.histogramFacet(getName()); - builder.field(field); + HistogramFacetBuilder builder = FacetBuilders.histogramFacet(getName()); + builder.field(field); - if (timeUnit != null) { - builder.interval(interval, timeUnit); - } else { - builder.interval(interval); - } + if (timeUnit != null) { + builder.interval(interval, timeUnit); + } else { + builder.interval(interval); + } - return builder; - } + return builder; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/HistogramFacetRequestBuilder.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/HistogramFacetRequestBuilder.java index e18c4eb72..c9c3fadd9 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/HistogramFacetRequestBuilder.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/HistogramFacetRequestBuilder.java @@ -15,42 +15,42 @@ */ package org.springframework.data.elasticsearch.core.facet.request; -import org.springframework.data.elasticsearch.core.facet.FacetRequest; - import java.util.concurrent.TimeUnit; +import org.springframework.data.elasticsearch.core.facet.FacetRequest; + /** * @author Artur Konczak */ public class HistogramFacetRequestBuilder { - HistogramFacetRequest result; + HistogramFacetRequest result; - public HistogramFacetRequestBuilder(String name) { - result = new HistogramFacetRequest(name); - } + public HistogramFacetRequestBuilder(String name) { + result = new HistogramFacetRequest(name); + } - public HistogramFacetRequestBuilder field(String field) { - result.setField(field); - return this; - } + public HistogramFacetRequestBuilder field(String field) { + result.setField(field); + return this; + } - public HistogramFacetRequestBuilder interval(long interval) { - result.setInterval(interval); - return this; - } + public HistogramFacetRequestBuilder interval(long interval) { + result.setInterval(interval); + return this; + } - public HistogramFacetRequestBuilder timeUnit(TimeUnit timeUnit) { - result.setTimeUnit(timeUnit); - return this; - } + public HistogramFacetRequestBuilder timeUnit(TimeUnit timeUnit) { + result.setTimeUnit(timeUnit); + return this; + } - public FacetRequest build() { - return result; - } + public FacetRequest build() { + return result; + } - public HistogramFacetRequestBuilder applyQueryFilter() { - result.setApplyQueryFilter(true); - return this; - } + public HistogramFacetRequestBuilder applyQueryFilter() { + result.setApplyQueryFilter(true); + return this; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/NativeFacetRequest.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/NativeFacetRequest.java index 98c401157..c9a36828e 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/NativeFacetRequest.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/NativeFacetRequest.java @@ -24,25 +24,25 @@ import org.springframework.data.elasticsearch.core.facet.FacetRequest; */ public class NativeFacetRequest implements FacetRequest { - private FacetBuilder facet; - private boolean applyQueryFilter; + private FacetBuilder facet; + private boolean applyQueryFilter; - public NativeFacetRequest(FacetBuilder facet) { - this(facet, false); - } + public NativeFacetRequest(FacetBuilder facet) { + this(facet, false); + } - public NativeFacetRequest(FacetBuilder facet, boolean applyQueryFilter) { - this.facet = facet; - this.applyQueryFilter = applyQueryFilter; - } + public NativeFacetRequest(FacetBuilder facet, boolean applyQueryFilter) { + this.facet = facet; + this.applyQueryFilter = applyQueryFilter; + } - @Override - public FacetBuilder getFacet() { - return facet; - } + @Override + public FacetBuilder getFacet() { + return facet; + } - @Override - public boolean applyQueryFilter() { - return applyQueryFilter; - } + @Override + public boolean applyQueryFilter() { + return applyQueryFilter; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/RangeFacetRequest.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/RangeFacetRequest.java index 3fc4f23f8..511aa9029 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/RangeFacetRequest.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/RangeFacetRequest.java @@ -15,6 +15,9 @@ */ package org.springframework.data.elasticsearch.core.facet.request; +import java.util.ArrayList; +import java.util.List; + import org.apache.commons.lang.StringUtils; import org.elasticsearch.search.facet.FacetBuilder; import org.elasticsearch.search.facet.FacetBuilders; @@ -22,9 +25,6 @@ import org.elasticsearch.search.facet.range.RangeFacetBuilder; import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest; import org.springframework.util.Assert; -import java.util.ArrayList; -import java.util.List; - /** * Range facet for numeric fields * @@ -32,56 +32,56 @@ import java.util.List; */ public class RangeFacetRequest extends AbstractFacetRequest { - private String field; - private String keyField; - private String valueField; + private String field; + private String keyField; + private String valueField; - private List from = new ArrayList(); - private List to = new ArrayList(); + private List from = new ArrayList(); + private List to = new ArrayList(); - public RangeFacetRequest(String name) { - super(name); - } + public RangeFacetRequest(String name) { + super(name); + } - public void setField(String field) { - this.field = field; - } + public void setField(String field) { + this.field = field; + } - public void setFields(String keyField, String valueField) { - this.keyField = keyField; - this.valueField = valueField; - } + public void setFields(String keyField, String valueField) { + this.keyField = keyField; + this.valueField = valueField; + } - public void range(Double from, Double to) { - if (from == null) { - this.from.add(Double.NEGATIVE_INFINITY); - } else { - this.from.add(from); - } + public void range(Double from, Double to) { + if (from == null) { + this.from.add(Double.NEGATIVE_INFINITY); + } else { + this.from.add(from); + } - if (to == null) { - this.to.add(Double.POSITIVE_INFINITY); - } else { - this.to.add(to); - } - } + if (to == null) { + this.to.add(Double.POSITIVE_INFINITY); + } else { + this.to.add(to); + } + } - @Override - public FacetBuilder getFacet() { - Assert.notNull(getName(), "Facet name can't be a null !!!"); - Assert.isTrue(StringUtils.isNotBlank(field) || StringUtils.isNotBlank(keyField) && StringUtils.isNotBlank(valueField), "Please select field or key field and value field !!!"); + @Override + public FacetBuilder getFacet() { + Assert.notNull(getName(), "Facet name can't be a null !!!"); + Assert.isTrue(StringUtils.isNotBlank(field) || StringUtils.isNotBlank(keyField) && StringUtils.isNotBlank(valueField), "Please select field or key field and value field !!!"); - RangeFacetBuilder builder = FacetBuilders.rangeFacet(getName()); - if (StringUtils.isNotBlank(keyField)) { - builder.keyField(keyField).valueField(valueField); - } else { - builder.field(field); - } - Assert.notEmpty(from, "Please select at last one range"); - Assert.notEmpty(to, "Please select at last one range"); - for (int i = 0; i < from.size(); i++) { - builder.addRange(from.get(i), to.get(i)); - } - return builder; - } + RangeFacetBuilder builder = FacetBuilders.rangeFacet(getName()); + if (StringUtils.isNotBlank(keyField)) { + builder.keyField(keyField).valueField(valueField); + } else { + builder.field(field); + } + Assert.notEmpty(from, "Please select at last one range"); + Assert.notEmpty(to, "Please select at last one range"); + for (int i = 0; i < from.size(); i++) { + builder.addRange(from.get(i), to.get(i)); + } + return builder; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/RangeFacetRequestBuilder.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/RangeFacetRequestBuilder.java index 037dabfd0..30ad3e11a 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/RangeFacetRequestBuilder.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/RangeFacetRequestBuilder.java @@ -24,44 +24,44 @@ import org.springframework.data.elasticsearch.core.facet.FacetRequest; */ public class RangeFacetRequestBuilder { - RangeFacetRequest result; + RangeFacetRequest result; - public RangeFacetRequestBuilder(String name) { - result = new RangeFacetRequest(name); - } + public RangeFacetRequestBuilder(String name) { + result = new RangeFacetRequest(name); + } - public RangeFacetRequestBuilder field(String field) { - result.setField(field); - return this; - } + public RangeFacetRequestBuilder field(String field) { + result.setField(field); + return this; + } - public RangeFacetRequestBuilder fields(String keyField, String valueField) { - result.setFields(keyField, valueField); - return this; - } + public RangeFacetRequestBuilder fields(String keyField, String valueField) { + result.setFields(keyField, valueField); + return this; + } - public RangeFacetRequestBuilder range(double from, double to) { - result.range(from, to); - return this; - } + public RangeFacetRequestBuilder range(double from, double to) { + result.range(from, to); + return this; + } - public RangeFacetRequestBuilder from(double from) { - result.range(from, null); - return this; - } + public RangeFacetRequestBuilder from(double from) { + result.range(from, null); + return this; + } - public RangeFacetRequestBuilder to(double to) { - result.range(null, to); - return this; - } + public RangeFacetRequestBuilder to(double to) { + result.range(null, to); + return this; + } - public RangeFacetRequestBuilder applyQueryFilter() { - result.setApplyQueryFilter(true); - return this; - } + public RangeFacetRequestBuilder applyQueryFilter() { + result.setApplyQueryFilter(true); + return this; + } - public FacetRequest build() { - return result; - } + public FacetRequest build() { + return result; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/StatisticalFacetRequest.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/StatisticalFacetRequest.java index a6bafb46e..bf28e194f 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/StatisticalFacetRequest.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/StatisticalFacetRequest.java @@ -28,33 +28,33 @@ import org.springframework.util.Assert; */ public class StatisticalFacetRequest extends AbstractFacetRequest { - private String field; + private String field; - private String[] fields; + private String[] fields; - public StatisticalFacetRequest(String name) { - super(name); - } + public StatisticalFacetRequest(String name) { + super(name); + } - public void setField(String field) { - this.field = field; - } + public void setField(String field) { + this.field = field; + } - public void setFields(String... fields) { - this.fields = fields; - } + public void setFields(String... fields) { + this.fields = fields; + } - public FacetBuilder getFacet() { - Assert.notNull(getName(), "Facet name can't be a null !!!"); - Assert.isTrue(StringUtils.isNotBlank(field) && fields == null, "Please select field or fields on which to build the facets !!!"); + public FacetBuilder getFacet() { + Assert.notNull(getName(), "Facet name can't be a null !!!"); + Assert.isTrue(StringUtils.isNotBlank(field) && fields == null, "Please select field or fields on which to build the facets !!!"); - StatisticalFacetBuilder builder = FacetBuilders.statisticalFacet(getName()); - if (ArrayUtils.isNotEmpty(fields)) { - builder.fields(fields); - } else { - builder.field(field); - } + StatisticalFacetBuilder builder = FacetBuilders.statisticalFacet(getName()); + if (ArrayUtils.isNotEmpty(fields)) { + builder.fields(fields); + } else { + builder.field(field); + } - return builder; - } + return builder; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/StatisticalFacetRequestBuilder.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/StatisticalFacetRequestBuilder.java index 2573172e7..6644eeaba 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/StatisticalFacetRequestBuilder.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/StatisticalFacetRequestBuilder.java @@ -22,28 +22,28 @@ import org.springframework.data.elasticsearch.core.facet.FacetRequest; */ public class StatisticalFacetRequestBuilder { - StatisticalFacetRequest result; + StatisticalFacetRequest result; - public StatisticalFacetRequestBuilder(String name) { - result = new StatisticalFacetRequest(name); - } + public StatisticalFacetRequestBuilder(String name) { + result = new StatisticalFacetRequest(name); + } - public StatisticalFacetRequestBuilder field(String field) { - result.setField(field); - return this; - } + public StatisticalFacetRequestBuilder field(String field) { + result.setField(field); + return this; + } - public StatisticalFacetRequestBuilder fields(String... fields) { - result.setFields(fields); - return this; - } + public StatisticalFacetRequestBuilder fields(String... fields) { + result.setFields(fields); + return this; + } - public StatisticalFacetRequestBuilder applyQueryFilter() { - result.setApplyQueryFilter(true); - return this; - } + public StatisticalFacetRequestBuilder applyQueryFilter() { + result.setApplyQueryFilter(true); + return this; + } - public FacetRequest build() { - return result; - } + public FacetRequest build() { + return result; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetOrder.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetOrder.java index 5741cec3b..deb7fd828 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetOrder.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetOrder.java @@ -21,6 +21,6 @@ package org.springframework.data.elasticsearch.core.facet.request; */ public enum TermFacetOrder { - ascTerm, descTerm, ascCount, descCount; + ascTerm, descTerm, ascCount, descCount; } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetRequest.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetRequest.java index ae7609499..125ab569c 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetRequest.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetRequest.java @@ -31,78 +31,78 @@ import org.springframework.util.Assert; */ public class TermFacetRequest extends AbstractFacetRequest { - private String[] fields; - private Object[] excludeTerms; - private int size = 10; - private TermFacetOrder order = TermFacetOrder.descCount; - private boolean allTerms = false; - private String regex = null; - private int regexFlag = 0; + private String[] fields; + private Object[] excludeTerms; + private int size = 10; + private TermFacetOrder order = TermFacetOrder.descCount; + private boolean allTerms = false; + private String regex = null; + private int regexFlag = 0; - public TermFacetRequest(String name) { - super(name); - } + public TermFacetRequest(String name) { + super(name); + } - public void setFields(String... fields) { - this.fields = fields; - } + public void setFields(String... fields) { + this.fields = fields; + } - public void setSize(int size) { - Assert.isTrue(size >= 0, "Size should be bigger then zero !!!"); - this.size = size; - } + public void setSize(int size) { + Assert.isTrue(size >= 0, "Size should be bigger then zero !!!"); + this.size = size; + } - public void setOrder(TermFacetOrder order) { - this.order = order; - } + public void setOrder(TermFacetOrder order) { + this.order = order; + } - public void setExcludeTerms(Object... excludeTerms) { - this.excludeTerms = excludeTerms; - } + public void setExcludeTerms(Object... excludeTerms) { + this.excludeTerms = excludeTerms; + } - public void setAllTerms(boolean allTerms) { - this.allTerms = allTerms; - } + public void setAllTerms(boolean allTerms) { + this.allTerms = allTerms; + } - public void setRegex(String regex) { - this.regex = regex; - } + public void setRegex(String regex) { + this.regex = regex; + } - public void setRegex(String regex, int regexFlag) { - this.regex = regex; - this.regexFlag = regexFlag; - } + public void setRegex(String regex, int regexFlag) { + this.regex = regex; + this.regexFlag = regexFlag; + } - @Override - public FacetBuilder getFacet() { - Assert.notEmpty(fields, "Please select at last one field !!!"); - TermsFacetBuilder builder = FacetBuilders.termsFacet(getName()).fields(fields).size(size); - switch (order) { + @Override + public FacetBuilder getFacet() { + Assert.notEmpty(fields, "Please select at last one field !!!"); + TermsFacetBuilder builder = FacetBuilders.termsFacet(getName()).fields(fields).size(size); + switch (order) { - case descTerm: - builder.order(TermsFacet.ComparatorType.REVERSE_TERM); - break; - case ascTerm: - builder.order(TermsFacet.ComparatorType.TERM); - break; - case ascCount: - builder.order(TermsFacet.ComparatorType.REVERSE_COUNT); - break; - default: - builder.order(TermsFacet.ComparatorType.COUNT); - } - if (ArrayUtils.isNotEmpty(excludeTerms)) { - builder.exclude(excludeTerms); - } + case descTerm: + builder.order(TermsFacet.ComparatorType.REVERSE_TERM); + break; + case ascTerm: + builder.order(TermsFacet.ComparatorType.TERM); + break; + case ascCount: + builder.order(TermsFacet.ComparatorType.REVERSE_COUNT); + break; + default: + builder.order(TermsFacet.ComparatorType.COUNT); + } + if (ArrayUtils.isNotEmpty(excludeTerms)) { + builder.exclude(excludeTerms); + } - if (allTerms) { - builder.allTerms(allTerms); - } + if (allTerms) { + builder.allTerms(allTerms); + } - if (StringUtils.isNotBlank(regex)) { - builder.regex(regex, regexFlag); - } + if (StringUtils.isNotBlank(regex)) { + builder.regex(regex, regexFlag); + } - return builder; - } + return builder; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetRequestBuilder.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetRequestBuilder.java index ac9875684..b23e751c0 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetRequestBuilder.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/request/TermFacetRequestBuilder.java @@ -24,68 +24,68 @@ import org.springframework.data.elasticsearch.core.facet.FacetRequest; */ public class TermFacetRequestBuilder { - private TermFacetRequest result; + private TermFacetRequest result; - public TermFacetRequestBuilder(String name) { - result = new TermFacetRequest(name); - } + public TermFacetRequestBuilder(String name) { + result = new TermFacetRequest(name); + } - public TermFacetRequestBuilder fields(String... fields) { - result.setFields(fields); - return this; - } + public TermFacetRequestBuilder fields(String... fields) { + result.setFields(fields); + return this; + } - public TermFacetRequestBuilder size(int size) { - result.setSize(size); - return this; - } + public TermFacetRequestBuilder size(int size) { + result.setSize(size); + return this; + } - public TermFacetRequestBuilder excludeTerms(Object... terms) { - result.setExcludeTerms(terms); - return this; - } + public TermFacetRequestBuilder excludeTerms(Object... terms) { + result.setExcludeTerms(terms); + return this; + } - public TermFacetRequestBuilder allTerms() { - result.setAllTerms(true); - return this; - } + public TermFacetRequestBuilder allTerms() { + result.setAllTerms(true); + return this; + } - public TermFacetRequestBuilder regex(String regex) { - result.setRegex(regex); - return this; - } + public TermFacetRequestBuilder regex(String regex) { + result.setRegex(regex); + return this; + } - public TermFacetRequestBuilder regex(String regex, int regexFlag) { - result.setRegex(regex, regexFlag); - return this; - } + public TermFacetRequestBuilder regex(String regex, int regexFlag) { + result.setRegex(regex, regexFlag); + return this; + } - public TermFacetRequestBuilder ascTerm() { - result.setOrder(TermFacetOrder.ascTerm); - return this; - } + public TermFacetRequestBuilder ascTerm() { + result.setOrder(TermFacetOrder.ascTerm); + return this; + } - public TermFacetRequestBuilder descTerm() { - result.setOrder(TermFacetOrder.descTerm); - return this; - } + public TermFacetRequestBuilder descTerm() { + result.setOrder(TermFacetOrder.descTerm); + return this; + } - public TermFacetRequestBuilder ascCount() { - result.setOrder(TermFacetOrder.ascCount); - return this; - } + public TermFacetRequestBuilder ascCount() { + result.setOrder(TermFacetOrder.ascCount); + return this; + } - public TermFacetRequestBuilder descCount() { - result.setOrder(TermFacetOrder.descCount); - return this; - } + public TermFacetRequestBuilder descCount() { + result.setOrder(TermFacetOrder.descCount); + return this; + } - public TermFacetRequestBuilder applyQueryFilter() { - result.setApplyQueryFilter(true); - return this; - } + public TermFacetRequestBuilder applyQueryFilter() { + result.setApplyQueryFilter(true); + return this; + } - public FacetRequest build() { - return result; - } + public FacetRequest build() { + return result; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/HistogramResult.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/HistogramResult.java index e7ec62c9a..4f1f3e653 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/HistogramResult.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/HistogramResult.java @@ -15,25 +15,24 @@ */ package org.springframework.data.elasticsearch.core.facet.result; -import org.springframework.data.elasticsearch.core.facet.AbstactFacetResult; -import org.springframework.data.elasticsearch.core.facet.FacetType; - import java.util.List; +import org.springframework.data.elasticsearch.core.facet.AbstractFacetResult; +import org.springframework.data.elasticsearch.core.facet.FacetType; + /** * @author Artur Konczak */ -public class HistogramResult extends AbstactFacetResult { +public class HistogramResult extends AbstractFacetResult { - private List terms; + private List terms; - public HistogramResult(String name, List terms) { - super(name, FacetType.term); - this.terms = terms; - } - - public List getIntervalUnit() { - return terms; - } + public HistogramResult(String name, List terms) { + super(name, FacetType.term); + this.terms = terms; + } + public List getIntervalUnit() { + return terms; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/IntervalUnit.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/IntervalUnit.java index 707a82602..99b1cfd0d 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/IntervalUnit.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/IntervalUnit.java @@ -28,64 +28,64 @@ import java.util.Date; */ public class IntervalUnit { - private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - long key; - long count; - long totalCount; - double total; - double mean; - double min; - double max; + long key; + long count; + long totalCount; + double total; + double mean; + double min; + double max; - public IntervalUnit(long key, long count, long totalCount, double total, double mean, double min, double max) { - this.key = key; - this.count = count; - this.totalCount = totalCount; - this.total = total; - this.mean = mean; - this.min = min; - this.max = max; - } + public IntervalUnit(long key, long count, long totalCount, double total, double mean, double min, double max) { + this.key = key; + this.count = count; + this.totalCount = totalCount; + this.total = total; + this.mean = mean; + this.min = min; + this.max = max; + } - public long getKey() { - return key; - } + public long getKey() { + return key; + } - public long getCount() { - return count; - } + public long getCount() { + return count; + } - public long getTotalCount() { - return totalCount; - } + public long getTotalCount() { + return totalCount; + } - public double getTotal() { - return total; - } + public double getTotal() { + return total; + } - public double getMean() { - return mean; - } + public double getMean() { + return mean; + } - public double getMin() { - return min; - } + public double getMin() { + return min; + } - public double getMax() { - return max; - } + public double getMax() { + return max; + } - @Override - public String toString() { - return "IntervalUnit{" + - "key=" + format.format(new Date(key)) + - ", count=" + count + - ", totalCount=" + totalCount + - ", total=" + total + - ", mean=" + mean + - ", min=" + min + - ", max=" + max + - '}'; - } + @Override + public String toString() { + return "IntervalUnit{" + + "key=" + format.format(new Date(key)) + + ", count=" + count + + ", totalCount=" + totalCount + + ", total=" + total + + ", mean=" + mean + + ", min=" + min + + ", max=" + max + + '}'; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/Range.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/Range.java index 25c86ba6b..b7b3cd9fd 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/Range.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/Range.java @@ -25,54 +25,54 @@ package org.springframework.data.elasticsearch.core.facet.result; */ public class Range { - private Double from; - private Double to; - private long count; - private double total; - private double totalCount; - private double min = Double.POSITIVE_INFINITY; - private double max = Double.NEGATIVE_INFINITY; + private Double from; + private Double to; + private long count; + private double total; + private double totalCount; + private double min = Double.POSITIVE_INFINITY; + private double max = Double.NEGATIVE_INFINITY; - public Range(Double from, Double to, long count, double total, double totalCount, double min, double max) { - this.from = from; - this.to = to; - this.count = count; - this.total = total; - this.totalCount = totalCount; - this.min = min; - this.max = max; - } + public Range(Double from, Double to, long count, double total, double totalCount, double min, double max) { + this.from = from; + this.to = to; + this.count = count; + this.total = total; + this.totalCount = totalCount; + this.min = min; + this.max = max; + } - public Double getFrom() { - return from; - } + public Double getFrom() { + return from; + } - public Double getTo() { - return to; - } + public Double getTo() { + return to; + } - /** - * Return number of documents in range - * - * @return - */ - public long getCount() { - return count; - } + /** + * Return number of documents in range + * + * @return + */ + public long getCount() { + return count; + } - public double getTotal() { - return total; - } + public double getTotal() { + return total; + } - public double getTotalCount() { - return totalCount; - } + public double getTotalCount() { + return totalCount; + } - public double getMin() { - return min; - } + public double getMin() { + return min; + } - public double getMax() { - return max; - } + public double getMax() { + return max; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/RangeResult.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/RangeResult.java index f5caf9ed8..c9f3b8174 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/RangeResult.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/RangeResult.java @@ -15,11 +15,11 @@ */ package org.springframework.data.elasticsearch.core.facet.result; -import org.springframework.data.elasticsearch.core.facet.AbstactFacetResult; -import org.springframework.data.elasticsearch.core.facet.FacetType; - import java.util.List; +import org.springframework.data.elasticsearch.core.facet.AbstractFacetResult; +import org.springframework.data.elasticsearch.core.facet.FacetType; + /** * Basic term facet result * @@ -28,17 +28,16 @@ import java.util.List; * @author Artur Konczak * @author Jonathan Yan */ -public class RangeResult extends AbstactFacetResult { +public class RangeResult extends AbstractFacetResult { - private List ranges; + private List ranges; - public RangeResult(String name, List ranges) { - super(name, FacetType.range); - this.ranges = ranges; - } - - public List getRanges() { - return ranges; - } + public RangeResult(String name, List ranges) { + super(name, FacetType.range); + this.ranges = ranges; + } + public List getRanges() { + return ranges; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/StatisticalResult.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/StatisticalResult.java index 1cbfc79ea..412315e98 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/StatisticalResult.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/StatisticalResult.java @@ -15,71 +15,71 @@ */ package org.springframework.data.elasticsearch.core.facet.result; -import org.springframework.data.elasticsearch.core.facet.AbstactFacetResult; +import org.springframework.data.elasticsearch.core.facet.AbstractFacetResult; import org.springframework.data.elasticsearch.core.facet.FacetType; /** * @author Petar Tahchiev */ -public class StatisticalResult extends AbstactFacetResult { +public class StatisticalResult extends AbstractFacetResult { - private long count; + private long count; - private double max; + private double max; - private double min; + private double min; - private double mean; + private double mean; - private double stdDeviation; + private double stdDeviation; - private double sumOfSquares; + private double sumOfSquares; - private double total; + private double total; - private double variance; + private double variance; - public StatisticalResult(String name, long count, double max, double min, double mean, double stdDeviation, double sumOfSquares, double total, double variance) { - super(name, FacetType.statistical); - this.count = count; - this.max = max; - this.min = min; - this.mean = mean; - this.stdDeviation = stdDeviation; - this.sumOfSquares = sumOfSquares; - this.total = total; - this.variance = variance; - } + public StatisticalResult(String name, long count, double max, double min, double mean, double stdDeviation, double sumOfSquares, double total, double variance) { + super(name, FacetType.statistical); + this.count = count; + this.max = max; + this.min = min; + this.mean = mean; + this.stdDeviation = stdDeviation; + this.sumOfSquares = sumOfSquares; + this.total = total; + this.variance = variance; + } - public long getCount() { - return count; - } + public long getCount() { + return count; + } - public double getMax() { - return max; - } + public double getMax() { + return max; + } - public double getMin() { - return min; - } + public double getMin() { + return min; + } - public double getMean() { - return mean; - } + public double getMean() { + return mean; + } - public double getStdDeviation() { - return stdDeviation; - } + public double getStdDeviation() { + return stdDeviation; + } - public double getSumOfSquares() { - return sumOfSquares; - } + public double getSumOfSquares() { + return sumOfSquares; + } - public double getTotal() { - return total; - } + public double getTotal() { + return total; + } - public double getVariance() { - return variance; - } + public double getVariance() { + return variance; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/Term.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/Term.java index fdd3a0ea0..9a355f1de 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/Term.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/Term.java @@ -25,19 +25,19 @@ package org.springframework.data.elasticsearch.core.facet.result; */ public class Term { - private String term; - private int count; + private String term; + private int count; - public Term(String term, int count) { - this.term = term; - this.count = count; - } + public Term(String term, int count) { + this.term = term; + this.count = count; + } - public String getTerm() { - return term; - } + public String getTerm() { + return term; + } - public int getCount() { - return count; - } + public int getCount() { + return count; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/TermResult.java b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/TermResult.java index 0c73e1ef8..0e6ee9128 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/facet/result/TermResult.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/facet/result/TermResult.java @@ -15,11 +15,11 @@ */ package org.springframework.data.elasticsearch.core.facet.result; -import org.springframework.data.elasticsearch.core.facet.AbstactFacetResult; -import org.springframework.data.elasticsearch.core.facet.FacetType; - import java.util.List; +import org.springframework.data.elasticsearch.core.facet.AbstractFacetResult; +import org.springframework.data.elasticsearch.core.facet.FacetType; + /** * Basic term facet result * @@ -28,17 +28,16 @@ import java.util.List; * @author Artur Konczak * @author Jonathan Yan */ -public class TermResult extends AbstactFacetResult { +public class TermResult extends AbstractFacetResult { - private List terms; + private List terms; - public TermResult(String name, List terms) { - super(name, FacetType.term); - this.terms = terms; - } - - public List getTerms() { - return terms; - } + public TermResult(String name, List terms) { + super(name, FacetType.term); + this.terms = terms; + } + public List getTerms() { + return terms; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/geo/GeoBox.java b/src/main/java/org/springframework/data/elasticsearch/core/geo/GeoBox.java index c8317b094..691ade147 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/geo/GeoBox.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/geo/GeoBox.java @@ -22,20 +22,19 @@ package org.springframework.data.elasticsearch.core.geo; */ public class GeoBox { - private GeoPoint topLeft; - private GeoPoint bottomRight; + private GeoPoint topLeft; + private GeoPoint bottomRight; - public GeoBox(GeoPoint topLeft, GeoPoint bottomRight) { - this.topLeft = topLeft; - this.bottomRight = bottomRight; - } + public GeoBox(GeoPoint topLeft, GeoPoint bottomRight) { + this.topLeft = topLeft; + this.bottomRight = bottomRight; + } - public GeoPoint getTopLeft() { - return topLeft; - } - - public GeoPoint getBottomRight() { - return bottomRight; - } + public GeoPoint getTopLeft() { + return topLeft; + } + public GeoPoint getBottomRight() { + return bottomRight; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/geo/GeoPoint.java b/src/main/java/org/springframework/data/elasticsearch/core/geo/GeoPoint.java index 75eae5ce1..116eb623a 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/geo/GeoPoint.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/geo/GeoPoint.java @@ -22,24 +22,23 @@ package org.springframework.data.elasticsearch.core.geo; */ public class GeoPoint { - private double lat; - private double lon; + private double lat; + private double lon; - private GeoPoint() { - //required by mapper to instantiate object - } + private GeoPoint() { + //required by mapper to instantiate object + } - public GeoPoint(double latitude, double longitude) { - this.lat = latitude; - this.lon = longitude; - } + public GeoPoint(double latitude, double longitude) { + this.lat = latitude; + this.lon = longitude; + } - public double getLat() { - return lat; - } - - public double getLon() { - return lon; - } + public double getLat() { + return lat; + } + public double getLon() { + return lon; + } } 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 4c4f28b79..78259f02d 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 @@ -19,7 +19,7 @@ import org.springframework.data.mapping.PersistentEntity; /** * ElasticsearchPersistentEntity - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -39,8 +39,8 @@ public interface ElasticsearchPersistentEntity extends PersistentEntity owner, SimpleTypeHolder simpleTypeHolder) { + SimpleElasticsearchPersistentEntity owner, SimpleTypeHolder simpleTypeHolder) { return new SimpleElasticsearchPersistentProperty(field, descriptor, owner, simpleTypeHolder); } - } 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 e95ac0114..a76ff9b52 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 @@ -15,6 +15,10 @@ */ package org.springframework.data.elasticsearch.core.mapping; +import static org.springframework.util.StringUtils.*; + +import java.util.Locale; + import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @@ -27,15 +31,10 @@ import org.springframework.data.util.TypeInformation; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.util.Assert; -import java.util.Locale; - -import static org.springframework.util.StringUtils.hasText; - /** * Elasticsearch specific {@link org.springframework.data.mapping.PersistentEntity} implementation holding - * + * * @param - * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -119,7 +118,7 @@ public class SimpleElasticsearchPersistentEntity extends BasicPersistentEntit @Override public void addPersistentProperty(ElasticsearchPersistentProperty property) { super.addPersistentProperty(property); - + Parent parent = property.getField().getAnnotation(Parent.class); if (parent != null) { Assert.isNull(this.parentIdProperty, "Only one field can hold a @Parent annotation"); @@ -128,7 +127,7 @@ public class SimpleElasticsearchPersistentEntity extends BasicPersistentEntit this.parentIdProperty = property; this.parentType = parent.type(); } - + 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 b93b58d3a..fc48bdbcd 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 @@ -15,19 +15,19 @@ */ package org.springframework.data.elasticsearch.core.mapping; -import org.springframework.data.mapping.Association; -import org.springframework.data.mapping.PersistentEntity; -import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty; -import org.springframework.data.mapping.model.SimpleTypeHolder; - import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; +import org.springframework.data.mapping.Association; +import org.springframework.data.mapping.PersistentEntity; +import org.springframework.data.mapping.model.AnnotationBasedPersistentProperty; +import org.springframework.data.mapping.model.SimpleTypeHolder; + /** * Elasticsearch specific {@link org.springframework.data.mapping.PersistentProperty} implementation processing - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -44,7 +44,7 @@ public class SimpleElasticsearchPersistentProperty extends } public SimpleElasticsearchPersistentProperty(Field field, PropertyDescriptor propertyDescriptor, - PersistentEntity owner, SimpleTypeHolder simpleTypeHolder) { + PersistentEntity owner, SimpleTypeHolder simpleTypeHolder) { super(field, propertyDescriptor, owner, simpleTypeHolder); } @@ -62,5 +62,4 @@ public class SimpleElasticsearchPersistentProperty extends 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 8fb89fd19..277286f56 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 @@ -15,18 +15,18 @@ */ package org.springframework.data.elasticsearch.core.query; -import org.springframework.data.domain.Pageable; -import org.springframework.data.domain.Sort; -import org.springframework.util.Assert; +import static org.apache.commons.collections.CollectionUtils.*; import java.util.ArrayList; import java.util.List; -import static org.apache.commons.collections.CollectionUtils.addAll; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.util.Assert; /** * AbstractQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -37,7 +37,7 @@ abstract class AbstractQuery implements Query { protected List indices = new ArrayList(); protected List types = new ArrayList(); protected List fields = new ArrayList(); - protected float minScore; + protected float minScore; @Override public Sort getSort() { @@ -101,11 +101,11 @@ abstract class AbstractQuery implements Query { return (T) this; } - public float getMinScore() { - return minScore; - } + public float getMinScore() { + return minScore; + } - public void setMinScore(float minScore) { - this.minScore = minScore; - } + public void setMinScore(float minScore) { + this.minScore = minScore; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/AliasBuilder.java b/src/main/java/org/springframework/data/elasticsearch/core/query/AliasBuilder.java index ab6b1460b..6b1ccaef4 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/AliasBuilder.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/AliasBuilder.java @@ -15,46 +15,46 @@ */ package org.springframework.data.elasticsearch.core.query; +import java.util.Map; + import org.elasticsearch.index.query.FilterBuilder; -import java.util.Map; /** - * * @author Mohsin Husen */ public class AliasBuilder { - private String indexName; - private String aliasName; - private FilterBuilder filterBuilder; - private Map filter; + private String indexName; + private String aliasName; + private FilterBuilder filterBuilder; + private Map filter; - public AliasBuilder withIndexName(String indexName){ - this.indexName = indexName; - return this; - } + public AliasBuilder withIndexName(String indexName) { + this.indexName = indexName; + return this; + } - public AliasBuilder withAliasName(String aliasName){ - this.aliasName = aliasName; - return this; - } + public AliasBuilder withAliasName(String aliasName) { + this.aliasName = aliasName; + return this; + } - public AliasBuilder withFilterBuilder(FilterBuilder filterBuilder){ - this.filterBuilder = filterBuilder; - return this; - } + public AliasBuilder withFilterBuilder(FilterBuilder filterBuilder) { + this.filterBuilder = filterBuilder; + return this; + } - public AliasBuilder withFilter(Map filter){ - this.filter = filter; - return this; - } + public AliasBuilder withFilter(Map filter) { + this.filter = filter; + return this; + } - public AliasQuery build(){ - AliasQuery aliasQuery = new AliasQuery(); - aliasQuery.setIndexName(indexName); - aliasQuery.setAliasName(aliasName); - aliasQuery.setFilterBuilder(filterBuilder); - aliasQuery.setFilter(filter); - return aliasQuery; - } + public AliasQuery build() { + AliasQuery aliasQuery = new AliasQuery(); + aliasQuery.setIndexName(indexName); + aliasQuery.setAliasName(aliasName); + aliasQuery.setFilterBuilder(filterBuilder); + aliasQuery.setFilter(filter); + return aliasQuery; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/AliasQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/AliasQuery.java index 3f5c52448..308b4ccf3 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/AliasQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/AliasQuery.java @@ -14,49 +14,52 @@ * limitations under the License. */ package org.springframework.data.elasticsearch.core.query; -import org.elasticsearch.index.query.FilterBuilder; + import java.util.Map; + +import org.elasticsearch.index.query.FilterBuilder; + /** - * AliasQuery is useful for creating new alias or deleting existing ones + * AliasQuery is useful for creating new alias or deleting existing ones * * @author Mohsin Husen */ public class AliasQuery { - private String indexName; - private String aliasName; - private FilterBuilder filterBuilder; - private Map filter; + private String indexName; + private String aliasName; + private FilterBuilder filterBuilder; + private Map filter; - 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 getAliasName() { - return aliasName; - } + public String getAliasName() { + return aliasName; + } - public void setAliasName(String aliasName) { - this.aliasName = aliasName; - } + public void setAliasName(String aliasName) { + this.aliasName = aliasName; + } - public FilterBuilder getFilterBuilder() { - return filterBuilder; - } + public FilterBuilder getFilterBuilder() { + return filterBuilder; + } - public void setFilterBuilder(FilterBuilder filterBuilder) { - this.filterBuilder = filterBuilder; - } + public void setFilterBuilder(FilterBuilder filterBuilder) { + this.filterBuilder = filterBuilder; + } - public Map getFilter() { - return filter; - } + public Map getFilter() { + return filter; + } - public void setFilter(Map filter) { - this.filter = filter; - } + public void setFilter(Map filter) { + this.filter = filter; + } } 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 5ebfa6c98..e9a8d90ba 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 @@ -15,13 +15,7 @@ */ package org.springframework.data.elasticsearch.core.query; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import org.apache.commons.lang.StringUtils; import org.springframework.dao.InvalidDataAccessApiUsageException; @@ -39,500 +33,497 @@ import org.springframework.util.Assert; */ public class Criteria { - public static final String WILDCARD = "*"; - public static final String CRITERIA_VALUE_SEPERATOR = " "; - - private static final String OR_OPERATOR = " OR "; - private static final String AND_OPERATOR = " AND "; - - private Field field; - private float boost = Float.NaN; - private boolean negating = false; - - private List criteriaChain = new ArrayList(1); - - private Set queryCriteria = new LinkedHashSet(); - - private Set filterCriteria = new LinkedHashSet(); - - public Criteria() { - } - - /** - * Creates a new CriterSimpleFieldia for the Filed with provided name - * - * @param fieldname - */ - public Criteria(String fieldname) { - this(new SimpleField(fieldname)); - } - - /** - * Creates a new Criteria for the given field - * - * @param field - */ - public Criteria(Field field) { - Assert.notNull(field, "Field for criteria must not be null"); - Assert.hasText(field.getName(), "Field.name for criteria must not be null/empty"); - - this.criteriaChain.add(this); - this.field = field; - } - - protected Criteria(List criteriaChain, String fieldname) { - this(criteriaChain, new SimpleField(fieldname)); - } - - protected Criteria(List criteriaChain, Field field) { - Assert.notNull(criteriaChain, "CriteriaChain must not be null"); - Assert.notNull(field, "Field for criteria must not be null"); - Assert.hasText(field.getName(), "Field.name for criteria must not be null/empty"); - - this.criteriaChain.addAll(criteriaChain); - this.criteriaChain.add(this); - this.field = field; - } - - /** - * Static factory method to create a new Criteria for field with given name - * - * @param field - * @return - */ - public static Criteria where(String field) { - return where(new SimpleField(field)); - } - - /** - * Static factory method to create a new Criteria for provided field - * - * @param field - * @return - */ - public static Criteria where(Field field) { - return new Criteria(field); - } - - /** - * Chain using {@code AND} - * - * @param field - * @return - */ - public Criteria and(Field field) { - return new Criteria(this.criteriaChain, field); - } - - /** - * Chain using {@code AND} - * - * @param fieldName - * @return - */ - public Criteria and(String fieldName) { - return new Criteria(this.criteriaChain, fieldName); - } - - /** - * Chain using {@code AND} - * - * @param criteria - * @return - */ - public Criteria and(Criteria criteria) { - this.criteriaChain.add(criteria); - return this; - } - - /** - * Chain using {@code AND} - * - * @param criterias - * @return - */ - public Criteria and(Criteria... criterias) { - this.criteriaChain.addAll(Arrays.asList(criterias)); - return this; - } - - /** - * Chain using {@code OR} - * - * @param field - * @return - */ - public Criteria or(Field field) { - return new OrCriteria(this.criteriaChain, field); - } - - /** - * Chain using {@code OR} - * - * @param criteria - * @return - */ - public Criteria or(Criteria criteria) { - Assert.notNull(criteria, "Cannot chain 'null' criteria."); - - Criteria orConnectedCritiera = new OrCriteria(this.criteriaChain, criteria.getField()); - orConnectedCritiera.queryCriteria.addAll(criteria.queryCriteria); - return orConnectedCritiera; - } - - /** - * Chain using {@code OR} - * - * @param fieldName - * @return - */ - public Criteria or(String fieldName) { - return or(new SimpleField(fieldName)); - } - - /** - * Crates new CriteriaEntry without any wildcards - * - * @param o - * @return - */ - public Criteria is(Object o) { - queryCriteria.add(new CriteriaEntry(OperationKey.EQUALS, o)); - return this; - } - - /** - * Crates new CriteriaEntry with leading and trailing wildcards
- * NOTE: mind your schema as leading wildcards may not be supported and/or execution might be slow. - * - * @param s - * @return - */ - public Criteria contains(String s) { - assertNoBlankInWildcardedQuery(s, true, true); - queryCriteria.add(new CriteriaEntry(OperationKey.CONTAINS, s)); - return this; - } - - /** - * Crates new CriteriaEntry with trailing wildcard - * - * @param s - * @return - */ - public Criteria startsWith(String s) { - assertNoBlankInWildcardedQuery(s, true, false); - queryCriteria.add(new CriteriaEntry(OperationKey.STARTS_WITH, s)); - return this; - } - - /** - * Crates new CriteriaEntry with leading wildcard
- * NOTE: mind your schema and execution times as leading wildcards may not be supported. - * - * @param s - * @return - */ - public Criteria endsWith(String s) { - assertNoBlankInWildcardedQuery(s, false, true); - queryCriteria.add(new CriteriaEntry(OperationKey.ENDS_WITH, s)); - return this; - } - - /** - * Crates new CriteriaEntry with trailing - - * - * @return - */ - public Criteria not() { - this.negating = true; - return this; - } - - /** - * Crates new CriteriaEntry with trailing ~ - * - * @param s - * @return - */ - public Criteria fuzzy(String s) { - queryCriteria.add(new CriteriaEntry(OperationKey.FUZZY, s)); - return this; - } - - /** - * Crates new CriteriaEntry allowing native elasticsearch expressions - * - * @param s - * @return - */ - public Criteria expression(String s) { - queryCriteria.add(new CriteriaEntry(OperationKey.EXPRESSION, s)); - return this; - } - - /** - * Boost positive hit with given factor. eg. ^2.3 - * - * @param boost - * @return - */ - public Criteria boost(float boost) { - if (boost < 0) { - throw new InvalidDataAccessApiUsageException("Boost must not be negative."); - } - this.boost = boost; - return this; - } - - /** - * Crates new CriteriaEntry for {@code RANGE [lowerBound TO upperBound]} - * - * @param lowerBound - * @param upperBound - * @return - */ - public Criteria between(Object lowerBound, Object upperBound) { - if (lowerBound == null && upperBound == null) { - throw new InvalidDataAccessApiUsageException("Range [* TO *] is not allowed"); - } - - queryCriteria.add(new CriteriaEntry(OperationKey.BETWEEN, new Object[]{lowerBound, upperBound})); - return this; - } - - /** - * Crates new CriteriaEntry for {@code RANGE [* TO upperBound]} - * - * @param upperBound - * @return - */ - public Criteria lessThanEqual(Object upperBound) { - between(null, upperBound); - return this; - } - - /** - * Crates new CriteriaEntry for {@code RANGE [lowerBound TO *]} - * - * @param lowerBound - * @return - */ - public Criteria greaterThanEqual(Object lowerBound) { - between(lowerBound, null); - return this; - } - - /** - * Crates new CriteriaEntry for multiple values {@code (arg0 arg1 arg2 ...)} - * - * @param values - * @return - */ - public Criteria in(Object... values) { - if (values.length == 0 || (values.length > 1 && values[1] instanceof Collection)) { - throw new InvalidDataAccessApiUsageException("At least one element " - + (values.length > 0 ? ("of argument of type " + values[1].getClass().getName()) : "") - + " has to be present."); - } - return in(Arrays.asList(values)); - } - - /** - * Crates new CriteriaEntry for multiple values {@code (arg0 arg1 arg2 ...)} - * - * @param values the collection containing the values to match against - * @return - */ - public Criteria in(Iterable values) { - Assert.notNull(values, "Collection of 'in' values must not be null"); - queryCriteria.add(new CriteriaEntry(OperationKey.IN, values)); - return this; - } - - /** - * Creates new CriteriaEntry for {@code location WITHIN distance} - * - * @param location {@link org.springframework.data.elasticsearch.core.geo.GeoPoint} center coordinates - * @param distance {@link String} radius as a string (e.g. : '100km'). - * Distance unit : - * either mi/miles or km can be set - * @return Criteria the chaind criteria with the new 'within' criteria included. - */ - public Criteria within(GeoPoint location, String distance) { - Assert.notNull(location, "Location value for near criteria must not be null"); - Assert.notNull(location, "Distance value for near criteria must not be null"); - filterCriteria.add(new CriteriaEntry(OperationKey.WITHIN, new Object[]{location, distance})); - return this; - } - - /** - * Creates new CriteriaEntry for {@code geoLocation WITHIN distance} - * - * @param geoLocation {@link String} center point - * supported formats: - * lat on = > "41.2,45.1", - * geohash = > "asd9as0d" - * @param distance {@link String} radius as a string (e.g. : '100km'). - * Distance unit : - * either mi/miles or km can be set - * @return - */ - public Criteria within(String geoLocation, String distance) { - Assert.isTrue(StringUtils.isNotBlank(geoLocation), "geoLocation value must not be null"); - filterCriteria.add(new CriteriaEntry(OperationKey.WITHIN, new Object[]{geoLocation, distance})); - return this; - } - - /** - * Creates new CriteriaEntry for {@code location GeoBox bounding box} - * - * @param boundingBox {@link org.springframework.data.elasticsearch.core.geo.GeoBox} bounding box(left top corner + right bottom corner) - * @return Criteria the chaind criteria with the new 'boundingBox' criteria included. - */ - public Criteria boundedBy(GeoBox boundingBox) { - Assert.notNull(boundingBox, "boundingBox value for boundedBy criteria must not be null"); - filterCriteria.add(new CriteriaEntry(OperationKey.BBOX, new Object[]{boundingBox})); - return this; - } - - - /** - * Creates new CriteriaEntry for bounding box created from points - * - * @param topLeftPoint left top corner of bounding box - * @param bottomRightPoint right bottom corner of bounding box - * @return Criteria the chaind criteria with the new 'boundedBy' criteria included. - */ - public Criteria boundedBy(String topLeftPoint, String bottomRightPoint) { - Assert.isTrue(StringUtils.isNotBlank(topLeftPoint), "topLeftPoint must not be empty"); - Assert.isTrue(StringUtils.isNotBlank(bottomRightPoint), "bottomRightPoint must not be empty"); - filterCriteria.add(new CriteriaEntry(OperationKey.BBOX, new Object[]{topLeftPoint, bottomRightPoint})); - return this; - } - - /** - * Creates new CriteriaEntry for bounding box created from points - * - * @param topLeftPoint left top corner of bounding box - * @param bottomRightPoint right bottom corner of bounding box - * @return Criteria the chaind criteria with the new 'boundedBy' criteria included. - */ - public Criteria boundedBy(GeoPoint topLeftPoint, GeoPoint bottomRightPoint) { - Assert.notNull(topLeftPoint, "topLeftPoint must not be null"); - Assert.notNull(bottomRightPoint, "bottomRightPoint must not be null"); - filterCriteria.add(new CriteriaEntry(OperationKey.BBOX, new Object[]{topLeftPoint, bottomRightPoint})); - return this; - } - - private void assertNoBlankInWildcardedQuery(String searchString, boolean leadingWildcard, boolean trailingWildcard) { - if (StringUtils.contains(searchString, CRITERIA_VALUE_SEPERATOR)) { - throw new InvalidDataAccessApiUsageException("Cannot constructQuery '" + (leadingWildcard ? "*" : "") + "\"" - + searchString + "\"" + (trailingWildcard ? "*" : "") + "'. Use epxression or mulitple clauses instead."); - } - } - - /** - * Field targeted by this Criteria - * - * @return - */ - public Field getField() { - return this.field; - } - - public Set getQueryCriteriaEntries() { - return Collections.unmodifiableSet(this.queryCriteria); - } - - public Set getFilterCriteriaEntries() { - return Collections.unmodifiableSet(this.filterCriteria); - } - - public Set getFilterCriteria() { - return filterCriteria; - } - - /** - * Conjunction to be used with this criteria (AND | OR) - * - * @return - */ - public String getConjunctionOperator() { - return AND_OPERATOR; - } - - public List getCriteriaChain() { - return Collections.unmodifiableList(this.criteriaChain); - } - - public boolean isNegating() { - return this.negating; - } - - public boolean isAnd() { - return AND_OPERATOR == getConjunctionOperator(); - } - - public boolean isOr() { - return OR_OPERATOR == getConjunctionOperator(); - } - - public float getBoost() { - return this.boost; - } - - static class OrCriteria extends Criteria { - - public OrCriteria() { - super(); - } - - public OrCriteria(Field field) { - super(field); - } - - public OrCriteria(List criteriaChain, Field field) { - super(criteriaChain, field); - } - - public OrCriteria(List criteriaChain, String fieldname) { - super(criteriaChain, fieldname); - } - - public OrCriteria(String fieldname) { - super(fieldname); - } - - @Override - public String getConjunctionOperator() { - return OR_OPERATOR; - } - - } - - public enum OperationKey { - EQUALS, CONTAINS, STARTS_WITH, ENDS_WITH, EXPRESSION, BETWEEN, FUZZY, IN, WITHIN, BBOX, NEAR; - } - - public static class CriteriaEntry { - - private OperationKey key; - private Object value; - - CriteriaEntry(OperationKey key, Object value) { - this.key = key; - this.value = value; - } - - public OperationKey getKey() { - return key; - } - - public Object getValue() { - return value; - } - - } - + public static final String WILDCARD = "*"; + public static final String CRITERIA_VALUE_SEPERATOR = " "; + + private static final String OR_OPERATOR = " OR "; + private static final String AND_OPERATOR = " AND "; + + private Field field; + private float boost = Float.NaN; + private boolean negating = false; + + private List criteriaChain = new ArrayList(1); + + private Set queryCriteria = new LinkedHashSet(); + + private Set filterCriteria = new LinkedHashSet(); + + public Criteria() { + } + + /** + * Creates a new CriterSimpleFieldia for the Filed with provided name + * + * @param fieldname + */ + public Criteria(String fieldname) { + this(new SimpleField(fieldname)); + } + + /** + * Creates a new Criteria for the given field + * + * @param field + */ + public Criteria(Field field) { + Assert.notNull(field, "Field for criteria must not be null"); + Assert.hasText(field.getName(), "Field.name for criteria must not be null/empty"); + + this.criteriaChain.add(this); + this.field = field; + } + + protected Criteria(List criteriaChain, String fieldname) { + this(criteriaChain, new SimpleField(fieldname)); + } + + protected Criteria(List criteriaChain, Field field) { + Assert.notNull(criteriaChain, "CriteriaChain must not be null"); + Assert.notNull(field, "Field for criteria must not be null"); + Assert.hasText(field.getName(), "Field.name for criteria must not be null/empty"); + + this.criteriaChain.addAll(criteriaChain); + this.criteriaChain.add(this); + this.field = field; + } + + /** + * Static factory method to create a new Criteria for field with given name + * + * @param field + * @return + */ + public static Criteria where(String field) { + return where(new SimpleField(field)); + } + + /** + * Static factory method to create a new Criteria for provided field + * + * @param field + * @return + */ + public static Criteria where(Field field) { + return new Criteria(field); + } + + /** + * Chain using {@code AND} + * + * @param field + * @return + */ + public Criteria and(Field field) { + return new Criteria(this.criteriaChain, field); + } + + /** + * Chain using {@code AND} + * + * @param fieldName + * @return + */ + public Criteria and(String fieldName) { + return new Criteria(this.criteriaChain, fieldName); + } + + /** + * Chain using {@code AND} + * + * @param criteria + * @return + */ + public Criteria and(Criteria criteria) { + this.criteriaChain.add(criteria); + return this; + } + + /** + * Chain using {@code AND} + * + * @param criterias + * @return + */ + public Criteria and(Criteria... criterias) { + this.criteriaChain.addAll(Arrays.asList(criterias)); + return this; + } + + /** + * Chain using {@code OR} + * + * @param field + * @return + */ + public Criteria or(Field field) { + return new OrCriteria(this.criteriaChain, field); + } + + /** + * Chain using {@code OR} + * + * @param criteria + * @return + */ + public Criteria or(Criteria criteria) { + Assert.notNull(criteria, "Cannot chain 'null' criteria."); + + Criteria orConnectedCritiera = new OrCriteria(this.criteriaChain, criteria.getField()); + orConnectedCritiera.queryCriteria.addAll(criteria.queryCriteria); + return orConnectedCritiera; + } + + /** + * Chain using {@code OR} + * + * @param fieldName + * @return + */ + public Criteria or(String fieldName) { + return or(new SimpleField(fieldName)); + } + + /** + * Crates new CriteriaEntry without any wildcards + * + * @param o + * @return + */ + public Criteria is(Object o) { + queryCriteria.add(new CriteriaEntry(OperationKey.EQUALS, o)); + return this; + } + + /** + * Crates new CriteriaEntry with leading and trailing wildcards
+ * NOTE: mind your schema as leading wildcards may not be supported and/or execution might be slow. + * + * @param s + * @return + */ + public Criteria contains(String s) { + assertNoBlankInWildcardedQuery(s, true, true); + queryCriteria.add(new CriteriaEntry(OperationKey.CONTAINS, s)); + return this; + } + + /** + * Crates new CriteriaEntry with trailing wildcard + * + * @param s + * @return + */ + public Criteria startsWith(String s) { + assertNoBlankInWildcardedQuery(s, true, false); + queryCriteria.add(new CriteriaEntry(OperationKey.STARTS_WITH, s)); + return this; + } + + /** + * Crates new CriteriaEntry with leading wildcard
+ * NOTE: mind your schema and execution times as leading wildcards may not be supported. + * + * @param s + * @return + */ + public Criteria endsWith(String s) { + assertNoBlankInWildcardedQuery(s, false, true); + queryCriteria.add(new CriteriaEntry(OperationKey.ENDS_WITH, s)); + return this; + } + + /** + * Crates new CriteriaEntry with trailing - + * + * @return + */ + public Criteria not() { + this.negating = true; + return this; + } + + /** + * Crates new CriteriaEntry with trailing ~ + * + * @param s + * @return + */ + public Criteria fuzzy(String s) { + queryCriteria.add(new CriteriaEntry(OperationKey.FUZZY, s)); + return this; + } + + /** + * Crates new CriteriaEntry allowing native elasticsearch expressions + * + * @param s + * @return + */ + public Criteria expression(String s) { + queryCriteria.add(new CriteriaEntry(OperationKey.EXPRESSION, s)); + return this; + } + + /** + * Boost positive hit with given factor. eg. ^2.3 + * + * @param boost + * @return + */ + public Criteria boost(float boost) { + if (boost < 0) { + throw new InvalidDataAccessApiUsageException("Boost must not be negative."); + } + this.boost = boost; + return this; + } + + /** + * Crates new CriteriaEntry for {@code RANGE [lowerBound TO upperBound]} + * + * @param lowerBound + * @param upperBound + * @return + */ + public Criteria between(Object lowerBound, Object upperBound) { + if (lowerBound == null && upperBound == null) { + throw new InvalidDataAccessApiUsageException("Range [* TO *] is not allowed"); + } + + queryCriteria.add(new CriteriaEntry(OperationKey.BETWEEN, new Object[]{lowerBound, upperBound})); + return this; + } + + /** + * Crates new CriteriaEntry for {@code RANGE [* TO upperBound]} + * + * @param upperBound + * @return + */ + public Criteria lessThanEqual(Object upperBound) { + between(null, upperBound); + return this; + } + + /** + * Crates new CriteriaEntry for {@code RANGE [lowerBound TO *]} + * + * @param lowerBound + * @return + */ + public Criteria greaterThanEqual(Object lowerBound) { + between(lowerBound, null); + return this; + } + + /** + * Crates new CriteriaEntry for multiple values {@code (arg0 arg1 arg2 ...)} + * + * @param values + * @return + */ + public Criteria in(Object... values) { + if (values.length == 0 || (values.length > 1 && values[1] instanceof Collection)) { + throw new InvalidDataAccessApiUsageException("At least one element " + + (values.length > 0 ? ("of argument of type " + values[1].getClass().getName()) : "") + + " has to be present."); + } + return in(Arrays.asList(values)); + } + + /** + * Crates new CriteriaEntry for multiple values {@code (arg0 arg1 arg2 ...)} + * + * @param values the collection containing the values to match against + * @return + */ + public Criteria in(Iterable values) { + Assert.notNull(values, "Collection of 'in' values must not be null"); + queryCriteria.add(new CriteriaEntry(OperationKey.IN, values)); + return this; + } + + /** + * Creates new CriteriaEntry for {@code location WITHIN distance} + * + * @param location {@link org.springframework.data.elasticsearch.core.geo.GeoPoint} center coordinates + * @param distance {@link String} radius as a string (e.g. : '100km'). + * Distance unit : + * either mi/miles or km can be set + * @return Criteria the chaind criteria with the new 'within' criteria included. + */ + public Criteria within(GeoPoint location, String distance) { + Assert.notNull(location, "Location value for near criteria must not be null"); + Assert.notNull(location, "Distance value for near criteria must not be null"); + filterCriteria.add(new CriteriaEntry(OperationKey.WITHIN, new Object[]{location, distance})); + return this; + } + + /** + * Creates new CriteriaEntry for {@code geoLocation WITHIN distance} + * + * @param geoLocation {@link String} center point + * supported formats: + * lat on = > "41.2,45.1", + * geohash = > "asd9as0d" + * @param distance {@link String} radius as a string (e.g. : '100km'). + * Distance unit : + * either mi/miles or km can be set + * @return + */ + public Criteria within(String geoLocation, String distance) { + Assert.isTrue(StringUtils.isNotBlank(geoLocation), "geoLocation value must not be null"); + filterCriteria.add(new CriteriaEntry(OperationKey.WITHIN, new Object[]{geoLocation, distance})); + return this; + } + + /** + * Creates new CriteriaEntry for {@code location GeoBox bounding box} + * + * @param boundingBox {@link org.springframework.data.elasticsearch.core.geo.GeoBox} bounding box(left top corner + right bottom corner) + * @return Criteria the chaind criteria with the new 'boundingBox' criteria included. + */ + public Criteria boundedBy(GeoBox boundingBox) { + Assert.notNull(boundingBox, "boundingBox value for boundedBy criteria must not be null"); + filterCriteria.add(new CriteriaEntry(OperationKey.BBOX, new Object[]{boundingBox})); + return this; + } + + + /** + * Creates new CriteriaEntry for bounding box created from points + * + * @param topLeftPoint left top corner of bounding box + * @param bottomRightPoint right bottom corner of bounding box + * @return Criteria the chaind criteria with the new 'boundedBy' criteria included. + */ + public Criteria boundedBy(String topLeftPoint, String bottomRightPoint) { + Assert.isTrue(StringUtils.isNotBlank(topLeftPoint), "topLeftPoint must not be empty"); + Assert.isTrue(StringUtils.isNotBlank(bottomRightPoint), "bottomRightPoint must not be empty"); + filterCriteria.add(new CriteriaEntry(OperationKey.BBOX, new Object[]{topLeftPoint, bottomRightPoint})); + return this; + } + + /** + * Creates new CriteriaEntry for bounding box created from points + * + * @param topLeftPoint left top corner of bounding box + * @param bottomRightPoint right bottom corner of bounding box + * @return Criteria the chaind criteria with the new 'boundedBy' criteria included. + */ + public Criteria boundedBy(GeoPoint topLeftPoint, GeoPoint bottomRightPoint) { + Assert.notNull(topLeftPoint, "topLeftPoint must not be null"); + Assert.notNull(bottomRightPoint, "bottomRightPoint must not be null"); + filterCriteria.add(new CriteriaEntry(OperationKey.BBOX, new Object[]{topLeftPoint, bottomRightPoint})); + return this; + } + + private void assertNoBlankInWildcardedQuery(String searchString, boolean leadingWildcard, boolean trailingWildcard) { + if (StringUtils.contains(searchString, CRITERIA_VALUE_SEPERATOR)) { + throw new InvalidDataAccessApiUsageException("Cannot constructQuery '" + (leadingWildcard ? "*" : "") + "\"" + + searchString + "\"" + (trailingWildcard ? "*" : "") + "'. Use epxression or mulitple clauses instead."); + } + } + + /** + * Field targeted by this Criteria + * + * @return + */ + public Field getField() { + return this.field; + } + + public Set getQueryCriteriaEntries() { + return Collections.unmodifiableSet(this.queryCriteria); + } + + public Set getFilterCriteriaEntries() { + return Collections.unmodifiableSet(this.filterCriteria); + } + + public Set getFilterCriteria() { + return filterCriteria; + } + + /** + * Conjunction to be used with this criteria (AND | OR) + * + * @return + */ + public String getConjunctionOperator() { + return AND_OPERATOR; + } + + public List getCriteriaChain() { + return Collections.unmodifiableList(this.criteriaChain); + } + + public boolean isNegating() { + return this.negating; + } + + public boolean isAnd() { + return AND_OPERATOR == getConjunctionOperator(); + } + + public boolean isOr() { + return OR_OPERATOR == getConjunctionOperator(); + } + + public float getBoost() { + return this.boost; + } + + static class OrCriteria extends Criteria { + + public OrCriteria() { + super(); + } + + public OrCriteria(Field field) { + super(field); + } + + public OrCriteria(List criteriaChain, Field field) { + super(criteriaChain, field); + } + + public OrCriteria(List criteriaChain, String fieldname) { + super(criteriaChain, fieldname); + } + + public OrCriteria(String fieldname) { + super(fieldname); + } + + @Override + public String getConjunctionOperator() { + return OR_OPERATOR; + } + } + + public enum OperationKey { + EQUALS, CONTAINS, STARTS_WITH, ENDS_WITH, EXPRESSION, BETWEEN, FUZZY, IN, WITHIN, BBOX, NEAR; + } + + public static class CriteriaEntry { + + private OperationKey key; + private Object value; + + CriteriaEntry(OperationKey key, Object value) { + this.key = key; + this.value = value; + } + + public OperationKey getKey() { + return key; + } + + public Object getValue() { + return 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 8dfa99de8..d760e665e 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 @@ -20,7 +20,7 @@ import org.springframework.util.Assert; /** * CriteriaQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -34,48 +34,47 @@ public class CriteriaQuery extends AbstractQuery { public CriteriaQuery(Criteria criteria) { this(criteria, null); } - - public CriteriaQuery(Criteria criteria, Pageable pageable) { - this.criteria = criteria; - this.pageable = pageable; - if (pageable != null) { - this.addSort(pageable.getSort()); - } - } - 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 b02c773fc..812cec05d 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 @@ -26,8 +26,8 @@ import org.elasticsearch.index.query.QueryBuilder; public class DeleteQuery { private QueryBuilder query; - private String index; - private String type; + private String index; + private String type; public QueryBuilder getQuery() { return query; @@ -35,21 +35,21 @@ public class DeleteQuery { public void setQuery(QueryBuilder query) { this.query = query; - } + } - public String getIndex() { - return index; - } + public String getIndex() { + return index; + } - public void setIndex(String index) { - this.index = index; - } + public void setIndex(String index) { + this.index = index; + } - 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/Field.java b/src/main/java/org/springframework/data/elasticsearch/core/query/Field.java index 56e7268a2..0be8a3363 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 */ @@ -25,9 +25,8 @@ public interface Field { /** * Get the name of the field used in schema.xml of elasticsearch server - * + * * @return */ String getName(); - } 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 76f1df9bf..53dcd55de 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 @@ -17,7 +17,7 @@ package org.springframework.data.elasticsearch.core.query; /** * GetQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ 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 1248e1826..b3ffb1678 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,7 +17,7 @@ package org.springframework.data.elasticsearch.core.query; /** * IndexQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -29,7 +29,7 @@ public class IndexQuery { private Long version; private String indexName; private String type; - private String source; + private String source; private String parentId; public String getId() { @@ -72,13 +72,13 @@ public class IndexQuery { this.type = type; } - public String getSource() { - return source; - } + public String getSource() { + return source; + } - public void setSource(String source) { - this.source = source; - } + public void setSource(String source) { + this.source = source; + } public String getParentId() { return parentId; 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 c125e5e12..e2a5359a3 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 @@ -15,17 +15,17 @@ */ package org.springframework.data.elasticsearch.core.query; -import org.springframework.data.domain.Pageable; +import static org.apache.commons.collections.CollectionUtils.*; +import static org.springframework.data.elasticsearch.core.query.AbstractQuery.*; import java.util.ArrayList; import java.util.List; -import static org.apache.commons.collections.CollectionUtils.addAll; -import static org.springframework.data.elasticsearch.core.query.AbstractQuery.DEFAULT_PAGE; +import org.springframework.data.domain.Pageable; /** * MoreLikeThisQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ 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 0b4ca5121..f668829b0 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,18 +15,18 @@ */ package org.springframework.data.elasticsearch.core.query; +import java.util.ArrayList; +import java.util.List; + import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.highlight.HighlightBuilder; import org.elasticsearch.search.sort.SortBuilder; import org.springframework.data.elasticsearch.core.facet.FacetRequest; -import java.util.ArrayList; -import java.util.List; - /** * NativeSearchQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak @@ -36,18 +36,18 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery { private QueryBuilder query; private FilterBuilder filter; private SortBuilder sort; - private List facets; - private HighlightBuilder.Field[] highlightFields; + private List facets; + private HighlightBuilder.Field[] highlightFields; - public NativeSearchQuery(QueryBuilder query) { - this.query = query; - } + public NativeSearchQuery(QueryBuilder query) { + this.query = query; + } - public NativeSearchQuery(QueryBuilder query, FilterBuilder filter) { - this.query = query; - this.filter = filter; - } + public NativeSearchQuery(QueryBuilder query, FilterBuilder filter) { + this.query = query; + this.filter = filter; + } public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, SortBuilder sort) { this.query = query; @@ -55,12 +55,12 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery { this.sort = sort; } - public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, SortBuilder sort, HighlightBuilder.Field[] highlightFields) { - this.query = query; - this.filter = filter; - this.sort = sort; - this.highlightFields = highlightFields; - } + public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, SortBuilder sort, HighlightBuilder.Field[] highlightFields) { + this.query = query; + this.filter = filter; + this.sort = sort; + this.highlightFields = highlightFields; + } public QueryBuilder getQuery() { return query; @@ -72,26 +72,26 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery { public SortBuilder getElasticsearchSort() { return sort; - } - - @Override - public HighlightBuilder.Field[] getHighlightFields() { - return highlightFields; } - public void addFacet(FacetRequest facetRequest){ - if(facets==null){ - facets = new ArrayList(); - } - facets.add(facetRequest); - } + @Override + public HighlightBuilder.Field[] getHighlightFields() { + return highlightFields; + } - public void setFacets(List facets){ - this.facets = facets; - } + public void addFacet(FacetRequest facetRequest) { + if (facets == null) { + facets = new ArrayList(); + } + facets.add(facetRequest); + } - @Override - public List getFacets() { - return facets; - } + public void setFacets(List facets) { + this.facets = facets; + } + + @Override + public List getFacets() { + return facets; + } } 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 90f1d9f17..dfb896d5f 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 @@ -15,6 +15,9 @@ */ package org.springframework.data.elasticsearch.core.query; +import java.util.ArrayList; +import java.util.List; + import org.apache.commons.collections.CollectionUtils; import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.QueryBuilder; @@ -23,9 +26,6 @@ import org.elasticsearch.search.sort.SortBuilder; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.facet.FacetRequest; -import java.util.ArrayList; -import java.util.List; - /** * NativeSearchQuery * @@ -36,88 +36,88 @@ import java.util.List; public class NativeSearchQueryBuilder { - private QueryBuilder queryBuilder; - private FilterBuilder filterBuilder; - private SortBuilder sortBuilder; - private List facetRequests = new ArrayList(); - private HighlightBuilder.Field[] highlightFields; - private Pageable pageable; - private String[] indices; - private String[] types; - private String[] fields; - private float minScore; + private QueryBuilder queryBuilder; + private FilterBuilder filterBuilder; + private SortBuilder sortBuilder; + private List facetRequests = new ArrayList(); + private HighlightBuilder.Field[] highlightFields; + private Pageable pageable; + private String[] indices; + private String[] types; + private String[] fields; + private float minScore; - 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 withFacet(FacetRequest facetRequest) { - facetRequests.add(facetRequest); - return this; - } + public NativeSearchQueryBuilder withFacet(FacetRequest facetRequest) { + facetRequests.add(facetRequest); + return this; + } - public NativeSearchQueryBuilder withHighlightFields(HighlightBuilder.Field... highlightFields){ - this.highlightFields = highlightFields; - return this; - } + public NativeSearchQueryBuilder withHighlightFields(HighlightBuilder.Field... highlightFields) { + this.highlightFields = highlightFields; + 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 NativeSearchQueryBuilder withMinScore(float minScore) { - this.minScore = minScore; - return this; - } + public NativeSearchQueryBuilder withMinScore(float minScore) { + this.minScore = minScore; + return this; + } - public NativeSearchQuery build() { - NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryBuilder, filterBuilder, sortBuilder, highlightFields); - if (pageable != null) { - nativeSearchQuery.setPageable(pageable); - } - if (indices != null) { - nativeSearchQuery.addIndices(indices); - } - if (types != null) { - nativeSearchQuery.addTypes(types); - } - if (fields != null) { - nativeSearchQuery.addFields(fields); - } - if (CollectionUtils.isNotEmpty(facetRequests)) { - nativeSearchQuery.setFacets(facetRequests); - } + public NativeSearchQuery build() { + NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryBuilder, filterBuilder, sortBuilder, highlightFields); + if (pageable != null) { + nativeSearchQuery.setPageable(pageable); + } + if (indices != null) { + nativeSearchQuery.addIndices(indices); + } + if (types != null) { + nativeSearchQuery.addTypes(types); + } + if (fields != null) { + nativeSearchQuery.addFields(fields); + } + if (CollectionUtils.isNotEmpty(facetRequests)) { + nativeSearchQuery.setFacets(facetRequests); + } - if(minScore>0){ - nativeSearchQuery.setMinScore(minScore); - } - return nativeSearchQuery; - } + if (minScore > 0) { + nativeSearchQuery.setMinScore(minScore); + } + 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 1d57e6968..782da3217 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,15 +15,15 @@ */ package org.springframework.data.elasticsearch.core.query; +import java.util.List; + 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 */ @@ -34,7 +34,7 @@ public interface Query { /** * restrict result to entries on given page. Corresponds to the 'start' and 'rows' parameter in elasticsearch - * + * * @param pageable * @return */ @@ -42,21 +42,21 @@ public interface Query { /** * 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 */ @@ -69,49 +69,50 @@ public interface Query { /** * 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 minimum score - * @return - */ - float getMinScore(); + /** + * Get minimum score + * + * @return + */ + float getMinScore(); } 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 2d823d720..80ed5f126 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 @@ -15,29 +15,30 @@ */ package org.springframework.data.elasticsearch.core.query; +import java.util.List; + import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.search.highlight.HighlightBuilder; import org.elasticsearch.search.sort.SortBuilder; import org.springframework.data.elasticsearch.core.facet.FacetRequest; -import java.util.List; - /** * NativeSearchQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak */ public interface SearchQuery extends Query { + QueryBuilder getQuery(); FilterBuilder getFilter(); SortBuilder getElasticsearchSort(); - List getFacets(); + List getFacets(); - HighlightBuilder.Field[] getHighlightFields(); + HighlightBuilder.Field[] getHighlightFields(); } 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 649573821..494be9a68 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 */ @@ -38,5 +38,4 @@ public class SimpleField implements Field { public String toString() { return this.name; } - } \ No newline at end of file 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 b77eb0956..f0c49b689 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 @@ -20,7 +20,7 @@ import org.springframework.data.domain.Sort; /** * StringQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -46,5 +46,4 @@ public class StringQuery extends AbstractQuery { public String getSource() { return source; } - } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQuery.java b/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQuery.java index 2eca04462..3e0d57db2 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQuery.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQuery.java @@ -23,58 +23,58 @@ import org.elasticsearch.action.index.IndexRequest; */ public class UpdateQuery { - private String id; - private IndexRequest indexRequest; - private String indexName; - private String type; - private Class clazz; - private boolean doUpsert; + private String id; + private IndexRequest indexRequest; + private String indexName; + private String type; + private Class clazz; + private boolean doUpsert; - 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 IndexRequest getIndexRequest() { - return indexRequest; - } + public IndexRequest getIndexRequest() { + return indexRequest; + } - public void setIndexRequest(IndexRequest indexRequest) { - this.indexRequest = indexRequest; - } + public void setIndexRequest(IndexRequest indexRequest) { + this.indexRequest = indexRequest; + } - 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 Class getClazz() { - return clazz; - } + public Class getClazz() { + return clazz; + } - public void setClazz(Class clazz) { - this.clazz = clazz; - } + public void setClazz(Class clazz) { + this.clazz = clazz; + } - public boolean DoUpsert() { - return doUpsert; - } + public boolean DoUpsert() { + return doUpsert; + } - public void setDoUpsert(boolean doUpsert) { - this.doUpsert = doUpsert; - } + public void setDoUpsert(boolean doUpsert) { + this.doUpsert = doUpsert; + } } diff --git a/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQueryBuilder.java b/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQueryBuilder.java index 773a645cf..ed07724c3 100644 --- a/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQueryBuilder.java +++ b/src/main/java/org/springframework/data/elasticsearch/core/query/UpdateQueryBuilder.java @@ -23,51 +23,51 @@ import org.elasticsearch.action.index.IndexRequest; */ public class UpdateQueryBuilder { - private String id; - private IndexRequest indexRequest; - private String indexName; - private String type; - private Class clazz; - private boolean doUpsert; + private String id; + private IndexRequest indexRequest; + private String indexName; + private String type; + private Class clazz; + private boolean doUpsert; - public UpdateQueryBuilder withId(String id){ - this.id = id; - return this; - } + public UpdateQueryBuilder withId(String id) { + this.id = id; + return this; + } - public UpdateQueryBuilder withIndexRequest(IndexRequest indexRequest){ - this.indexRequest = indexRequest; - return this; - } + public UpdateQueryBuilder withIndexRequest(IndexRequest indexRequest) { + this.indexRequest = indexRequest; + return this; + } - public UpdateQueryBuilder withIndexName(String indexName){ - this.indexName = indexName; - return this; - } + public UpdateQueryBuilder withIndexName(String indexName) { + this.indexName = indexName; + return this; + } - public UpdateQueryBuilder withType(String type){ - this.type = type; - return this; - } + public UpdateQueryBuilder withType(String type) { + this.type = type; + return this; + } - public UpdateQueryBuilder withClass(Class clazz){ - this.clazz = clazz; - return this; - } + public UpdateQueryBuilder withClass(Class clazz) { + this.clazz = clazz; + return this; + } - public UpdateQueryBuilder withDoUpsert(boolean doUpsert){ - this.doUpsert = doUpsert; - return this; - } + public UpdateQueryBuilder withDoUpsert(boolean doUpsert) { + this.doUpsert = doUpsert; + return this; + } - public UpdateQuery build(){ - UpdateQuery updateQuery = new UpdateQuery(); - updateQuery.setId(id); - updateQuery.setIndexName(indexName); - updateQuery.setType(type); - updateQuery.setClazz(clazz); - updateQuery.setIndexRequest(indexRequest); - updateQuery.setDoUpsert(doUpsert); - return updateQuery; - } + public UpdateQuery build() { + UpdateQuery updateQuery = new UpdateQuery(); + updateQuery.setId(id); + updateQuery.setIndexName(indexName); + updateQuery.setType(type); + updateQuery.setClazz(clazz); + updateQuery.setIndexRequest(indexRequest); + updateQuery.setDoUpsert(doUpsert); + return updateQuery; + } } 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 d2326731d..2df696fbe 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchCrudRepository.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchCrudRepository.java @@ -23,7 +23,6 @@ import org.springframework.data.repository.PagingAndSortingRepository; /** * @param * @param - * * @author Rizwan Idrees * @author Mohsin Husen * @author Oliver Gierke 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 978127aa7..7db1e3257 100644 --- a/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchRepository.java +++ b/src/main/java/org/springframework/data/elasticsearch/repository/ElasticsearchRepository.java @@ -15,6 +15,8 @@ */ package org.springframework.data.elasticsearch.repository; +import java.io.Serializable; + import org.elasticsearch.index.query.QueryBuilder; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -22,12 +24,9 @@ import org.springframework.data.elasticsearch.core.FacetedPage; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.data.repository.NoRepositoryBean; -import java.io.Serializable; - /** * @param * @param - * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -40,7 +39,7 @@ public interface ElasticsearchRepository extends Ela FacetedPage search(QueryBuilder query, Pageable pageable); - FacetedPage search(SearchQuery searchQuery); + FacetedPage search(SearchQuery searchQuery); - Page searchSimilar(T entity,String[] fields, Pageable pageable); + Page searchSimilar(T entity, String[] fields, Pageable pageable); } 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 9efe063a9..3128935e1 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 @@ -15,20 +15,20 @@ */ package org.springframework.data.elasticsearch.repository.cdi; -import org.springframework.data.elasticsearch.core.ElasticsearchOperations; -import org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactory; -import org.springframework.data.repository.cdi.CdiRepositoryBean; -import org.springframework.util.Assert; - import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import java.lang.annotation.Annotation; import java.util.Set; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; +import org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactory; +import org.springframework.data.repository.cdi.CdiRepositoryBean; +import org.springframework.util.Assert; + /** * Uses CdiRepositoryBean to create ElasticsearchRepository instances. - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -37,7 +37,7 @@ public class ElasticsearchRepositoryBean extends CdiRepositoryBean { private final Bean elasticsearchOperationsBean; public ElasticsearchRepositoryBean(Bean operations, Set qualifiers, - Class repositoryType, BeanManager beanManager) { + Class repositoryType, BeanManager beanManager) { super(qualifiers, repositoryType, beanManager); Assert.notNull(operations, "Cannot create repository with 'null' for ElasticsearchOperations."); @@ -55,5 +55,4 @@ public class ElasticsearchRepositoryBean extends CdiRepositoryBean { public Class getScope() { return elasticsearchOperationsBean.getScope(); } - } 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 afd71ce37..12e838fb3 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 @@ -15,10 +15,6 @@ */ package org.springframework.data.elasticsearch.repository.cdi; -import org.springframework.data.elasticsearch.core.ElasticsearchOperations; -import org.springframework.data.repository.cdi.CdiRepositoryBean; -import org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport; - import javax.enterprise.event.Observes; import javax.enterprise.inject.UnsatisfiedResolutionException; import javax.enterprise.inject.spi.AfterBeanDiscovery; @@ -32,9 +28,13 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import org.springframework.data.elasticsearch.core.ElasticsearchOperations; +import org.springframework.data.repository.cdi.CdiRepositoryBean; +import org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport; + /** * ElasticsearchRepositoryExtension - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Oliver Gierke @@ -66,7 +66,7 @@ public class ElasticsearchRepositoryExtension extends CdiRepositoryExtensionSupp } private CdiRepositoryBean createRepositoryBean(Class repositoryType, Set qualifiers, BeanManager beanManager) { - + Bean elasticsearchOperationsBean = this.elasticsearchOperationsMap.get(qualifiers .toString()); @@ -74,7 +74,7 @@ public class ElasticsearchRepositoryExtension extends CdiRepositoryExtensionSupp throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.", ElasticsearchOperations.class.getName(), qualifiers)); } - + 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 774044128..1ff41a654 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 @@ -15,15 +15,15 @@ */ package org.springframework.data.elasticsearch.repository.config; +import java.lang.annotation.Annotation; + import org.springframework.data.repository.config.RepositoryBeanDefinitionRegistrarSupport; import org.springframework.data.repository.config.RepositoryConfigurationExtension; -import java.lang.annotation.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 7a336cd46..741f3feb9 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 @@ -27,7 +27,7 @@ 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. - * + * * @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 b282d43a1..c6f2a77d4 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 @@ -15,18 +15,18 @@ */ package org.springframework.data.elasticsearch.repository.config; +import java.lang.annotation.*; + import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Import; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactoryBean; 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. - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -72,7 +72,7 @@ public @interface EnableElasticsearchRepositories { * Returns the postfix to be used when looking up custom repository implementations. Defaults to {@literal Impl}. So * for a repository named {@code PersonRepository} the corresponding implementation class will be looked up scanning * for {@code PersonRepositoryImpl}. - * + * * @return */ String repositoryImplementationPostfix() default "Impl"; @@ -80,7 +80,7 @@ public @interface EnableElasticsearchRepositories { /** * Configures the location of where to find the Spring Data named queries properties file. Will default to * {@code META-INFO/elasticsearch-named-queries.properties}. - * + * * @return */ String namedQueriesLocation() default ""; @@ -89,7 +89,7 @@ public @interface EnableElasticsearchRepositories { * 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; @@ -97,7 +97,7 @@ public @interface EnableElasticsearchRepositories { /** * Returns the {@link org.springframework.beans.factory.FactoryBean} class to be used for each repository instance. * Defaults to {@link ElasticsearchRepositoryFactoryBean}. - * + * * @return */ Class repositoryFactoryBeanClass() default ElasticsearchRepositoryFactoryBean.class; @@ -107,7 +107,7 @@ public @interface EnableElasticsearchRepositories { /** * Configures the name of the {@link ElasticsearchTemplate} bean definition to be used to create repositories * discovered through this annotation. Defaults to {@code elasticsearchTemplate}. - * + * * @return */ String elasticsearchTemplateRef() default "elasticsearchTemplate"; 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 c3c79eddf..f2aafc6dc 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,7 +21,7 @@ import org.springframework.data.repository.query.RepositoryQuery; /** * AbstractElasticsearchRepositoryQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -32,7 +32,7 @@ public abstract class AbstractElasticsearchRepositoryQuery implements Repository protected ElasticsearchOperations elasticsearchOperations; public AbstractElasticsearchRepositoryQuery(ElasticsearchQueryMethod queryMethod, - ElasticsearchOperations elasticsearchOperations) { + ElasticsearchOperations elasticsearchOperations) { this.queryMethod = queryMethod; this.elasticsearchOperations = elasticsearchOperations; } @@ -41,5 +41,4 @@ public abstract class AbstractElasticsearchRepositoryQuery implements Repository 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 30c024543..9888e6991 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 @@ -25,7 +25,7 @@ import org.springframework.data.repository.query.parser.PartTree; /** * ElasticsearchPartQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ 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 ffcd040de..3d29735cd 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 @@ -15,6 +15,8 @@ */ package org.springframework.data.elasticsearch.repository.query; +import java.lang.reflect.Method; + import org.springframework.core.annotation.AnnotationUtils; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.support.ElasticsearchEntityInformation; @@ -23,11 +25,9 @@ import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.query.QueryMethod; import org.springframework.util.StringUtils; -import java.lang.reflect.Method; - /** * ElasticsearchQueryMethod - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -37,7 +37,7 @@ public class ElasticsearchQueryMethod extends QueryMethod { private Method method; public ElasticsearchQueryMethod(Method method, RepositoryMetadata metadata, - ElasticsearchEntityInformationCreator elasticsearchEntityInformationCreator) { + ElasticsearchEntityInformationCreator elasticsearchEntityInformationCreator) { super(method, metadata); this.entityInformation = elasticsearchEntityInformationCreator.getEntityInformation(metadata .getReturnedDomainClass(method)); @@ -56,5 +56,4 @@ public class ElasticsearchQueryMethod extends QueryMethod { 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 cef6fbf38..8bf2bcf93 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,6 +15,9 @@ */ package org.springframework.data.elasticsearch.repository.query; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import org.springframework.core.convert.support.GenericConversionService; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.convert.DateTimeConverters; @@ -22,12 +25,9 @@ import org.springframework.data.elasticsearch.core.query.StringQuery; import org.springframework.data.repository.query.ParametersParameterAccessor; import org.springframework.util.Assert; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - /** * ElasticsearchStringQuery - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -48,11 +48,10 @@ public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQue if (!conversionService.canConvert(org.joda.time.LocalDateTime.class, String.class)) { conversionService.addConverter(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE); } - } public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod, - ElasticsearchOperations elasticsearchOperations, String query) { + ElasticsearchOperations elasticsearchOperations, String query) { super(queryMethod, elasticsearchOperations); Assert.notNull(query, "Query cannot be empty"); this.query = query; 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 f068e86e6..38c47c4dd 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,6 +15,9 @@ */ package org.springframework.data.elasticsearch.repository.query.parser; +import java.util.Collection; +import java.util.Iterator; + import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.domain.Sort; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; @@ -27,12 +30,9 @@ import org.springframework.data.repository.query.parser.AbstractQueryCreator; import org.springframework.data.repository.query.parser.Part; import org.springframework.data.repository.query.parser.PartTree; -import java.util.Collection; -import java.util.Iterator; - /** * ElasticsearchQueryCreator - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -41,7 +41,7 @@ public class ElasticsearchQueryCreator extends AbstractQueryCreator context; public ElasticsearchQueryCreator(PartTree tree, ParameterAccessor parameters, - MappingContext context) { + MappingContext context) { super(tree, parameters); this.context = context; } @@ -89,39 +89,39 @@ public class ElasticsearchQueryCreator extends AbstractQueryCreator metadata, - ElasticsearchOperations elasticsearchOperations) { + ElasticsearchOperations elasticsearchOperations) { this(elasticsearchOperations); Assert.notNull(metadata); this.entityInformation = metadata; @@ -88,7 +86,7 @@ public abstract class AbstractElasticsearchRepository findAll() { int itemCount = (int) this.count(); if (itemCount == 0) { - return new PageImpl(Collections. emptyList()); + return new PageImpl(Collections.emptyList()); } return this.findAll(new PageRequest(0, Math.max(1, itemCount))); } @@ -103,7 +101,7 @@ public abstract class AbstractElasticsearchRepository findAll(Sort sort) { int itemCount = (int) this.count(); if (itemCount == 0) { - return new PageImpl(Collections. emptyList()); + return new PageImpl(Collections.emptyList()); } SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withPageable(new PageRequest(0, itemCount, sort)).build(); @@ -173,7 +171,7 @@ public abstract class AbstractElasticsearchRepository(Collections. emptyList()); + return new PageImpl(Collections.emptyList()); } searchQuery.setPageable(new PageRequest(0, count)); return elasticsearchOperations.queryForPage(searchQuery, getEntityClass()); @@ -197,9 +195,9 @@ public abstract class AbstractElasticsearchRepository * @param - * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -35,6 +34,6 @@ public interface ElasticsearchEntityInformation exte String getType(); Long getVersion(T entity); - + String getParentId(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 c69051c5c..bec17ffb2 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 @@ -19,12 +19,11 @@ import java.io.Serializable; /** * ElasticsearchEntityInformationCreator - * + * * @author Rizwan Idrees * @author Mohsin Husen */ public interface ElasticsearchEntityInformationCreator { ElasticsearchEntityInformation getEntityInformation(Class domainClass); - } 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 8a4dd443f..91792c706 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 @@ -15,16 +15,16 @@ */ package org.springframework.data.elasticsearch.repository.support; +import java.io.Serializable; + import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; import org.springframework.data.mapping.context.MappingContext; import org.springframework.util.Assert; -import java.io.Serializable; - /** * ElasticsearchEntityInformationCreatorImpl - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Oliver Gierke @@ -42,12 +42,12 @@ public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchE @Override @SuppressWarnings("unchecked") public ElasticsearchEntityInformation getEntityInformation(Class domainClass) { - + ElasticsearchPersistentEntity persistentEntity = (ElasticsearchPersistentEntity) mappingContext .getPersistentEntity(domainClass); - + Assert.notNull(persistentEntity, String.format("Unable to obtain mapping metadata for %s!", 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 b98350ecf..a874856c3 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 @@ -15,7 +15,7 @@ */ package org.springframework.data.elasticsearch.repository.support; -import static org.springframework.data.querydsl.QueryDslUtils.QUERY_DSL_PRESENT; +import static org.springframework.data.querydsl.QueryDslUtils.*; import java.io.Serializable; import java.lang.reflect.Method; @@ -35,7 +35,7 @@ import org.springframework.util.Assert; /** * Factory to create {@link ElasticsearchRepository} - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Ryan Henszey @@ -58,7 +58,7 @@ public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport { } @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) protected Object getTargetRepository(RepositoryMetadata metadata) { ElasticsearchEntityInformation entityInformation = getEntityInformation(metadata.getDomainType()); @@ -117,5 +117,4 @@ public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport { 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 538a831ec..8eb808085 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 @@ -15,18 +15,18 @@ */ package org.springframework.data.elasticsearch.repository.support; +import java.io.Serializable; + import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.repository.Repository; import org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport; import org.springframework.data.repository.core.support.RepositoryFactorySupport; 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. - * + * * @author Rizwan Idrees * @author Mohsin Husen */ @@ -37,7 +37,7 @@ public class ElasticsearchRepositoryFactoryBean, S, /** * Configures the {@link ElasticsearchOperations} to be used to create Elasticsearch repositories. - * + * * @param operations the operations to set */ public void setElasticsearchOperations(ElasticsearchOperations operations) { @@ -59,5 +59,4 @@ public class ElasticsearchRepositoryFactoryBean, S, 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 9820f5513..78779db1c 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 @@ -28,10 +28,9 @@ import org.springframework.util.Assert; /** * Elasticsearch specific implementation of * {@link org.springframework.data.repository.core.support.AbstractEntityInformation} - * + * * @param * @param - * * @author Rizwan Idrees * @author Mohsin Husen * @author Ryan Henszey @@ -104,7 +103,7 @@ public class MappingElasticsearchEntityInformation e } return null; } - + @Override public String getParentId(T entity) { ElasticsearchPersistentProperty parentProperty = entityMetadata.getParentIdProperty(); 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 2cc8aa3b7..a386f5660 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 @@ -20,8 +20,7 @@ import org.springframework.data.elasticsearch.core.ElasticsearchOperations; /** * Elasticsearch specific repository implementation. Likely to be used as target within * {@link ElasticsearchRepositoryFactory} - * - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Ryan Henszey @@ -33,7 +32,7 @@ public class NumberKeyedRepository extends AbstractElastic } public NumberKeyedRepository(ElasticsearchEntityInformation metadata, - ElasticsearchOperations elasticsearchOperations) { + ElasticsearchOperations elasticsearchOperations) { super(metadata, elasticsearchOperations); } @@ -45,5 +44,4 @@ public class NumberKeyedRepository extends AbstractElastic 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 41e32ca22..e6bef78b1 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 @@ -20,8 +20,7 @@ import org.springframework.data.elasticsearch.core.ElasticsearchOperations; /** * Elasticsearch specific repository implementation. Likely to be used as target within * {@link ElasticsearchRepositoryFactory} - * - * + * * @author Rizwan Idrees * @author Mohsin Husen * @author Ryan Henszey @@ -33,7 +32,7 @@ public class SimpleElasticsearchRepository extends AbstractElasticsearchRepos } public SimpleElasticsearchRepository(ElasticsearchEntityInformation metadata, - ElasticsearchOperations elasticsearchOperations) { + ElasticsearchOperations elasticsearchOperations) { super(metadata, elasticsearchOperations); } @@ -45,5 +44,4 @@ public class SimpleElasticsearchRepository extends AbstractElasticsearchRepos protected String stringIdRepresentation(String id) { return id; } - } diff --git a/src/main/resources/org/springframework/data/elasticsearch/config/spring-elasticsearch-1.0.xsd b/src/main/resources/org/springframework/data/elasticsearch/config/spring-elasticsearch-1.0.xsd index 4f472c2c6..117ca2a09 100644 --- a/src/main/resources/org/springframework/data/elasticsearch/config/spring-elasticsearch-1.0.xsd +++ b/src/main/resources/org/springframework/data/elasticsearch/config/spring-elasticsearch-1.0.xsd @@ -7,17 +7,18 @@ targetNamespace="http://www.springframework.org/schema/data/elasticsearch" elementFormDefault="qualified" attributeFormDefault="unqualified"> - - + + + schemaLocation="http://www.springframework.org/schema/data/repository/spring-repository.xsd"/> - - + + @@ -27,16 +28,16 @@ - + - + - + @@ -46,12 +47,14 @@ - + + - + + @@ -66,7 +69,7 @@ - + @@ -76,32 +79,38 @@ - + + - + + - + + - + + - + + - + + diff --git a/src/test/java/org/springframework/data/elasticsearch/Car.java b/src/test/java/org/springframework/data/elasticsearch/Car.java index 03b7d0f2f..651b39e9f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/Car.java +++ b/src/test/java/org/springframework/data/elasticsearch/Car.java @@ -22,22 +22,22 @@ package org.springframework.data.elasticsearch; */ public class Car { - private String name; - private String model; + private String name; + private String model; - 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 String getModel() { - return model; - } + public String getModel() { + return model; + } - public void setModel(String model) { - this.model = model; - } + public void setModel(String model) { + this.model = model; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/CarBuilder.java b/src/test/java/org/springframework/data/elasticsearch/CarBuilder.java index e312a99e6..dc71bbb9f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/CarBuilder.java +++ b/src/test/java/org/springframework/data/elasticsearch/CarBuilder.java @@ -20,19 +20,19 @@ package org.springframework.data.elasticsearch; */ public class CarBuilder { - private Car car = new Car(); + private Car car = new Car(); - public CarBuilder name(String name) { - car.setName(name); - return this; - } + public CarBuilder name(String name) { + car.setName(name); + return this; + } - public CarBuilder model(String model) { - car.setModel(model); - return this; - } + public CarBuilder model(String model) { + car.setModel(model); + return this; + } - public Car build(){ - return car; - } + public Car build() { + return car; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/DoubleIDEntity.java b/src/test/java/org/springframework/data/elasticsearch/DoubleIDEntity.java index 3955b38db..ca59159f0 100644 --- a/src/test/java/org/springframework/data/elasticsearch/DoubleIDEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/DoubleIDEntity.java @@ -65,5 +65,4 @@ public class DoubleIDEntity { public void setVersion(Long version) { this.version = version; } - } diff --git a/src/test/java/org/springframework/data/elasticsearch/GirlFriend.java b/src/test/java/org/springframework/data/elasticsearch/GirlFriend.java index 6e1a5dcb2..f57626c81 100644 --- a/src/test/java/org/springframework/data/elasticsearch/GirlFriend.java +++ b/src/test/java/org/springframework/data/elasticsearch/GirlFriend.java @@ -15,45 +15,45 @@ */ package org.springframework.data.elasticsearch; +import java.util.List; + import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; -import java.util.List; - /** * @author Mohsin Husen */ public class GirlFriend { - private String name; + private String name; - private String type; + private String type; - @Field(type = FieldType.Nested) - private List cars; + @Field(type = FieldType.Nested) + private List cars; - 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 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 getCars() { - return cars; - } + public List getCars() { + return cars; + } - public void setCars(List cars) { - this.cars = cars; - } + public void setCars(List cars) { + this.cars = cars; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/IntegerIDEntity.java b/src/test/java/org/springframework/data/elasticsearch/IntegerIDEntity.java index 9b9206093..2b7aff18e 100644 --- a/src/test/java/org/springframework/data/elasticsearch/IntegerIDEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/IntegerIDEntity.java @@ -65,5 +65,4 @@ public class IntegerIDEntity { public void setVersion(Long version) { this.version = version; } - } diff --git a/src/test/java/org/springframework/data/elasticsearch/MinimalEntity.java b/src/test/java/org/springframework/data/elasticsearch/MinimalEntity.java index d4b787beb..e0ff2ed4e 100644 --- a/src/test/java/org/springframework/data/elasticsearch/MinimalEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/MinimalEntity.java @@ -17,6 +17,7 @@ package org.springframework.data.elasticsearch; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; + /** * MinimalEntity * @@ -24,6 +25,7 @@ import org.springframework.data.elasticsearch.annotations.Document; */ @Document(indexName = "index", type = "type") public class MinimalEntity { + @Id private String id; } diff --git a/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java b/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java index f1cc0ce86..ab2c5fadb 100644 --- a/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/NestedObjectTests.java @@ -15,6 +15,15 @@ */ package org.springframework.data.elasticsearch; +import static org.apache.commons.lang.RandomStringUtils.*; +import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.junit.Before; @@ -31,20 +40,6 @@ import org.springframework.data.elasticsearch.repositories.SampleElasticSearchBo import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; -import static org.elasticsearch.index.query.QueryBuilders.boolQuery; -import static org.elasticsearch.index.query.QueryBuilders.nestedQuery; -import static org.elasticsearch.index.query.QueryBuilders.termQuery; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -54,130 +49,128 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:/repository-test-nested-object.xml") public class NestedObjectTests { - @Resource + @Autowired private SampleElasticSearchBookRepository bookRepository; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; - @Before - public void before() { - elasticsearchTemplate.deleteIndex(Book.class); - elasticsearchTemplate.createIndex(Book.class); - elasticsearchTemplate.refresh(Book.class, true); - elasticsearchTemplate.deleteIndex(Person.class); - elasticsearchTemplate.createIndex(Person.class); - elasticsearchTemplate.putMapping(Person.class); - elasticsearchTemplate.refresh(Person.class, true); - elasticsearchTemplate.deleteIndex(PersonMultipleLevelNested.class); - elasticsearchTemplate.createIndex(PersonMultipleLevelNested.class); - elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); - elasticsearchTemplate.refresh(PersonMultipleLevelNested.class,true); - } - - @Test - public void shouldIndexInitialLevelNestedObject(){ - - List cars = new ArrayList(); - - Car saturn = new Car(); - saturn.setName("Saturn"); - saturn.setModel("SL"); - - Car subaru = new Car(); - subaru.setName("Subaru"); - subaru.setModel("Imprezza"); - - Car ford = new Car(); - ford.setName("Ford"); - ford.setModel("Focus"); - - cars.add(saturn); - cars.add(subaru); - cars.add(ford); - - Person foo = new Person(); - foo.setName("Foo"); - foo.setId("1"); - foo.setCar(cars); - - - Car car = new Car(); - car.setName("Saturn"); - car.setModel("Imprezza"); - - Person bar = new Person(); - bar.setId("2"); - bar.setName("Bar"); - bar.setCar(Arrays.asList(car)); - - List indexQueries = new ArrayList(); - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(foo.getId()); - indexQuery1.setObject(foo); - - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(bar.getId()); - indexQuery2.setObject(bar); - - indexQueries.add(indexQuery1); - indexQueries.add(indexQuery2); - - elasticsearchTemplate.putMapping(Person.class); - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(Person.class, true); - - QueryBuilder builder = nestedQuery("car", boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza"))); - - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); - List persons = elasticsearchTemplate.queryForList(searchQuery, Person.class); - - assertThat(persons.size() , is(1)); - - } + @Before + public void before() { + elasticsearchTemplate.deleteIndex(Book.class); + elasticsearchTemplate.createIndex(Book.class); + elasticsearchTemplate.refresh(Book.class, true); + elasticsearchTemplate.deleteIndex(Person.class); + elasticsearchTemplate.createIndex(Person.class); + elasticsearchTemplate.putMapping(Person.class); + elasticsearchTemplate.refresh(Person.class, true); + elasticsearchTemplate.deleteIndex(PersonMultipleLevelNested.class); + elasticsearchTemplate.createIndex(PersonMultipleLevelNested.class); + elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); + elasticsearchTemplate.refresh(PersonMultipleLevelNested.class, true); + } @Test - public void shouldIndexMultipleLevelNestedObject(){ - //given - List indexQueries = createPerson(); + public void shouldIndexInitialLevelNestedObject() { - //when - elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(PersonMultipleLevelNested.class, true); + List cars = new ArrayList(); - //then - GetQuery getQuery = new GetQuery(); - getQuery.setId("1"); - PersonMultipleLevelNested personIndexed = elasticsearchTemplate.queryForObject(getQuery, PersonMultipleLevelNested.class); - assertThat(personIndexed, is(notNullValue())); - } + Car saturn = new Car(); + saturn.setName("Saturn"); + saturn.setModel("SL"); - @Test - public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject(){ - //given - List indexQueries = createPerson(); + Car subaru = new Car(); + subaru.setName("Subaru"); + subaru.setModel("Imprezza"); - //when - elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(PersonMultipleLevelNested.class, true); + Car ford = new Car(); + ford.setName("Ford"); + ford.setModel("Focus"); - //then - BoolQueryBuilder builder = boolQuery(); - builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type","temp"))) - .must(nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()))); + cars.add(saturn); + cars.add(subaru); + cars.add(ford); - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(builder) - .build(); + Person foo = new Person(); + foo.setName("Foo"); + foo.setId("1"); + foo.setCar(cars); - Page personIndexed = elasticsearchTemplate.queryForPage(searchQuery, PersonMultipleLevelNested.class); - assertThat(personIndexed, is(notNullValue())); - assertThat(personIndexed.getTotalElements(), is(1L)); - assertThat(personIndexed.getContent().get(0).getId(), is("1")); - } + Car car = new Car(); + car.setName("Saturn"); + car.setModel("Imprezza"); + + Person bar = new Person(); + bar.setId("2"); + bar.setName("Bar"); + bar.setCar(Arrays.asList(car)); + + List indexQueries = new ArrayList(); + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(foo.getId()); + indexQuery1.setObject(foo); + + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(bar.getId()); + indexQuery2.setObject(bar); + + indexQueries.add(indexQuery1); + indexQueries.add(indexQuery2); + + elasticsearchTemplate.putMapping(Person.class); + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(Person.class, true); + + QueryBuilder builder = nestedQuery("car", boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza"))); + + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); + List persons = elasticsearchTemplate.queryForList(searchQuery, Person.class); + + assertThat(persons.size(), is(1)); + } + + @Test + public void shouldIndexMultipleLevelNestedObject() { + //given + List indexQueries = createPerson(); + + //when + elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(PersonMultipleLevelNested.class, true); + + //then + GetQuery getQuery = new GetQuery(); + getQuery.setId("1"); + PersonMultipleLevelNested personIndexed = elasticsearchTemplate.queryForObject(getQuery, PersonMultipleLevelNested.class); + assertThat(personIndexed, is(notNullValue())); + } + + @Test + public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject() { + //given + List indexQueries = createPerson(); + + //when + elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(PersonMultipleLevelNested.class, true); + + //then + BoolQueryBuilder builder = boolQuery(); + builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"))) + .must(nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()))); + + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(builder) + .build(); + + Page personIndexed = elasticsearchTemplate.queryForPage(searchQuery, PersonMultipleLevelNested.class); + assertThat(personIndexed, is(notNullValue())); + assertThat(personIndexed.getTotalElements(), is(1L)); + assertThat(personIndexed.getContent().get(0).getId(), is("1")); + } @Test public void shouldIndexInnerObject() { @@ -196,62 +189,60 @@ public class NestedObjectTests { assertThat(bookRepository.findOne(id), is(notNullValue())); } - private List createPerson(){ + private List createPerson() { - PersonMultipleLevelNested person1 = new PersonMultipleLevelNested(); + PersonMultipleLevelNested person1 = new PersonMultipleLevelNested(); - person1.setId("1"); - person1.setName("name"); + person1.setId("1"); + person1.setName("name"); - Car saturn = new Car(); - saturn.setName("Saturn"); - saturn.setModel("SL"); + Car saturn = new Car(); + saturn.setName("Saturn"); + saturn.setModel("SL"); - Car subaru = new Car(); - subaru.setName("Subaru"); - subaru.setModel("Imprezza"); + Car subaru = new Car(); + subaru.setName("Subaru"); + subaru.setModel("Imprezza"); - Car car = new Car(); - car.setName("Saturn"); - car.setModel("Imprezza"); + Car car = new Car(); + car.setName("Saturn"); + car.setModel("Imprezza"); - Car ford = new Car(); - ford.setName("Ford"); - ford.setModel("Focus"); + Car ford = new Car(); + ford.setName("Ford"); + ford.setModel("Focus"); - GirlFriend permanent = new GirlFriend(); - permanent.setName("permanent"); - permanent.setType("permanent"); - permanent.setCars(Arrays.asList(saturn, subaru)); + GirlFriend permanent = new GirlFriend(); + permanent.setName("permanent"); + permanent.setType("permanent"); + permanent.setCars(Arrays.asList(saturn, subaru)); - GirlFriend temp = new GirlFriend(); - temp.setName("temp"); - temp.setType("temp"); - temp.setCars(Arrays.asList(car,ford)); + GirlFriend temp = new GirlFriend(); + temp.setName("temp"); + temp.setType("temp"); + temp.setCars(Arrays.asList(car, ford)); - person1.setGirlFriends(Arrays.asList(permanent, temp)); + person1.setGirlFriends(Arrays.asList(permanent, temp)); - IndexQuery indexQuery1 = new IndexQuery(); - indexQuery1.setId(person1.getId()); - indexQuery1.setObject(person1); + IndexQuery indexQuery1 = new IndexQuery(); + indexQuery1.setId(person1.getId()); + indexQuery1.setObject(person1); + PersonMultipleLevelNested person2 = new PersonMultipleLevelNested(); - PersonMultipleLevelNested person2 = new PersonMultipleLevelNested(); + person2.setId("2"); + person2.setName("name"); - person2.setId("2"); - person2.setName("name"); + person2.setGirlFriends(Arrays.asList(permanent)); - person2.setGirlFriends(Arrays.asList(permanent)); + IndexQuery indexQuery2 = new IndexQuery(); + indexQuery2.setId(person2.getId()); + indexQuery2.setObject(person2); - IndexQuery indexQuery2 = new IndexQuery(); - indexQuery2.setId(person2.getId()); - indexQuery2.setObject(person2); - - List indexQueries = new ArrayList(); - indexQueries.add(indexQuery1); - indexQueries.add(indexQuery2); - - return indexQueries; + List indexQueries = new ArrayList(); + indexQueries.add(indexQuery1); + indexQueries.add(indexQuery2); + return indexQueries; } } diff --git a/src/test/java/org/springframework/data/elasticsearch/ParentEntity.java b/src/test/java/org/springframework/data/elasticsearch/ParentEntity.java index 24658d389..4557011fc 100644 --- a/src/test/java/org/springframework/data/elasticsearch/ParentEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/ParentEntity.java @@ -18,6 +18,7 @@ package org.springframework.data.elasticsearch; import org.springframework.core.style.ToStringCreator; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.*; + /** * ParentEntity * @@ -26,6 +27,7 @@ import org.springframework.data.elasticsearch.annotations.*; */ @Document(indexName = ParentEntity.INDEX, type = ParentEntity.PARENT_TYPE, indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class ParentEntity { + public static final String INDEX = "parent-child"; public static final String PARENT_TYPE = "parent-entity"; public static final String CHILD_TYPE = "child-entity"; @@ -58,6 +60,7 @@ public class ParentEntity { @Document(indexName = INDEX, type = CHILD_TYPE, indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public static class ChildEntity { + @Id private String id; @Field(type = FieldType.String, store = true) diff --git a/src/test/java/org/springframework/data/elasticsearch/Person.java b/src/test/java/org/springframework/data/elasticsearch/Person.java index fbdef1155..f8f2530ec 100644 --- a/src/test/java/org/springframework/data/elasticsearch/Person.java +++ b/src/test/java/org/springframework/data/elasticsearch/Person.java @@ -16,51 +16,51 @@ package org.springframework.data.elasticsearch; +import java.util.List; + import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; -import java.util.List; - /** * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak */ -@Document( indexName = "person" , type = "user", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") +@Document(indexName = "person", type = "user", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class Person { - @Id - private String id; + @Id + private String id; - private String name; + private String name; - @Field( type = FieldType.Nested) - private List car; + @Field(type = FieldType.Nested) + private List car; - 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 List getCar() { - return car; - } + public List getCar() { + return car; + } - public void setCar(List car) { - this.car = car; - } + public void setCar(List car) { + this.car = car; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/PersonMultipleLevelNested.java b/src/test/java/org/springframework/data/elasticsearch/PersonMultipleLevelNested.java index 0c7e54889..00243d34c 100644 --- a/src/test/java/org/springframework/data/elasticsearch/PersonMultipleLevelNested.java +++ b/src/test/java/org/springframework/data/elasticsearch/PersonMultipleLevelNested.java @@ -16,51 +16,51 @@ package org.springframework.data.elasticsearch; +import java.util.List; + import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; -import java.util.List; - /** * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak */ -@Document( indexName = "person-multiple-level-nested" , type = "user", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") +@Document(indexName = "person-multiple-level-nested", type = "user", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class PersonMultipleLevelNested { - @Id - private String id; + @Id + private String id; - private String name; + private String name; - @Field(type = FieldType.Nested) - private List girlFriends; + @Field(type = FieldType.Nested) + private List girlFriends; - 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 List getGirlFriends() { - return girlFriends; - } + public List getGirlFriends() { + return girlFriends; + } - public void setGirlFriends(List girlFriends) { - this.girlFriends = girlFriends; - } + public void setGirlFriends(List girlFriends) { + this.girlFriends = girlFriends; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/Product.java b/src/test/java/org/springframework/data/elasticsearch/Product.java index de1141f00..ffcf1de95 100644 --- a/src/test/java/org/springframework/data/elasticsearch/Product.java +++ b/src/test/java/org/springframework/data/elasticsearch/Product.java @@ -15,12 +15,12 @@ */ package org.springframework.data.elasticsearch; -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.Document; - import java.util.Date; import java.util.List; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; + /** * @author Mohsin Husen */ @@ -174,5 +174,4 @@ public class Product { public void setText(String text) { this.text = text; } - } diff --git a/src/test/java/org/springframework/data/elasticsearch/SampleDateMappingEntity.java b/src/test/java/org/springframework/data/elasticsearch/SampleDateMappingEntity.java index 3d7ca3f29..45856052e 100644 --- a/src/test/java/org/springframework/data/elasticsearch/SampleDateMappingEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/SampleDateMappingEntity.java @@ -1,73 +1,74 @@ package org.springframework.data.elasticsearch; +import static org.springframework.data.elasticsearch.annotations.FieldIndex.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.String; + +import java.util.Date; + import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.DateFormat; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; -import java.util.Date; - -import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed; -import static org.springframework.data.elasticsearch.annotations.FieldType.String; -import static org.springframework.data.elasticsearch.annotations.FieldType.Date; - /** * @author Jakub Vavrik */ @Document(indexName = "test-datemapping", type = "mapping", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class SampleDateMappingEntity { - @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 = Date, format = DateFormat.custom, pattern = "dd.MM.yyyy hh:mm") - private Date customFormatDate; + @Field(type = String, index = not_analyzed, store = true, searchAnalyzer = "standard", indexAnalyzer = "standard") + private String message; - @Field(type = Date) - private Date defaultFormatDate; + @Field(type = Date, format = DateFormat.custom, pattern = "dd.MM.yyyy hh:mm") + private Date customFormatDate; - @Field(type = Date, format = DateFormat.basic_date) - private Date basicFormatDate; + @Field(type = Date) + private Date defaultFormatDate; - public String getId() { - return id; - } + @Field(type = Date, format = DateFormat.basic_date) + private Date basicFormatDate; - public void setId(String id) { - this.id = id; - } + public String getId() { + return id; + } - public String getMessage() { - return message; - } + public void setId(String id) { + this.id = id; + } - public void setMessage(String message) { - this.message = message; - } + public String getMessage() { + return message; + } - public Date getCustomFormatDate() { - return customFormatDate; - } + public void setMessage(String message) { + this.message = message; + } - public void setCustomFormatDate(Date customFormatDate) { - this.customFormatDate = customFormatDate; - } + public Date getCustomFormatDate() { + return customFormatDate; + } - public Date getDefaultFormatDate() { - return defaultFormatDate; - } + public void setCustomFormatDate(Date customFormatDate) { + this.customFormatDate = customFormatDate; + } - public void setDefaultFormatDate(Date defaultFormatDate) { - this.defaultFormatDate = defaultFormatDate; - } + public Date getDefaultFormatDate() { + return defaultFormatDate; + } - public Date getBasicFormatDate() { - return basicFormatDate; - } + public void setDefaultFormatDate(Date defaultFormatDate) { + this.defaultFormatDate = defaultFormatDate; + } - public void setBasicFormatDate(Date basicFormatDate) { - this.basicFormatDate = basicFormatDate; - } + public Date getBasicFormatDate() { + return basicFormatDate; + } + + public void setBasicFormatDate(Date basicFormatDate) { + this.basicFormatDate = basicFormatDate; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/SampleEntity.java b/src/test/java/org/springframework/data/elasticsearch/SampleEntity.java index 795ac6266..c828d80dd 100644 --- a/src/test/java/org/springframework/data/elasticsearch/SampleEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/SampleEntity.java @@ -34,7 +34,7 @@ public class SampleEntity { private String message; private int rate; private boolean available; - private String highlightedMessage; + private String highlightedMessage; @Version private Long version; @@ -78,12 +78,12 @@ public class SampleEntity { this.available = available; } - public String getHighlightedMessage() { - return highlightedMessage; - } + public String getHighlightedMessage() { + return highlightedMessage; + } - public void setHighlightedMessage(String highlightedMessage) { - this.highlightedMessage = highlightedMessage; + public void setHighlightedMessage(String highlightedMessage) { + this.highlightedMessage = highlightedMessage; } public Long getVersion() { @@ -113,16 +113,16 @@ public class SampleEntity { .toHashCode(); } - @Override - public String toString() { - return "SampleEntity{" + - "id='" + id + '\'' + - ", type='" + type + '\'' + - ", message='" + message + '\'' + - ", rate=" + rate + - ", available=" + available + - ", highlightedMessage='" + highlightedMessage + '\'' + - ", version=" + version + - '}'; - } + @Override + public String toString() { + return "SampleEntity{" + + "id='" + id + '\'' + + ", type='" + type + '\'' + + ", message='" + message + '\'' + + ", rate=" + rate + + ", available=" + available + + ", highlightedMessage='" + highlightedMessage + '\'' + + ", version=" + version + + '}'; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/SampleEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/SampleEntityBuilder.java index cce779050..9a881b57a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/SampleEntityBuilder.java +++ b/src/test/java/org/springframework/data/elasticsearch/SampleEntityBuilder.java @@ -24,51 +24,51 @@ import org.springframework.data.elasticsearch.core.query.IndexQuery; */ public class SampleEntityBuilder { - private SampleEntity result; + private SampleEntity result; - public SampleEntityBuilder(String id) { - result = new SampleEntity(); - result.setId(id); - } + public SampleEntityBuilder(String id) { + result = new SampleEntity(); + result.setId(id); + } - public SampleEntityBuilder type(String type) { - result.setType(type); - return this; - } + public SampleEntityBuilder type(String type) { + result.setType(type); + return this; + } - public SampleEntityBuilder message(String message) { - result.setMessage(message); - return this; - } + public SampleEntityBuilder message(String message) { + result.setMessage(message); + return this; + } - public SampleEntityBuilder rate(int rate) { - result.setRate(rate); - return this; - } + public SampleEntityBuilder rate(int rate) { + result.setRate(rate); + return this; + } - public SampleEntityBuilder available(boolean available) { - result.setAvailable(available); - return this; - } + public SampleEntityBuilder available(boolean available) { + result.setAvailable(available); + return this; + } - public SampleEntityBuilder highlightedMessage(String highlightedMessage) { - result.setHighlightedMessage(highlightedMessage); - return this; - } + public SampleEntityBuilder highlightedMessage(String highlightedMessage) { + result.setHighlightedMessage(highlightedMessage); + return this; + } - public SampleEntityBuilder version(Long version) { - result.setVersion(version); - return this; - } + public SampleEntityBuilder version(Long version) { + result.setVersion(version); + return this; + } - public SampleEntity build() { - return result; - } + public SampleEntity build() { + return result; + } - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/SampleMappingEntity.java b/src/test/java/org/springframework/data/elasticsearch/SampleMappingEntity.java index 831595321..ce10c955f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/SampleMappingEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/SampleMappingEntity.java @@ -15,14 +15,12 @@ */ package org.springframework.data.elasticsearch; +import static org.springframework.data.elasticsearch.annotations.FieldIndex.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.String; + import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; -import org.springframework.data.elasticsearch.annotations.FieldIndex; -import org.springframework.data.elasticsearch.annotations.FieldType; - -import static org.springframework.data.elasticsearch.annotations.FieldIndex.*; -import static org.springframework.data.elasticsearch.annotations.FieldType.*; /** * @author Rizwan Idrees @@ -31,41 +29,41 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.*; @Document(indexName = "test-mapping", type = "mapping", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class SampleMappingEntity { - @Id - private String id; + @Id + private String id; - @Field(type = String, index = not_analyzed, store = true, searchAnalyzer = "standard", indexAnalyzer = "standard") - private String message; + @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 { - public String getSomeField() { - return someField; - } + @Field(type = String) + private String someField; - public void setSomeField(String someField) { - this.someField = someField; - } - } + public String getSomeField() { + return someField; + } + public void setSomeField(String someField) { + this.someField = someField; + } + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/SampleTransientEntity.java b/src/test/java/org/springframework/data/elasticsearch/SampleTransientEntity.java index 994eefcfd..e9300d979 100644 --- a/src/test/java/org/springframework/data/elasticsearch/SampleTransientEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/SampleTransientEntity.java @@ -15,62 +15,66 @@ */ package org.springframework.data.elasticsearch; +import static org.springframework.data.elasticsearch.annotations.FieldIndex.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.String; + import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; -import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed; -import static org.springframework.data.elasticsearch.annotations.FieldType.String; - /** * @author Jakub Vavrik */ @Document(indexName = "test-recursive-mapping", type = "mapping", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class SampleTransientEntity { - @Id - private String id; + @Id + private String id; - @Field(type = String, index = not_analyzed, store = true, searchAnalyzer = "standard", indexAnalyzer = "standard") - private String message; + @Field(type = String, index = not_analyzed, store = true, searchAnalyzer = "standard", indexAnalyzer = "standard") + private String message; - @Transient - private NestedEntity nested; + @Transient + 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 - private static NestedEntity someField = new NestedEntity(); - @Field - private Boolean something; + static class NestedEntity { - public NestedEntity getSomeField() { - return someField; - } + @Field + private static NestedEntity someField = new NestedEntity(); + @Field + private Boolean something; - public void setSomeField(NestedEntity someField) { - this.someField = someField; - } + public NestedEntity getSomeField() { + return someField; + } - public Boolean getSomething() { return something; } + public void setSomeField(NestedEntity someField) { + this.someField = someField; + } - public void setSomething(Boolean something) { this.something = something; } - } + public Boolean getSomething() { + return something; + } + public void setSomething(Boolean something) { + this.something = something; + } + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/SimpleRecursiveEntity.java b/src/test/java/org/springframework/data/elasticsearch/SimpleRecursiveEntity.java index aa2083e3d..7c323df98 100644 --- a/src/test/java/org/springframework/data/elasticsearch/SimpleRecursiveEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/SimpleRecursiveEntity.java @@ -24,11 +24,11 @@ import org.springframework.data.elasticsearch.annotations.FieldType; * @author Stuart Stevenson * @author Mohsin Husen */ -@Document(indexName = "circular-objects", type = "circular-object" , indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") +@Document(indexName = "circular-objects", type = "circular-object", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class SimpleRecursiveEntity { - @Id - private String id; - @Field(type = FieldType.Object, ignoreFields = {"circularObject"}) - private SimpleRecursiveEntity circularObject; + @Id + private String id; + @Field(type = FieldType.Object, ignoreFields = {"circularObject"}) + private SimpleRecursiveEntity circularObject; } diff --git a/src/test/java/org/springframework/data/elasticsearch/StockPrice.java b/src/test/java/org/springframework/data/elasticsearch/StockPrice.java index 0d319305c..c76740a34 100644 --- a/src/test/java/org/springframework/data/elasticsearch/StockPrice.java +++ b/src/test/java/org/springframework/data/elasticsearch/StockPrice.java @@ -15,13 +15,13 @@ */ package org.springframework.data.elasticsearch; +import java.math.BigDecimal; + import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; -import java.math.BigDecimal; - /** * @author Artur Konczak * @author Mohsin Husen @@ -29,43 +29,43 @@ import java.math.BigDecimal; @Document(indexName = "stock", type = "price", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class StockPrice { - @Id - private String id; + @Id + private String id; - private String symbol; + private String symbol; - @Field(type = FieldType.Double) - private BigDecimal price; + @Field(type = FieldType.Double) + private BigDecimal price; - private StockPrice(){ - //don't delete - } + private StockPrice() { + //don't delete + } - public StockPrice(String id) { - this.id = id; - } + public StockPrice(String id) { + this.id = 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; + } - public String getSymbol() { - return symbol; - } + public String getSymbol() { + return symbol; + } - public void setSymbol(String symbol) { - this.symbol = symbol; - } + public void setSymbol(String symbol) { + this.symbol = symbol; + } - public BigDecimal getPrice() { - return price; - } + public BigDecimal getPrice() { + return price; + } - public void setPrice(BigDecimal price) { - this.price = price; - } + public void setPrice(BigDecimal price) { + this.price = price; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/StockPriceBuilder.java b/src/test/java/org/springframework/data/elasticsearch/StockPriceBuilder.java index 8a1b6c526..28c64b83c 100644 --- a/src/test/java/org/springframework/data/elasticsearch/StockPriceBuilder.java +++ b/src/test/java/org/springframework/data/elasticsearch/StockPriceBuilder.java @@ -15,45 +15,45 @@ */ package org.springframework.data.elasticsearch; -import org.springframework.data.elasticsearch.core.query.IndexQuery; - import java.math.BigDecimal; +import org.springframework.data.elasticsearch.core.query.IndexQuery; + /** * @author Artur Konczak * @author Mohsin Husen */ public class StockPriceBuilder { - private StockPrice result; + private StockPrice result; - public StockPriceBuilder(String id) { - result = new StockPrice(id); - } + public StockPriceBuilder(String id) { + result = new StockPrice(id); + } - public StockPriceBuilder symbol(String symbol) { - result.setSymbol(symbol); - return this; - } + public StockPriceBuilder symbol(String symbol) { + result.setSymbol(symbol); + return this; + } - public StockPriceBuilder price(BigDecimal price) { - result.setPrice(price); - return this; - } + public StockPriceBuilder price(BigDecimal price) { + result.setPrice(price); + return this; + } - public StockPriceBuilder price(double price) { - result.setPrice(new BigDecimal(price)); - return this; - } + public StockPriceBuilder price(double price) { + result.setPrice(new BigDecimal(price)); + return this; + } - public StockPrice build() { - return result; - } + public StockPrice build() { + return result; + } - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java b/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java index bfb4ff13e..4e0b33896 100644 --- a/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/ElasticsearchNamespaceHandlerTests.java @@ -15,21 +15,20 @@ */ package org.springframework.data.elasticsearch.config; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.*; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.data.elasticsearch.repositories.SampleElasticsearchRepository; import org.springframework.data.elasticsearch.client.NodeClientFactoryBean; import org.springframework.data.elasticsearch.client.TransportClientFactoryBean; +import org.springframework.data.elasticsearch.repositories.SampleElasticsearchRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -60,5 +59,4 @@ public class ElasticsearchNamespaceHandlerTests { 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 2e5e881db..f7b1431ad 100644 --- a/src/test/java/org/springframework/data/elasticsearch/config/EnableElasticsearchRepositoriesTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/config/EnableElasticsearchRepositoriesTests.java @@ -15,6 +15,10 @@ */ package org.springframework.data.elasticsearch.config; +import static org.elasticsearch.node.NodeBuilder.*; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -27,11 +31,6 @@ import org.springframework.data.elasticsearch.repository.config.EnableElasticsea import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.elasticsearch.node.NodeBuilder.nodeBuilder; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.junit.Assert.assertThat; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -57,5 +56,4 @@ public class EnableElasticsearchRepositoriesTests { public void bootstrapsRepository() { assertThat(repository, is(notNullValue())); } - } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/CustomEntityMapper.java b/src/test/java/org/springframework/data/elasticsearch/core/CustomEntityMapper.java index b90eb3e48..5ff250504 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/CustomEntityMapper.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/CustomEntityMapper.java @@ -23,19 +23,19 @@ import java.io.IOException; */ public class CustomEntityMapper implements EntityMapper { - public CustomEntityMapper(){ - //custom configuration/implementation (e.g. FasterXML/jackson) - } + public CustomEntityMapper() { + //custom configuration/implementation (e.g. FasterXML/jackson) + } - @Override - public String mapToString(Object object) throws IOException { - //mapping Object to String - return null; - } + @Override + public String mapToString(Object object) throws IOException { + //mapping Object to String + return null; + } - @Override - public T mapToObject(String source, Class clazz) throws IOException { - //mapping String to Object - return null; - } + @Override + public T mapToObject(String source, Class clazz) throws IOException { + //mapping String to Object + return null; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/CustomResultMapper.java b/src/test/java/org/springframework/data/elasticsearch/core/CustomResultMapper.java index 1d8d0b9b7..ccd7d10c9 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/CustomResultMapper.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/CustomResultMapper.java @@ -23,27 +23,27 @@ import org.springframework.data.domain.Pageable; * @author Artur Konczak * @author Mohsin Husen */ -public class CustomResultMapper implements ResultsMapper{ +public class CustomResultMapper implements ResultsMapper { - private EntityMapper entityMapper; + private EntityMapper entityMapper; - public CustomResultMapper(EntityMapper entityMapper) { - this.entityMapper = entityMapper; - } + public CustomResultMapper(EntityMapper entityMapper) { + this.entityMapper = entityMapper; + } - @Override - public EntityMapper getEntityMapper() { - return entityMapper; - } + @Override + public EntityMapper getEntityMapper() { + return entityMapper; + } - @Override - public T mapResult(GetResponse response, Class clazz) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + @Override + public T mapResult(GetResponse response, Class clazz) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } - @Override - public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { - return null; //To change body of implemented methods use File | Settings | File Templates. - } + @Override + public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/DefaultEntityMapperTests.java b/src/test/java/org/springframework/data/elasticsearch/core/DefaultEntityMapperTests.java index 2014a6a60..3caba48e5 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/DefaultEntityMapperTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/DefaultEntityMapperTests.java @@ -15,53 +15,52 @@ */ package org.springframework.data.elasticsearch.core; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.io.IOException; + import org.junit.Before; import org.junit.Test; import org.springframework.data.elasticsearch.Car; import org.springframework.data.elasticsearch.CarBuilder; -import java.io.IOException; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - /** * @author Artur Konczak * @author Mohsin Husen */ public class DefaultEntityMapperTests { - public static final String JSON_STRING = "{\"name\":\"Grat\",\"model\":\"Ford\"}"; - public static final String CAR_MODEL = "Ford"; - public static final String CAR_NAME = "Grat"; - DefaultEntityMapper entityMapper; + public static final String JSON_STRING = "{\"name\":\"Grat\",\"model\":\"Ford\"}"; + public static final String CAR_MODEL = "Ford"; + public static final String CAR_NAME = "Grat"; + DefaultEntityMapper entityMapper; - @Before - public void init(){ - entityMapper = new DefaultEntityMapper(); - } + @Before + public void init() { + entityMapper = new DefaultEntityMapper(); + } - @Test - public void shouldMapObjectToJsonString() throws IOException { - //Given + @Test + public void shouldMapObjectToJsonString() throws IOException { + //Given - //When - String jsonResult = entityMapper.mapToString(new CarBuilder().model(CAR_MODEL).name(CAR_NAME).build()); + //When + String jsonResult = entityMapper.mapToString(new CarBuilder().model(CAR_MODEL).name(CAR_NAME).build()); - //Then - assertThat(jsonResult, is(JSON_STRING)); - } + //Then + assertThat(jsonResult, is(JSON_STRING)); + } - @Test - public void shouldMapJsonStringToObject() throws IOException { - //Given + @Test + public void shouldMapJsonStringToObject() throws IOException { + //Given - //When - Car result = entityMapper.mapToObject(JSON_STRING,Car.class); - - //Then - assertThat(result.getName(),is(CAR_NAME)); - assertThat(result.getModel(),is(CAR_MODEL)); - } + //When + Car result = entityMapper.mapToObject(JSON_STRING, Car.class); + //Then + assertThat(result.getName(), is(CAR_NAME)); + assertThat(result.getModel(), is(CAR_MODEL)); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/DefaultResultMapperTests.java b/src/test/java/org/springframework/data/elasticsearch/core/DefaultResultMapperTests.java index f345f37c1..ff71668ba 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/DefaultResultMapperTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/DefaultResultMapperTests.java @@ -15,6 +15,14 @@ */ package org.springframework.data.elasticsearch.core; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + import org.apache.commons.collections.iterators.ArrayIterator; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.search.SearchResponse; @@ -28,110 +36,99 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.data.elasticsearch.Car; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - /** * @author Artur Konczak * @author Mohsin Husen */ public class DefaultResultMapperTests { - private DefaultResultMapper resultMapper; + private DefaultResultMapper resultMapper; - @Mock - private SearchResponse response; + @Mock + private SearchResponse response; - @Before - public void init() { - MockitoAnnotations.initMocks(this); - resultMapper = new DefaultResultMapper(); - } + @Before + public void init() { + MockitoAnnotations.initMocks(this); + resultMapper = new DefaultResultMapper(); + } - @Test - public void shouldMapSearchRequestToPage() { - //Given - SearchHit[] hits = {createCarHit("Ford", "Grat"), createCarHit("BMW", "Arrow")}; - SearchHits searchHits = mock(SearchHits.class); - when(searchHits.totalHits()).thenReturn(2L); - when(searchHits.iterator()).thenReturn(new ArrayIterator(hits)); - when(response.getHits()).thenReturn(searchHits); + @Test + public void shouldMapSearchRequestToPage() { + //Given + SearchHit[] hits = {createCarHit("Ford", "Grat"), createCarHit("BMW", "Arrow")}; + SearchHits searchHits = mock(SearchHits.class); + when(searchHits.totalHits()).thenReturn(2L); + when(searchHits.iterator()).thenReturn(new ArrayIterator(hits)); + when(response.getHits()).thenReturn(searchHits); - //When - FacetedPage page = resultMapper.mapResults(response, Car.class, null); + //When + FacetedPage page = resultMapper.mapResults(response, Car.class, null); - //Then - assertThat(page.hasContent(), is(true)); - assertThat(page.getTotalElements(), is(2L)); - assertThat(page.getContent().get(0).getName(), is("Ford")); - } + //Then + assertThat(page.hasContent(), is(true)); + assertThat(page.getTotalElements(), is(2L)); + assertThat(page.getContent().get(0).getName(), is("Ford")); + } - @Test - public void shouldMapPartialSearchRequestToObject() { - //Given - SearchHit[] hits = {createCarPartialHit("Ford", "Grat"), createCarPartialHit("BMW", "Arrow")}; - SearchHits searchHits = mock(SearchHits.class); - when(searchHits.totalHits()).thenReturn(2L); - when(searchHits.iterator()).thenReturn(new ArrayIterator(hits)); - when(response.getHits()).thenReturn(searchHits); + @Test + public void shouldMapPartialSearchRequestToObject() { + //Given + SearchHit[] hits = {createCarPartialHit("Ford", "Grat"), createCarPartialHit("BMW", "Arrow")}; + SearchHits searchHits = mock(SearchHits.class); + when(searchHits.totalHits()).thenReturn(2L); + when(searchHits.iterator()).thenReturn(new ArrayIterator(hits)); + when(response.getHits()).thenReturn(searchHits); - //When - FacetedPage page = resultMapper.mapResults(response, Car.class, null); + //When + FacetedPage page = resultMapper.mapResults(response, Car.class, null); - //Then - assertThat(page.hasContent(), is(true)); - assertThat(page.getTotalElements(), is(2L)); - assertThat(page.getContent().get(0).getName(), is("Ford")); - } + //Then + assertThat(page.hasContent(), is(true)); + assertThat(page.getTotalElements(), is(2L)); + assertThat(page.getContent().get(0).getName(), is("Ford")); + } - @Test - public void shouldMapGetRequestToObject() { - //Given - GetResponse response = mock(GetResponse.class); - when(response.getSourceAsString()).thenReturn(createJsonCar("Ford", "Grat")); + @Test + public void shouldMapGetRequestToObject() { + //Given + GetResponse response = mock(GetResponse.class); + when(response.getSourceAsString()).thenReturn(createJsonCar("Ford", "Grat")); - //When - Car result = resultMapper.mapResult(response, Car.class); + //When + Car result = resultMapper.mapResult(response, Car.class); - //Then - assertThat(result, notNullValue()); - assertThat(result.getModel(), is("Grat")); - assertThat(result.getName(), is("Ford")); - } + //Then + assertThat(result, notNullValue()); + assertThat(result.getModel(), is("Grat")); + assertThat(result.getName(), is("Ford")); + } - private SearchHit createCarHit(String name, String model) { - SearchHit hit = mock(SearchHit.class); - when(hit.sourceAsString()).thenReturn(createJsonCar(name, model)); - return hit; - } + private SearchHit createCarHit(String name, String model) { + SearchHit hit = mock(SearchHit.class); + when(hit.sourceAsString()).thenReturn(createJsonCar(name, model)); + return hit; + } - private SearchHit createCarPartialHit(String name, String model) { - SearchHit hit = mock(SearchHit.class); - when(hit.sourceAsString()).thenReturn(null); - when(hit.getFields()).thenReturn(createCarFields(name, model)); - return hit; - } + private SearchHit createCarPartialHit(String name, String model) { + SearchHit hit = mock(SearchHit.class); + when(hit.sourceAsString()).thenReturn(null); + when(hit.getFields()).thenReturn(createCarFields(name, model)); + return hit; + } - private String createJsonCar(String name, String model) { - final String q = "\""; - StringBuffer sb = new StringBuffer(); - sb.append("{").append(q).append("name").append(q).append(":").append(q).append(name).append(q).append(","); - sb.append(q).append("model").append(q).append(":").append(q).append(model).append(q).append("}"); - return sb.toString(); - } - - private Map createCarFields(String name, String model) { - Map result = new HashMap(); - result.put("name", new InternalSearchHitField("name", Arrays.asList(name))); - result.put("model", new InternalSearchHitField("model", Arrays.asList(model))); - return result; - } + private String createJsonCar(String name, String model) { + final String q = "\""; + StringBuffer sb = new StringBuffer(); + sb.append("{").append(q).append("name").append(q).append(":").append(q).append(name).append(q).append(","); + sb.append(q).append("model").append(q).append(":").append(q).append(model).append(q).append("}"); + return sb.toString(); + } + private Map createCarFields(String name, String model) { + Map result = new HashMap(); + result.put("name", new InternalSearchHitField("name", Arrays.asList(name))); + result.put("model", new InternalSearchHitField("model", Arrays.asList(model))); + return result; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateCustomMapperTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateCustomMapperTests.java index 1b108915e..dc2692637 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateCustomMapperTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateCustomMapperTests.java @@ -15,15 +15,15 @@ */ package org.springframework.data.elasticsearch.core; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - /** * @author Artur Konczak */ @@ -31,22 +31,21 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:elasticsearch-template-custom-mapper.xml") public class ElasticsearchTemplateCustomMapperTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; - @Autowired - private EntityMapper entityMapper; + @Autowired + private EntityMapper entityMapper; - @Autowired - private ResultsMapper resultsMapper; - - @Test - public void shouldUseCustomMapper() { - //given - //when - //them - assertThat(elasticsearchTemplate.getResultsMapper(), is(resultsMapper)); - assertThat(elasticsearchTemplate.getResultsMapper().getEntityMapper(), is(entityMapper)); - } + @Autowired + private ResultsMapper resultsMapper; + @Test + public void shouldUseCustomMapper() { + //given + //when + //them + assertThat(elasticsearchTemplate.getResultsMapper(), is(resultsMapper)); + assertThat(elasticsearchTemplate.getResultsMapper().getEntityMapper(), is(entityMapper)); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateParentChildTests.java b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateParentChildTests.java index d14496d29..29c3556e3 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateParentChildTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateParentChildTests.java @@ -15,16 +15,17 @@ */ package org.springframework.data.elasticsearch.core; -import static org.elasticsearch.index.query.QueryBuilders.hasChildQuery; -import static org.elasticsearch.index.query.QueryBuilders.topChildrenQuery; +import static org.elasticsearch.index.query.QueryBuilders.*; import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; +import static org.junit.Assert.*; import java.util.List; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; -import org.junit.*; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.ParentEntity; @@ -81,27 +82,27 @@ public class ElasticsearchTemplateParentChildTests { assertThat("parents", parents, contains(hasProperty("id", is(parent1.getId())))); } - @Test - public void shouldSearchTopChildrenForGivenParent(){ - // index two parents - ParentEntity parent1 = index("parent1", "First Parent"); - ParentEntity parent2 = index("parent2", "Second Parent"); + @Test + public void shouldSearchTopChildrenForGivenParent() { + // index two parents + ParentEntity parent1 = index("parent1", "First Parent"); + ParentEntity parent2 = index("parent2", "Second Parent"); - // index a child for each parent - String child1name = "First"; - index("child1", parent1.getId(), child1name); - index("child2", parent2.getId(), "Second"); + // index a child for each parent + String child1name = "First"; + index("child1", parent1.getId(), child1name); + index("child2", parent2.getId(), "Second"); - elasticsearchTemplate.refresh(ParentEntity.class, true); - elasticsearchTemplate.refresh(ChildEntity.class, true); + elasticsearchTemplate.refresh(ParentEntity.class, true); + elasticsearchTemplate.refresh(ChildEntity.class, true); - // find all parents that have the first child using topChildren Query - QueryBuilder query = topChildrenQuery(ParentEntity.CHILD_TYPE, QueryBuilders.fieldQuery("name", child1name)); - List parents = elasticsearchTemplate.queryForList(new NativeSearchQuery(query), ParentEntity.class); + // find all parents that have the first child using topChildren Query + QueryBuilder query = topChildrenQuery(ParentEntity.CHILD_TYPE, QueryBuilders.fieldQuery("name", child1name)); + List parents = elasticsearchTemplate.queryForList(new NativeSearchQuery(query), ParentEntity.class); - // we're expecting only the first parent as result - assertThat("parents", parents, contains(hasProperty("id", is(parent1.getId())))); - } + // we're expecting only the first parent as result + assertThat("parents", parents, contains(hasProperty("id", is(parent1.getId())))); + } private ParentEntity index(String parentId, String name) { ParentEntity parent = new ParentEntity(parentId, name); 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 605d10453..c261a1e1a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/ElasticsearchTemplateTests.java @@ -15,6 +15,16 @@ */ package org.springframework.data.elasticsearch.core; +import static org.apache.commons.lang.RandomStringUtils.*; +import static org.elasticsearch.index.query.FilterBuilders.*; +import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.index.engine.DocumentMissingException; @@ -39,17 +49,6 @@ import org.springframework.data.elasticsearch.core.query.*; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import static org.apache.commons.lang.RandomStringUtils.randomNumeric; -import static org.elasticsearch.index.query.FilterBuilders.boolFilter; -import static org.elasticsearch.index.query.FilterBuilders.termFilter; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -59,1037 +58,1034 @@ import static org.junit.Assert.*; @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); - elasticsearchTemplate.createIndex(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, String.class, new SearchResultMapper() { - @Override - public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { - List values = new ArrayList(); - for (SearchHit searchHit : response.getHits()) { - values.add((String) searchHit.field("message").value()); - } - return new FacetedPageImpl((List) 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 entities = createSampleEntitiesWithMessage("Test message", 30); - // when - elasticsearchTemplate.bulkIndex(entities); - elasticsearchTemplate.refresh(SampleEntity.class, true); - // then - - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices("test-index") - .withTypes("test-type").withPageable(new PageRequest(0, 10)).build(); - - String scrollId = elasticsearchTemplate.scan(searchQuery, 1000, false); - List sampleEntities = new ArrayList(); - boolean hasRecords = true; - while (hasRecords) { - Page page = elasticsearchTemplate.scroll(scrollId, 5000L, SampleEntity.class); - if (page.hasContent()) { - sampleEntities.addAll(page.getContent()); - } else { - hasRecords = false; - } - - } - assertThat(sampleEntities.size(), is(equalTo(30))); - } - - @Test - public void shouldReturnResultsForScanAndScrollWithCustomResultMapper() { - //given - List entities = createSampleEntitiesWithMessage("Test message", 30); - // when - elasticsearchTemplate.bulkIndex(entities); - elasticsearchTemplate.refresh(SampleEntity.class, true); - // then - - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices("test-index") - .withTypes("test-type").withPageable(new PageRequest(0, 10)).build(); - - String scrollId = elasticsearchTemplate.scan(searchQuery, 1000, false); - List sampleEntities = new ArrayList(); - boolean hasRecords = true; - while (hasRecords) { - Page page = elasticsearchTemplate.scroll(scrollId, 5000L, new SearchResultMapper() { - @Override - public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { - 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); - } - if (chunk.size() > 0) { - return new FacetedPageImpl((List) chunk); - } - return null; - } - }); - if (page != null) { - sampleEntities.addAll(page.getContent()); - } else { - hasRecords = false; - } - } - assertThat(sampleEntities.size(), is(equalTo(30))); - } - - private static List createSampleEntitiesWithMessage(String message, int numberOfEntities) { - List indexQueries = 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()); - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - indexQueries.add(indexQuery); - } - return indexQueries; - } - - @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)); - } - - @Test - public void shouldDoPartialUpdateForExistingDocument() { - //given - String documentId = randomNumeric(5); - String messageBeforeUpdate = "some test message"; - String messageAfterUpdate = "test message"; - - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage(messageBeforeUpdate); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(documentId); - indexQuery.setObject(sampleEntity); - - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - - IndexRequest indexRequest = new IndexRequest(); - indexRequest.source("message", messageAfterUpdate); - UpdateQuery updateQuery = new UpdateQueryBuilder().withId(documentId) - .withClass(SampleEntity.class).withIndexRequest(indexRequest).build(); - // when - elasticsearchTemplate.update(updateQuery); - //then - GetQuery getQuery = new GetQuery(); - getQuery.setId(documentId); - SampleEntity indexedEntity = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); - assertThat(indexedEntity.getMessage(), is(messageAfterUpdate)); - } - - @Test(expected = DocumentMissingException.class) - public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() { - // when - IndexRequest indexRequest = new IndexRequest(); - UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)) - .withClass(SampleEntity.class).withIndexRequest(indexRequest).build(); - elasticsearchTemplate.update(updateQuery); - } - - @Test - public void shouldDoUpsertIfDocumentDoesNotExist() { - //given - String documentId = randomNumeric(5); - String message = "test message"; - IndexRequest indexRequest = new IndexRequest(); - indexRequest.source("message", message); - UpdateQuery updateQuery = new UpdateQueryBuilder().withId(documentId) - .withDoUpsert(true).withClass(SampleEntity.class) - .withIndexRequest(indexRequest).build(); - //when - elasticsearchTemplate.update(updateQuery); - //then - GetQuery getQuery = new GetQuery(); - getQuery.setId(documentId); - SampleEntity indexedEntity = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); - assertThat(indexedEntity.getMessage(), is(message)); - } - - @Test - public void shouldReturnHighlightedFieldsForGivenQueryAndFields() { - - //given - String documentId = randomNumeric(5); - String actualMessage = "some test message"; - String highlightedMessage = "some test message"; - - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(documentId); - sampleEntity.setMessage(actualMessage); - 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(termQuery("message", "test")) - .withHighlightFields(new HighlightBuilder.Field("message")) - .build(); - - Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() { - @Override - public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { - 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")); - user.setHighlightedMessage(searchHit.getHighlightFields().get("message").fragments()[0].toString()); - chunk.add(user); - } - if (chunk.size() > 0) { - return new FacetedPageImpl((List) chunk); - } - return null; - } - }); - - assertThat(sampleEntities.getContent().get(0).getHighlightedMessage(), is(highlightedMessage)); - - } - - @Test - public void shouldDeleteSpecifiedTypeFromAnIndex() { - // 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); - // when - elasticsearchTemplate.deleteType("test-index", "test-type"); - - //then - boolean typeExists = elasticsearchTemplate.typeExists("test-index", "test-type"); - assertThat(typeExists, is(false)); - } - - @Test - public void shouldDeleteDocumentBySpecifiedTypeUsingDeleteQuery() { - // 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)); - deleteQuery.setIndex("test-index"); - deleteQuery.setType("test-type"); - elasticsearchTemplate.delete(deleteQuery); - // 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 shouldAddAlias(){ - // given - elasticsearchTemplate.createIndex(SampleEntity.class); - AliasQuery aliasQuery = new AliasBuilder() - .withIndexName("test-index") - .withAliasName("test-alias").build(); - // when - elasticsearchTemplate.addAlias(aliasQuery); - // then - Set aliases = elasticsearchTemplate.queryForAlias("test-index"); - assertThat(aliases, is(notNullValue())); - assertThat(aliases.contains("test-alias"), is(true)); - } - - @Test - public void shouldRemoveAlias(){ - // given - elasticsearchTemplate.createIndex(SampleEntity.class); - String indexName = "test-index"; - String aliasName = "test-alias"; - AliasQuery aliasQuery = new AliasBuilder() - .withIndexName(indexName) - .withAliasName(aliasName).build(); - // when - elasticsearchTemplate.addAlias(aliasQuery); - Set aliases = elasticsearchTemplate.queryForAlias(indexName); - assertThat(aliases, is(notNullValue())); - assertThat(aliases.contains(aliasName), is(true)); - // then - elasticsearchTemplate.removeAlias(aliasQuery); - aliases = elasticsearchTemplate.queryForAlias(indexName); - assertThat(aliases, is(notNullValue())); - assertThat(aliases.size(), is(0)); - } - - - @Test - public void shouldIndexDocumentForSpecifiedSource(){ - - // given - String documentSource = "{\"id\":\"2333343434\",\"type\":null,\"message\":\"some message\",\"rate\":0,\"available\":false,\"highlightedMessage\":null,\"version\":1385208779482}"; - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId("2333343434"); - indexQuery.setSource(documentSource); - indexQuery.setIndexName("test-index"); - indexQuery.setType("test-type"); - // when - elasticsearchTemplate.index(indexQuery); - elasticsearchTemplate.refresh(SampleEntity.class, true); - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id",indexQuery.getId())) - .withIndices("test-index") - .withTypes("test-type") - .build(); - // then - Page page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() { - @Override - public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { - List values = new ArrayList(); - for (SearchHit searchHit : response.getHits()) { - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setId(searchHit.getId()); - sampleEntity.setMessage((String) searchHit.getSource().get("message")); - values.add(sampleEntity); - } - return new FacetedPageImpl((List) values); - } - }); - assertThat(page, is(notNullValue())); - assertThat(page.getContent().size(), is(1)); - assertThat(page.getContent().get(0).getId(), is(indexQuery.getId())); - } - - @Test (expected = ElasticsearchException.class) - public void shouldThrowElasticsearchExceptionWhenNoDocumentSpecified(){ - // given - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId("2333343434"); - indexQuery.setIndexName("test-index"); - indexQuery.setType("test-type"); - - //when - elasticsearchTemplate.index(indexQuery); - } - - @Test - public void shouldReturnIds(){ - //given - List entities = createSampleEntitiesWithMessage("Test message", 30); - // when - elasticsearchTemplate.bulkIndex(entities); - elasticsearchTemplate.refresh(SampleEntity.class, true); - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(termQuery("message", "message")) - .withIndices("test-index") - .withTypes("test-type") - .withPageable(new PageRequest(0,100)) - .build(); - // then - List ids = elasticsearchTemplate.queryForIds(searchQuery); - assertThat(ids, is(notNullValue())); - assertThat(ids.size(), is(30)); - } - - @Test - public void shouldReturnDocumentAboveMinimalScoreGivenQuery() { - // given - List indexQueries = new ArrayList(); - - indexQueries.add(new SampleEntityBuilder("1").message("ab").buildIndex()); - indexQueries.add(new SampleEntityBuilder("2").message("bc").buildIndex()); - indexQueries.add(new SampleEntityBuilder("3").message("ac").buildIndex()); - - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class, true); - - // when - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(boolQuery().must(wildcardQuery("message", "*a*")).should(wildcardQuery("message", "*b*"))) - .withIndices("test-index") - .withTypes("test-type") - .withMinScore(0.5F) - .build(); - - Page page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); - // then - assertThat(page.getTotalElements(),is(1L)); - assertThat(page.getContent().get(0).getMessage(), is("ab")); - } - - - @Test - public void shouldDoIndexWithoutId() { - // given - // document - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setObject(sampleEntity); - // when - String documentId = elasticsearchTemplate.index(indexQuery); - // then - assertThat(sampleEntity.getId(), is(equalTo(documentId))); - - GetQuery getQuery = new GetQuery(); - getQuery.setId(documentId); - SampleEntity result = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); - assertThat(result.getId(), is(equalTo(documentId))); - } - - @Test - public void shouldDoBulkIndexWithoutId() { - // given - List indexQueries = new ArrayList(); - // first document - String documentId = randomNumeric(5); - SampleEntity sampleEntity1 = new SampleEntity(); - sampleEntity1.setMessage("some message"); - sampleEntity1.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery1 = new IndexQuery(); - //indexQuery1.setId(documentId); - indexQuery1.setObject(sampleEntity1); - indexQueries.add(indexQuery1); - - // second document - SampleEntity sampleEntity2 = new SampleEntity(); - sampleEntity2.setMessage("some message"); - sampleEntity2.setVersion(System.currentTimeMillis()); - - IndexQuery indexQuery2 = new IndexQuery(); - 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))); - - assertThat(sampleEntities.getContent().get(0).getId(), is(notNullValue())); - assertThat(sampleEntities.getContent().get(1).getId(), is(notNullValue())); - } - + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + elasticsearchTemplate.deleteIndex(SampleEntity.class); + elasticsearchTemplate.createIndex(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, String.class, new SearchResultMapper() { + @Override + public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { + List values = new ArrayList(); + for (SearchHit searchHit : response.getHits()) { + values.add((String) searchHit.field("message").value()); + } + return new FacetedPageImpl((List) 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 entities = createSampleEntitiesWithMessage("Test message", 30); + // when + elasticsearchTemplate.bulkIndex(entities); + elasticsearchTemplate.refresh(SampleEntity.class, true); + // then + + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices("test-index") + .withTypes("test-type").withPageable(new PageRequest(0, 10)).build(); + + String scrollId = elasticsearchTemplate.scan(searchQuery, 1000, false); + List sampleEntities = new ArrayList(); + boolean hasRecords = true; + while (hasRecords) { + Page page = elasticsearchTemplate.scroll(scrollId, 5000L, SampleEntity.class); + if (page.hasContent()) { + sampleEntities.addAll(page.getContent()); + } else { + hasRecords = false; + } + } + assertThat(sampleEntities.size(), is(equalTo(30))); + } + + @Test + public void shouldReturnResultsForScanAndScrollWithCustomResultMapper() { + //given + List entities = createSampleEntitiesWithMessage("Test message", 30); + // when + elasticsearchTemplate.bulkIndex(entities); + elasticsearchTemplate.refresh(SampleEntity.class, true); + // then + + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices("test-index") + .withTypes("test-type").withPageable(new PageRequest(0, 10)).build(); + + String scrollId = elasticsearchTemplate.scan(searchQuery, 1000, false); + List sampleEntities = new ArrayList(); + boolean hasRecords = true; + while (hasRecords) { + Page page = elasticsearchTemplate.scroll(scrollId, 5000L, new SearchResultMapper() { + @Override + public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { + 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); + } + if (chunk.size() > 0) { + return new FacetedPageImpl((List) chunk); + } + return null; + } + }); + if (page != null) { + sampleEntities.addAll(page.getContent()); + } else { + hasRecords = false; + } + } + assertThat(sampleEntities.size(), is(equalTo(30))); + } + + private static List createSampleEntitiesWithMessage(String message, int numberOfEntities) { + List indexQueries = 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()); + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + indexQueries.add(indexQuery); + } + return indexQueries; + } + + @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)); + } + + @Test + public void shouldDoPartialUpdateForExistingDocument() { + //given + String documentId = randomNumeric(5); + String messageBeforeUpdate = "some test message"; + String messageAfterUpdate = "test message"; + + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage(messageBeforeUpdate); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(documentId); + indexQuery.setObject(sampleEntity); + + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + + IndexRequest indexRequest = new IndexRequest(); + indexRequest.source("message", messageAfterUpdate); + UpdateQuery updateQuery = new UpdateQueryBuilder().withId(documentId) + .withClass(SampleEntity.class).withIndexRequest(indexRequest).build(); + // when + elasticsearchTemplate.update(updateQuery); + //then + GetQuery getQuery = new GetQuery(); + getQuery.setId(documentId); + SampleEntity indexedEntity = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); + assertThat(indexedEntity.getMessage(), is(messageAfterUpdate)); + } + + @Test(expected = DocumentMissingException.class) + public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() { + // when + IndexRequest indexRequest = new IndexRequest(); + UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)) + .withClass(SampleEntity.class).withIndexRequest(indexRequest).build(); + elasticsearchTemplate.update(updateQuery); + } + + @Test + public void shouldDoUpsertIfDocumentDoesNotExist() { + //given + String documentId = randomNumeric(5); + String message = "test message"; + IndexRequest indexRequest = new IndexRequest(); + indexRequest.source("message", message); + UpdateQuery updateQuery = new UpdateQueryBuilder().withId(documentId) + .withDoUpsert(true).withClass(SampleEntity.class) + .withIndexRequest(indexRequest).build(); + //when + elasticsearchTemplate.update(updateQuery); + //then + GetQuery getQuery = new GetQuery(); + getQuery.setId(documentId); + SampleEntity indexedEntity = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); + assertThat(indexedEntity.getMessage(), is(message)); + } + + @Test + public void shouldReturnHighlightedFieldsForGivenQueryAndFields() { + + //given + String documentId = randomNumeric(5); + String actualMessage = "some test message"; + String highlightedMessage = "some test message"; + + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(documentId); + sampleEntity.setMessage(actualMessage); + 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(termQuery("message", "test")) + .withHighlightFields(new HighlightBuilder.Field("message")) + .build(); + + Page sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() { + @Override + public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { + 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")); + user.setHighlightedMessage(searchHit.getHighlightFields().get("message").fragments()[0].toString()); + chunk.add(user); + } + if (chunk.size() > 0) { + return new FacetedPageImpl((List) chunk); + } + return null; + } + }); + + assertThat(sampleEntities.getContent().get(0).getHighlightedMessage(), is(highlightedMessage)); + } + + @Test + public void shouldDeleteSpecifiedTypeFromAnIndex() { + // 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); + // when + elasticsearchTemplate.deleteType("test-index", "test-type"); + + //then + boolean typeExists = elasticsearchTemplate.typeExists("test-index", "test-type"); + assertThat(typeExists, is(false)); + } + + @Test + public void shouldDeleteDocumentBySpecifiedTypeUsingDeleteQuery() { + // 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)); + deleteQuery.setIndex("test-index"); + deleteQuery.setType("test-type"); + elasticsearchTemplate.delete(deleteQuery); + // 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 shouldAddAlias() { + // given + elasticsearchTemplate.createIndex(SampleEntity.class); + AliasQuery aliasQuery = new AliasBuilder() + .withIndexName("test-index") + .withAliasName("test-alias").build(); + // when + elasticsearchTemplate.addAlias(aliasQuery); + // then + Set aliases = elasticsearchTemplate.queryForAlias("test-index"); + assertThat(aliases, is(notNullValue())); + assertThat(aliases.contains("test-alias"), is(true)); + } + + @Test + public void shouldRemoveAlias() { + // given + elasticsearchTemplate.createIndex(SampleEntity.class); + String indexName = "test-index"; + String aliasName = "test-alias"; + AliasQuery aliasQuery = new AliasBuilder() + .withIndexName(indexName) + .withAliasName(aliasName).build(); + // when + elasticsearchTemplate.addAlias(aliasQuery); + Set aliases = elasticsearchTemplate.queryForAlias(indexName); + assertThat(aliases, is(notNullValue())); + assertThat(aliases.contains(aliasName), is(true)); + // then + elasticsearchTemplate.removeAlias(aliasQuery); + aliases = elasticsearchTemplate.queryForAlias(indexName); + assertThat(aliases, is(notNullValue())); + assertThat(aliases.size(), is(0)); + } + + + @Test + public void shouldIndexDocumentForSpecifiedSource() { + + // given + String documentSource = "{\"id\":\"2333343434\",\"type\":null,\"message\":\"some message\",\"rate\":0,\"available\":false,\"highlightedMessage\":null,\"version\":1385208779482}"; + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId("2333343434"); + indexQuery.setSource(documentSource); + indexQuery.setIndexName("test-index"); + indexQuery.setType("test-type"); + // when + elasticsearchTemplate.index(indexQuery); + elasticsearchTemplate.refresh(SampleEntity.class, true); + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", indexQuery.getId())) + .withIndices("test-index") + .withTypes("test-type") + .build(); + // then + Page page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() { + @Override + public FacetedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) { + List values = new ArrayList(); + for (SearchHit searchHit : response.getHits()) { + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setId(searchHit.getId()); + sampleEntity.setMessage((String) searchHit.getSource().get("message")); + values.add(sampleEntity); + } + return new FacetedPageImpl((List) values); + } + }); + assertThat(page, is(notNullValue())); + assertThat(page.getContent().size(), is(1)); + assertThat(page.getContent().get(0).getId(), is(indexQuery.getId())); + } + + @Test(expected = ElasticsearchException.class) + public void shouldThrowElasticsearchExceptionWhenNoDocumentSpecified() { + // given + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId("2333343434"); + indexQuery.setIndexName("test-index"); + indexQuery.setType("test-type"); + + //when + elasticsearchTemplate.index(indexQuery); + } + + @Test + public void shouldReturnIds() { + //given + List entities = createSampleEntitiesWithMessage("Test message", 30); + // when + elasticsearchTemplate.bulkIndex(entities); + elasticsearchTemplate.refresh(SampleEntity.class, true); + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(termQuery("message", "message")) + .withIndices("test-index") + .withTypes("test-type") + .withPageable(new PageRequest(0, 100)) + .build(); + // then + List ids = elasticsearchTemplate.queryForIds(searchQuery); + assertThat(ids, is(notNullValue())); + assertThat(ids.size(), is(30)); + } + + @Test + public void shouldReturnDocumentAboveMinimalScoreGivenQuery() { + // given + List indexQueries = new ArrayList(); + + indexQueries.add(new SampleEntityBuilder("1").message("ab").buildIndex()); + indexQueries.add(new SampleEntityBuilder("2").message("bc").buildIndex()); + indexQueries.add(new SampleEntityBuilder("3").message("ac").buildIndex()); + + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); + + // when + SearchQuery searchQuery = new NativeSearchQueryBuilder() + .withQuery(boolQuery().must(wildcardQuery("message", "*a*")).should(wildcardQuery("message", "*b*"))) + .withIndices("test-index") + .withTypes("test-type") + .withMinScore(0.5F) + .build(); + + Page page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); + // then + assertThat(page.getTotalElements(), is(1L)); + assertThat(page.getContent().get(0).getMessage(), is("ab")); + } + + + @Test + public void shouldDoIndexWithoutId() { + // given + // document + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setObject(sampleEntity); + // when + String documentId = elasticsearchTemplate.index(indexQuery); + // then + assertThat(sampleEntity.getId(), is(equalTo(documentId))); + + GetQuery getQuery = new GetQuery(); + getQuery.setId(documentId); + SampleEntity result = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); + assertThat(result.getId(), is(equalTo(documentId))); + } + + @Test + public void shouldDoBulkIndexWithoutId() { + // given + List indexQueries = new ArrayList(); + // first document + String documentId = randomNumeric(5); + SampleEntity sampleEntity1 = new SampleEntity(); + sampleEntity1.setMessage("some message"); + sampleEntity1.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery1 = new IndexQuery(); + //indexQuery1.setId(documentId); + indexQuery1.setObject(sampleEntity1); + indexQueries.add(indexQuery1); + + // second document + SampleEntity sampleEntity2 = new SampleEntity(); + sampleEntity2.setMessage("some message"); + sampleEntity2.setVersion(System.currentTimeMillis()); + + IndexQuery indexQuery2 = new IndexQuery(); + 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))); + + assertThat(sampleEntities.getContent().get(0).getId(), is(notNullValue())); + assertThat(sampleEntities.getContent().get(1).getId(), is(notNullValue())); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/MappingBuilderTests.java b/src/test/java/org/springframework/data/elasticsearch/core/MappingBuilderTests.java index 5ec35c25b..1d857c699 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/MappingBuilderTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/MappingBuilderTests.java @@ -16,6 +16,14 @@ package org.springframework.data.elasticsearch.core; +import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.List; + import org.elasticsearch.common.xcontent.XContentBuilder; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,14 +34,6 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.IOException; -import java.math.BigDecimal; -import java.util.List; - -import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - /** * @author Stuart Stevenson * @author Jakub Vavrik @@ -43,64 +43,64 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class MappingBuilderTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; - @Test - public void shouldNotFailOnCircularReference() { - elasticsearchTemplate.createIndex(SimpleRecursiveEntity.class); - elasticsearchTemplate.putMapping(SimpleRecursiveEntity.class); - } + @Test + public void shouldNotFailOnCircularReference() { + elasticsearchTemplate.createIndex(SimpleRecursiveEntity.class); + elasticsearchTemplate.putMapping(SimpleRecursiveEntity.class); + } - @Test - public void testInfiniteLoopAvoidance() throws IOException { - final String expected = "{\"mapping\":{\"properties\":{\"message\":{\"store\":true,\"" + - "type\":\"string\",\"index\":\"not_analyzed\",\"search_analyzer\":\"standard\"," + - "\"index_analyzer\":\"standard\"}}}}"; + @Test + public void testInfiniteLoopAvoidance() throws IOException { + final String expected = "{\"mapping\":{\"properties\":{\"message\":{\"store\":true,\"" + + "type\":\"string\",\"index\":\"not_analyzed\",\"search_analyzer\":\"standard\"," + + "\"index_analyzer\":\"standard\"}}}}"; - XContentBuilder xContentBuilder = MappingBuilder.buildMapping(SampleTransientEntity.class, "mapping", "id", null); - assertThat(xContentBuilder.string(), is(expected)); - } + XContentBuilder xContentBuilder = MappingBuilder.buildMapping(SampleTransientEntity.class, "mapping", "id", null); + assertThat(xContentBuilder.string(), is(expected)); + } - @Test - public void shouldUseValueFromAnnotationType() throws IOException { - //Given - final String expected = "{\"mapping\":{\"properties\":{\"price\":{\"store\":false,\"type\":\"double\"}}}}"; + @Test + public void shouldUseValueFromAnnotationType() throws IOException { + //Given + final String expected = "{\"mapping\":{\"properties\":{\"price\":{\"store\":false,\"type\":\"double\"}}}}"; - //When - XContentBuilder xContentBuilder = MappingBuilder.buildMapping(StockPrice.class, "mapping", "id", null); + //When + XContentBuilder xContentBuilder = MappingBuilder.buildMapping(StockPrice.class, "mapping", "id", null); - //Then - assertThat(xContentBuilder.string(), is(expected)); - } + //Then + assertThat(xContentBuilder.string(), is(expected)); + } - @Test - public void shouldAddStockPriceDocumentToIndex() throws IOException { - //Given + @Test + public void shouldAddStockPriceDocumentToIndex() throws IOException { + //Given - //When - elasticsearchTemplate.deleteIndex(StockPrice.class); - elasticsearchTemplate.createIndex(StockPrice.class); - elasticsearchTemplate.putMapping(StockPrice.class); - String symbol = "AU"; - double price = 2.34; - String id = "abc"; - elasticsearchTemplate.index(new StockPriceBuilder(id).symbol(symbol).price(price).buildIndex()); - elasticsearchTemplate.refresh(StockPrice.class, true); + //When + elasticsearchTemplate.deleteIndex(StockPrice.class); + elasticsearchTemplate.createIndex(StockPrice.class); + elasticsearchTemplate.putMapping(StockPrice.class); + String symbol = "AU"; + double price = 2.34; + String id = "abc"; + elasticsearchTemplate.index(new StockPriceBuilder(id).symbol(symbol).price(price).buildIndex()); + elasticsearchTemplate.refresh(StockPrice.class, true); - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); - List result = elasticsearchTemplate.queryForList(searchQuery, StockPrice.class); - //Then - assertThat(result.size(), is(1)); - StockPrice entry = result.get(0); - assertThat(entry.getSymbol(), is(symbol)); - assertThat(entry.getPrice(), is(new BigDecimal(price))); - } + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); + List result = elasticsearchTemplate.queryForList(searchQuery, StockPrice.class); + //Then + assertThat(result.size(), is(1)); + StockPrice entry = result.get(0); + assertThat(entry.getSymbol(), is(symbol)); + assertThat(entry.getPrice(), is(new BigDecimal(price))); + } - @Test - public void shouldCreateMappingForSpecifiedParentType() throws IOException { - final String expected = "{\"mapping\":{\"_parent\":{\"type\":\"parentType\"},\"properties\":{}}}"; - XContentBuilder xContentBuilder = MappingBuilder.buildMapping(MinimalEntity.class, "mapping", "id", "parentType"); - assertThat(xContentBuilder.string(), is(expected)); - } + @Test + public void shouldCreateMappingForSpecifiedParentType() throws IOException { + final String expected = "{\"mapping\":{\"_parent\":{\"type\":\"parentType\"},\"properties\":{}}}"; + XContentBuilder xContentBuilder = MappingBuilder.buildMapping(MinimalEntity.class, "mapping", "id", "parentType"); + assertThat(xContentBuilder.string(), is(expected)); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/SimpleElasticsearchDateMappingTest.java b/src/test/java/org/springframework/data/elasticsearch/core/SimpleElasticsearchDateMappingTest.java index 5c7e5eda2..b14661cb6 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/SimpleElasticsearchDateMappingTest.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/SimpleElasticsearchDateMappingTest.java @@ -15,28 +15,29 @@ */ package org.springframework.data.elasticsearch.core; +import java.beans.IntrospectionException; +import java.io.IOException; + import org.elasticsearch.common.xcontent.XContentBuilder; import org.junit.Assert; import org.junit.Test; import org.springframework.data.elasticsearch.SampleDateMappingEntity; -import java.beans.IntrospectionException; -import java.io.IOException; - /** * @author Jakub Vavrik * @author Mohsin Husen */ public class SimpleElasticsearchDateMappingTest { - private static final String EXPECTED_MAPPING = "{\"mapping\":{\"properties\":{\"message\":{\"store\":true," + - "\"type\":\"string\",\"index\":\"not_analyzed\",\"search_analyzer\":\"standard\",\"index_analyzer\"" + - ":\"standard\"},\"customFormatDate\":{\"store\":false,\"type\":\"date\",\"format\":\"dd.MM.yyyy hh:mm\"}," + - "\"defaultFormatDate\":{\"store\":false,\"type\":\"date\"},\"basicFormatDate\":{\"store\":false,\"" + - "type\":\"date\",\"format\":\"basic_date\"}}}}"; - @Test - public void testCorrectDateMappings() throws NoSuchFieldException, IntrospectionException, IOException { - XContentBuilder xContentBuilder = MappingBuilder.buildMapping(SampleDateMappingEntity.class, "mapping", "id", null); - Assert.assertEquals(EXPECTED_MAPPING, xContentBuilder.string()); - } + private static final String EXPECTED_MAPPING = "{\"mapping\":{\"properties\":{\"message\":{\"store\":true," + + "\"type\":\"string\",\"index\":\"not_analyzed\",\"search_analyzer\":\"standard\",\"index_analyzer\"" + + ":\"standard\"},\"customFormatDate\":{\"store\":false,\"type\":\"date\",\"format\":\"dd.MM.yyyy hh:mm\"}," + + "\"defaultFormatDate\":{\"store\":false,\"type\":\"date\"},\"basicFormatDate\":{\"store\":false,\"" + + "type\":\"date\",\"format\":\"basic_date\"}}}}"; + + @Test + public void testCorrectDateMappings() throws NoSuchFieldException, IntrospectionException, IOException { + XContentBuilder xContentBuilder = MappingBuilder.buildMapping(SampleDateMappingEntity.class, "mapping", "id", null); + Assert.assertEquals(EXPECTED_MAPPING, xContentBuilder.string()); + } } 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 f2c136636..fcf0df6ea 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 @@ -15,20 +15,21 @@ */ package org.springframework.data.elasticsearch.core.convert; +import java.util.Calendar; +import java.util.TimeZone; + import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDateTime; import org.junit.Assert; import org.junit.Test; -import java.util.Calendar; -import java.util.TimeZone; - /** * @author Rizwan Idrees * @author Mohsin Husen */ public class DateTimeConvertersTests { + @Test public void testJodaDateTimeConverterWithNullValue() { Assert.assertNull(DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(null)); 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 2348ce930..88dd15ccc 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,14 +15,14 @@ */ package org.springframework.data.elasticsearch.core.convert; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + import org.junit.Test; import org.springframework.core.convert.ConversionService; import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext; import org.springframework.data.mapping.context.MappingContext; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -54,5 +54,4 @@ public class MappingElasticsearchConverterTests { // then assertThat(conversionService, is(notNullValue())); } - } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntity.java index 6d6c1df1d..1618587bf 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntity.java @@ -1,15 +1,17 @@ package org.springframework.data.elasticsearch.core.facet; -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.*; +import static org.springframework.data.elasticsearch.annotations.FieldIndex.*; +import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; +import static org.springframework.data.elasticsearch.annotations.FieldType.String; import java.util.ArrayList; import java.util.List; -import static org.springframework.data.elasticsearch.annotations.FieldIndex.analyzed; -import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed; -import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; -import static org.springframework.data.elasticsearch.annotations.FieldType.String; +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.MultiField; +import org.springframework.data.elasticsearch.annotations.NestedField; /** * Simple type to test facets @@ -17,70 +19,70 @@ import static org.springframework.data.elasticsearch.annotations.FieldType.Strin @Document(indexName = "articles", type = "article", shards = 1, replicas = 0, refreshInterval = "-1", indexStoreType = "memory") public class ArticleEntity { - @Id - private String id; + @Id + private String id; - private String title; + private String title; - @MultiField( - mainField = @Field(type = String, index = analyzed), - otherFields = { - @NestedField(dotSuffix = "untouched", type = String, store = true, index = not_analyzed), - @NestedField(dotSuffix = "sort", type = String, store = true, indexAnalyzer = "keyword") - } - ) - private List authors = new ArrayList(); + @MultiField( + mainField = @Field(type = String, index = analyzed), + otherFields = { + @NestedField(dotSuffix = "untouched", type = String, store = true, index = not_analyzed), + @NestedField(dotSuffix = "sort", type = String, store = true, indexAnalyzer = "keyword") + } + ) + private List authors = new ArrayList(); - @Field(type = Integer, store = true) - private List publishedYears = new ArrayList(); + @Field(type = Integer, store = true) + private List publishedYears = new ArrayList(); - private int score; + private int score; - private ArticleEntity(){ + private ArticleEntity() { - } + } - public ArticleEntity(String id) { - this.id = id; - } + public ArticleEntity(String id) { + this.id = id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getTitle() { - return title; - } + public String getTitle() { + return title; + } - public void setTitle(String title) { - this.title = title; - } + public void setTitle(String title) { + this.title = title; + } - public List getAuthors() { - return authors; - } + public List getAuthors() { + return authors; + } - public void setAuthors(List authors) { - this.authors = authors; - } + public void setAuthors(List authors) { + this.authors = authors; + } - public List getPublishedYears() { - return publishedYears; - } + public List getPublishedYears() { + return publishedYears; + } - public void setPublishedYears(List publishedYears) { - this.publishedYears = publishedYears; - } + public void setPublishedYears(List publishedYears) { + this.publishedYears = publishedYears; + } - public int getScore() { - return score; - } + public int getScore() { + return score; + } - public void setScore(int score) { - this.score = score; - } + public void setScore(int score) { + this.score = score; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntityBuilder.java index 4b55b7328..8bdc0717d 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntityBuilder.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/facet/ArticleEntityBuilder.java @@ -7,41 +7,40 @@ import org.springframework.data.elasticsearch.core.query.IndexQuery; */ public class ArticleEntityBuilder { - private ArticleEntity result; + private ArticleEntity result; - public ArticleEntityBuilder(String id) { - result = new ArticleEntity(id); - } + public ArticleEntityBuilder(String id) { + result = new ArticleEntity(id); + } - public ArticleEntityBuilder title(String title) { - result.setTitle(title); - return this; - } + public ArticleEntityBuilder title(String title) { + result.setTitle(title); + return this; + } - public ArticleEntityBuilder addAuthor(String author) { - result.getAuthors().add(author); - return this; - } + public ArticleEntityBuilder addAuthor(String author) { + result.getAuthors().add(author); + return this; + } - public ArticleEntityBuilder addPublishedYear(Integer year) { - result.getPublishedYears().add(year); - return this; - } + public ArticleEntityBuilder addPublishedYear(Integer year) { + result.getPublishedYears().add(year); + return this; + } - public ArticleEntityBuilder score(int score) { - result.setScore(score); - return this; - } + public ArticleEntityBuilder score(int score) { + result.setScore(score); + return this; + } - public ArticleEntity build() { - return result; - } - - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } + public ArticleEntity build() { + return result; + } + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateFacetTests.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateFacetTests.java index 52a757992..b7432c93e 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateFacetTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateFacetTests.java @@ -15,6 +15,10 @@ */ package org.springframework.data.elasticsearch.core.facet; +import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.search.facet.FacetBuilders; import org.junit.Before; @@ -31,10 +35,6 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -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 @@ -45,487 +45,477 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateFacetTests { - public static final String RIZWAN_IDREES = "Rizwan Idrees"; - public static final String MOHSIN_HUSEN = "Mohsin Husen"; - public static final String JONATHAN_YAN = "Jonathan Yan"; - public static final String ARTUR_KONCZAK = "Artur Konczak"; - public static final int YEAR_2002 = 2002; - public static final int YEAR_2001 = 2001; - public static final int YEAR_2000 = 2000; - public static final String PUBLISHED_YEARS = "publishedYears"; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; - - @Before - public void before() { - elasticsearchTemplate.deleteIndex(ArticleEntity.class); - elasticsearchTemplate.createIndex(ArticleEntity.class); - elasticsearchTemplate.putMapping(ArticleEntity.class); - elasticsearchTemplate.refresh(ArticleEntity.class, true); - - IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex(); - IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex(); - IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex(); - IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex(); - - elasticsearchTemplate.index(article1); - elasticsearchTemplate.index(article2); - elasticsearchTemplate.index(article3); - elasticsearchTemplate.index(article4); - elasticsearchTemplate.refresh(ArticleEntity.class, true); - } - - @Test - public void shouldReturnFacetedAuthorsForGivenQueryWithDefaultOrder() { - - // given - String facetName = "fauthors"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").build()).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - TermResult facet = (TermResult) result.getFacet(facetName); - Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(RIZWAN_IDREES)); - assertThat(term.getCount(), is(4)); - - term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(3)); - - term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(2)); - - term = facet.getTerms().get(3); - assertThat(term.getTerm(), is(JONATHAN_YAN)); - assertThat(term.getCount(), is(1)); - } - - @Test - public void shouldReturnFacetedAuthorsForGivenFilteredQuery() { - - // given - String facetName = "fauthors"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) - .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").build()).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(3))); - - TermResult facet = (TermResult) result.getFacet(facetName); - Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(RIZWAN_IDREES)); - assertThat(term.getCount(), is(3)); - - term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(2)); - - term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(1)); - } - - @Test - public void shouldExcludeTermsFromFacetedAuthorsForGivenQuery() { - // given - String facetName = "fauthors"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) - .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").excludeTerms(RIZWAN_IDREES, ARTUR_KONCZAK).build()).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(3))); - - TermResult facet = (TermResult) result.getFacet(facetName); - - assertThat(facet.getTerms().size(), is(1)); - - Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(1)); - - } - - @Test - public void shouldReturnFacetedAuthorsForGivenQueryOrderedByTerm() { - - // given - String facetName = "fauthors"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").ascTerm().build()).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - TermResult facet = (TermResult) result.getFacet(facetName); - Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(3)); - - term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(JONATHAN_YAN)); - assertThat(term.getCount(), is(1)); - - term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(2)); - - term = facet.getTerms().get(3); - assertThat(term.getTerm(), is(RIZWAN_IDREES)); - assertThat(term.getCount(), is(4)); - - } - - @Test - public void shouldReturnFacetedAuthorsForGivenQueryOrderedByCountAsc() { - - // given - String facetName = "fauthors"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").ascCount().build()).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - TermResult facet = (TermResult) result.getFacet(facetName); - Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(JONATHAN_YAN)); - assertThat(term.getCount(), is(1)); - - term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(2)); - - term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(3)); - - term = facet.getTerms().get(3); - assertThat(term.getTerm(), is(RIZWAN_IDREES)); - assertThat(term.getCount(), is(4)); - } - - @Test - public void shouldReturnFacetedYearsForGivenQuery() { - - // given - String facetName = "fyears"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(facetName).fields("publishedYears").descCount().build()).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - TermResult facet = (TermResult) result.getFacet(facetName); - assertThat(facet.getTerms().size(), is(equalTo(3))); - - - Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(Integer.toString(YEAR_2000))); - assertThat(term.getCount(), is(3)); - - term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(Integer.toString(YEAR_2001))); - assertThat(term.getCount(), is(2)); - - term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(Integer.toString(YEAR_2002))); - assertThat(term.getCount(), is(1)); - } - - - @Test - public void shouldReturnSingleFacetOverYearsAndAuthorsForGivenQuery() { - - // given - String facetName = "fyears"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(facetName).fields("publishedYears", "authors.untouched").ascTerm().build()).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - TermResult facet = (TermResult) result.getFacet(facetName); - assertThat(facet.getTerms().size(), is(equalTo(7))); - - - Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(Integer.toString(YEAR_2000))); - assertThat(term.getCount(), is(3)); - - term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(Integer.toString(YEAR_2001))); - assertThat(term.getCount(), is(2)); - - term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(Integer.toString(YEAR_2002))); - assertThat(term.getCount(), is(1)); - - term = facet.getTerms().get(3); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(3)); - - term = facet.getTerms().get(4); - assertThat(term.getTerm(), is(JONATHAN_YAN)); - assertThat(term.getCount(), is(1)); - - term = facet.getTerms().get(5); - assertThat(term.getTerm(), is(MOHSIN_HUSEN)); - assertThat(term.getCount(), is(2)); - - term = facet.getTerms().get(6); - assertThat(term.getTerm(), is(RIZWAN_IDREES)); - assertThat(term.getCount(), is(4)); - - } - - @Test - public void shouldReturnFacetedYearsAndFacetedAuthorsForGivenQuery() { - - // given - String numberFacetName = "fAuthors"; - String stringFacetName = "fyears"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new TermFacetRequestBuilder(numberFacetName).fields("publishedYears").ascTerm().build()) - .withFacet(new TermFacetRequestBuilder(stringFacetName).fields("authors.untouched").ascTerm().build()) - .build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - TermResult numberFacet = (TermResult) result.getFacet(numberFacetName); - assertThat(numberFacet.getTerms().size(), is(equalTo(3))); - - Term numberTerm = numberFacet.getTerms().get(0); - assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2000))); - assertThat(numberTerm.getCount(), is(3)); - - numberTerm = numberFacet.getTerms().get(1); - assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2001))); - assertThat(numberTerm.getCount(), is(2)); - - numberTerm = numberFacet.getTerms().get(2); - assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2002))); - assertThat(numberTerm.getCount(), is(1)); - - - TermResult stringFacet = (TermResult) result.getFacet(stringFacetName); - Term stringTerm = stringFacet.getTerms().get(0); - assertThat(stringTerm.getTerm(), is(ARTUR_KONCZAK)); - assertThat(stringTerm.getCount(), is(3)); - - stringTerm = stringFacet.getTerms().get(1); - assertThat(stringTerm.getTerm(), is(JONATHAN_YAN)); - assertThat(stringTerm.getCount(), is(1)); - - stringTerm = stringFacet.getTerms().get(2); - assertThat(stringTerm.getTerm(), is(MOHSIN_HUSEN)); - assertThat(stringTerm.getCount(), is(2)); - - stringTerm = stringFacet.getTerms().get(3); - assertThat(stringTerm.getTerm(), is(RIZWAN_IDREES)); - assertThat(stringTerm.getCount(), is(4)); - } - - - @Test - public void shouldReturnFacetedYearsForNativeFacet() { - - // given - String facetName = "fyears"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new NativeFacetRequest(FacetBuilders.termsFacet(facetName).field("publishedYears"))).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - TermResult facet = (TermResult) result.getFacet(facetName); - assertThat(facet.getTerms().size(), is(equalTo(3))); - - - Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(Integer.toString(YEAR_2000))); - assertThat(term.getCount(), is(3)); - - term = facet.getTerms().get(1); - assertThat(term.getTerm(), is(Integer.toString(YEAR_2001))); - assertThat(term.getCount(), is(2)); - - term = facet.getTerms().get(2); - assertThat(term.getTerm(), is(Integer.toString(YEAR_2002))); - assertThat(term.getCount(), is(1)); - } - - @Test - public void shouldFilterResultByRegexForGivenQuery() { - // given - String facetName = "regex_authors"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) - .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").regex("Art.*").build()).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(3))); - - TermResult facet = (TermResult) result.getFacet(facetName); - - assertThat(facet.getTerms().size(), is(1)); - - Term term = facet.getTerms().get(0); - assertThat(term.getTerm(), is(ARTUR_KONCZAK)); - assertThat(term.getCount(), is(2)); - - } - - @Test - public void shouldReturnAllTermsForGivenQuery() { - // given - String facetName = "all_authors"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) - .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").allTerms().build()).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(3))); - - TermResult facet = (TermResult) result.getFacet(facetName); - - assertThat(facet.getTerms().size(), is(4)); - } - - - @Test - public void shouldReturnRangeFacetForGivenQuery() { - // given - String facetName = "rangeYears"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet( - new RangeFacetRequestBuilder(facetName).field(PUBLISHED_YEARS) - .to(YEAR_2000).range(YEAR_2000, YEAR_2002).from(YEAR_2002).build() - ).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - RangeResult facet = (RangeResult) result.getFacet(facetName); - assertThat(facet.getRanges().size(), is(equalTo(3))); - - - Range range = facet.getRanges().get(0); - assertThat(range.getFrom(), nullValue()); - assertThat(range.getTo(), is((double) YEAR_2000)); - assertThat(range.getCount(), is(0L)); - assertThat(range.getTotal(), is(0.0)); - - range = facet.getRanges().get(1); - assertThat(range.getFrom(), is((double) YEAR_2000)); - assertThat(range.getTo(), is((double) YEAR_2002)); - assertThat(range.getCount(), is(3L)); - assertThat(range.getTotal(), is(6000.0)); - - range = facet.getRanges().get(2); - assertThat(range.getFrom(), is((double) YEAR_2002)); - assertThat(range.getTo(), nullValue()); - assertThat(range.getCount(), is(1L)); - assertThat(range.getTotal(), is(2002.0)); - } - - @Test - public void shouldReturnKeyValueRangeFacetForGivenQuery() { - // given - String facetName = "rangeScoreOverYears"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet( - new RangeFacetRequestBuilder(facetName).fields(PUBLISHED_YEARS, "score") - .to(YEAR_2000).range(YEAR_2000, YEAR_2002).from(YEAR_2002).build() - ).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - RangeResult facet = (RangeResult) result.getFacet(facetName); - assertThat(facet.getRanges().size(), is(equalTo(3))); - - - Range range = facet.getRanges().get(0); - assertThat(range.getFrom(), nullValue()); - assertThat(range.getTo(), is((double) YEAR_2000)); - assertThat(range.getCount(), is(0L)); - assertThat(range.getTotal(), is(0.0)); - - range = facet.getRanges().get(1); - assertThat(range.getFrom(), is((double) YEAR_2000)); - assertThat(range.getTo(), is((double) YEAR_2002)); - assertThat(range.getCount(), is(3L)); - assertThat(range.getTotal(), is(90.0)); - - range = facet.getRanges().get(2); - assertThat(range.getFrom(), is((double) YEAR_2002)); - assertThat(range.getTo(), nullValue()); - assertThat(range.getCount(), is(1L)); - assertThat(range.getTotal(), is(40.0)); - } - - @Test - public void shouldReturnStatisticalFacetForGivenQuery() { - // given - String facetName = "statPublishedYear"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new StatisticalFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).build() - ).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - StatisticalResult facet = (StatisticalResult) result.getFacet(facetName); - assertThat(facet.getCount(), is(equalTo(6L))); - assertThat(facet.getMax(), is(equalTo(2002.0))); - assertThat(facet.getMin(), is(equalTo(2000.0))); - } - - @Test - public void shouldReturnHistogramFacetForGivenQuery() { - // given - String facetName = "numberPublicationPerYear"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new HistogramFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).interval(1).build() - ).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); - - HistogramResult facet = (HistogramResult) result.getFacet(facetName); - assertThat(facet.getIntervalUnit().size(), is(equalTo(3))); - - IntervalUnit unit = facet.getIntervalUnit().get(0); - assertThat(unit.getKey(), is(Long.valueOf(YEAR_2000))); - assertThat(unit.getCount(), is(3L)); - - unit = facet.getIntervalUnit().get(1); - assertThat(unit.getKey(), is(Long.valueOf(YEAR_2001))); - assertThat(unit.getCount(), is(2L)); - - unit = facet.getIntervalUnit().get(2); - assertThat(unit.getKey(), is(Long.valueOf(YEAR_2002))); - assertThat(unit.getCount(), is(1L)); - } + public static final String RIZWAN_IDREES = "Rizwan Idrees"; + public static final String MOHSIN_HUSEN = "Mohsin Husen"; + public static final String JONATHAN_YAN = "Jonathan Yan"; + public static final String ARTUR_KONCZAK = "Artur Konczak"; + public static final int YEAR_2002 = 2002; + public static final int YEAR_2001 = 2001; + public static final int YEAR_2000 = 2000; + public static final String PUBLISHED_YEARS = "publishedYears"; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; + + @Before + public void before() { + elasticsearchTemplate.deleteIndex(ArticleEntity.class); + elasticsearchTemplate.createIndex(ArticleEntity.class); + elasticsearchTemplate.putMapping(ArticleEntity.class); + elasticsearchTemplate.refresh(ArticleEntity.class, true); + + IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex(); + IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex(); + IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex(); + IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex(); + + elasticsearchTemplate.index(article1); + elasticsearchTemplate.index(article2); + elasticsearchTemplate.index(article3); + elasticsearchTemplate.index(article4); + elasticsearchTemplate.refresh(ArticleEntity.class, true); + } + + @Test + public void shouldReturnFacetedAuthorsForGivenQueryWithDefaultOrder() { + + // given + String facetName = "fauthors"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").build()).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + TermResult facet = (TermResult) result.getFacet(facetName); + Term term = facet.getTerms().get(0); + assertThat(term.getTerm(), is(RIZWAN_IDREES)); + assertThat(term.getCount(), is(4)); + + term = facet.getTerms().get(1); + assertThat(term.getTerm(), is(ARTUR_KONCZAK)); + assertThat(term.getCount(), is(3)); + + term = facet.getTerms().get(2); + assertThat(term.getTerm(), is(MOHSIN_HUSEN)); + assertThat(term.getCount(), is(2)); + + term = facet.getTerms().get(3); + assertThat(term.getTerm(), is(JONATHAN_YAN)); + assertThat(term.getCount(), is(1)); + } + + @Test + public void shouldReturnFacetedAuthorsForGivenFilteredQuery() { + + // given + String facetName = "fauthors"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) + .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").build()).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(3))); + + TermResult facet = (TermResult) result.getFacet(facetName); + Term term = facet.getTerms().get(0); + assertThat(term.getTerm(), is(RIZWAN_IDREES)); + assertThat(term.getCount(), is(3)); + + term = facet.getTerms().get(1); + assertThat(term.getTerm(), is(ARTUR_KONCZAK)); + assertThat(term.getCount(), is(2)); + + term = facet.getTerms().get(2); + assertThat(term.getTerm(), is(MOHSIN_HUSEN)); + assertThat(term.getCount(), is(1)); + } + + @Test + public void shouldExcludeTermsFromFacetedAuthorsForGivenQuery() { + // given + String facetName = "fauthors"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) + .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").excludeTerms(RIZWAN_IDREES, ARTUR_KONCZAK).build()).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(3))); + + TermResult facet = (TermResult) result.getFacet(facetName); + + assertThat(facet.getTerms().size(), is(1)); + + Term term = facet.getTerms().get(0); + assertThat(term.getTerm(), is(MOHSIN_HUSEN)); + assertThat(term.getCount(), is(1)); + } + + @Test + public void shouldReturnFacetedAuthorsForGivenQueryOrderedByTerm() { + + // given + String facetName = "fauthors"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").ascTerm().build()).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + TermResult facet = (TermResult) result.getFacet(facetName); + Term term = facet.getTerms().get(0); + assertThat(term.getTerm(), is(ARTUR_KONCZAK)); + assertThat(term.getCount(), is(3)); + + term = facet.getTerms().get(1); + assertThat(term.getTerm(), is(JONATHAN_YAN)); + assertThat(term.getCount(), is(1)); + + term = facet.getTerms().get(2); + assertThat(term.getTerm(), is(MOHSIN_HUSEN)); + assertThat(term.getCount(), is(2)); + + term = facet.getTerms().get(3); + assertThat(term.getTerm(), is(RIZWAN_IDREES)); + assertThat(term.getCount(), is(4)); + } + + @Test + public void shouldReturnFacetedAuthorsForGivenQueryOrderedByCountAsc() { + + // given + String facetName = "fauthors"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").ascCount().build()).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + TermResult facet = (TermResult) result.getFacet(facetName); + Term term = facet.getTerms().get(0); + assertThat(term.getTerm(), is(JONATHAN_YAN)); + assertThat(term.getCount(), is(1)); + + term = facet.getTerms().get(1); + assertThat(term.getTerm(), is(MOHSIN_HUSEN)); + assertThat(term.getCount(), is(2)); + + term = facet.getTerms().get(2); + assertThat(term.getTerm(), is(ARTUR_KONCZAK)); + assertThat(term.getCount(), is(3)); + + term = facet.getTerms().get(3); + assertThat(term.getTerm(), is(RIZWAN_IDREES)); + assertThat(term.getCount(), is(4)); + } + + @Test + public void shouldReturnFacetedYearsForGivenQuery() { + + // given + String facetName = "fyears"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new TermFacetRequestBuilder(facetName).fields("publishedYears").descCount().build()).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + TermResult facet = (TermResult) result.getFacet(facetName); + assertThat(facet.getTerms().size(), is(equalTo(3))); + + Term term = facet.getTerms().get(0); + assertThat(term.getTerm(), is(Integer.toString(YEAR_2000))); + assertThat(term.getCount(), is(3)); + + term = facet.getTerms().get(1); + assertThat(term.getTerm(), is(Integer.toString(YEAR_2001))); + assertThat(term.getCount(), is(2)); + + term = facet.getTerms().get(2); + assertThat(term.getTerm(), is(Integer.toString(YEAR_2002))); + assertThat(term.getCount(), is(1)); + } + + + @Test + public void shouldReturnSingleFacetOverYearsAndAuthorsForGivenQuery() { + + // given + String facetName = "fyears"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new TermFacetRequestBuilder(facetName).fields("publishedYears", "authors.untouched").ascTerm().build()).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + TermResult facet = (TermResult) result.getFacet(facetName); + assertThat(facet.getTerms().size(), is(equalTo(7))); + + Term term = facet.getTerms().get(0); + assertThat(term.getTerm(), is(Integer.toString(YEAR_2000))); + assertThat(term.getCount(), is(3)); + + term = facet.getTerms().get(1); + assertThat(term.getTerm(), is(Integer.toString(YEAR_2001))); + assertThat(term.getCount(), is(2)); + + term = facet.getTerms().get(2); + assertThat(term.getTerm(), is(Integer.toString(YEAR_2002))); + assertThat(term.getCount(), is(1)); + + term = facet.getTerms().get(3); + assertThat(term.getTerm(), is(ARTUR_KONCZAK)); + assertThat(term.getCount(), is(3)); + + term = facet.getTerms().get(4); + assertThat(term.getTerm(), is(JONATHAN_YAN)); + assertThat(term.getCount(), is(1)); + + term = facet.getTerms().get(5); + assertThat(term.getTerm(), is(MOHSIN_HUSEN)); + assertThat(term.getCount(), is(2)); + + term = facet.getTerms().get(6); + assertThat(term.getTerm(), is(RIZWAN_IDREES)); + assertThat(term.getCount(), is(4)); + } + + @Test + public void shouldReturnFacetedYearsAndFacetedAuthorsForGivenQuery() { + + // given + String numberFacetName = "fAuthors"; + String stringFacetName = "fyears"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new TermFacetRequestBuilder(numberFacetName).fields("publishedYears").ascTerm().build()) + .withFacet(new TermFacetRequestBuilder(stringFacetName).fields("authors.untouched").ascTerm().build()) + .build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + TermResult numberFacet = (TermResult) result.getFacet(numberFacetName); + assertThat(numberFacet.getTerms().size(), is(equalTo(3))); + + Term numberTerm = numberFacet.getTerms().get(0); + assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2000))); + assertThat(numberTerm.getCount(), is(3)); + + numberTerm = numberFacet.getTerms().get(1); + assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2001))); + assertThat(numberTerm.getCount(), is(2)); + + numberTerm = numberFacet.getTerms().get(2); + assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2002))); + assertThat(numberTerm.getCount(), is(1)); + + TermResult stringFacet = (TermResult) result.getFacet(stringFacetName); + Term stringTerm = stringFacet.getTerms().get(0); + assertThat(stringTerm.getTerm(), is(ARTUR_KONCZAK)); + assertThat(stringTerm.getCount(), is(3)); + + stringTerm = stringFacet.getTerms().get(1); + assertThat(stringTerm.getTerm(), is(JONATHAN_YAN)); + assertThat(stringTerm.getCount(), is(1)); + + stringTerm = stringFacet.getTerms().get(2); + assertThat(stringTerm.getTerm(), is(MOHSIN_HUSEN)); + assertThat(stringTerm.getCount(), is(2)); + + stringTerm = stringFacet.getTerms().get(3); + assertThat(stringTerm.getTerm(), is(RIZWAN_IDREES)); + assertThat(stringTerm.getCount(), is(4)); + } + + + @Test + public void shouldReturnFacetedYearsForNativeFacet() { + + // given + String facetName = "fyears"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new NativeFacetRequest(FacetBuilders.termsFacet(facetName).field("publishedYears"))).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + TermResult facet = (TermResult) result.getFacet(facetName); + assertThat(facet.getTerms().size(), is(equalTo(3))); + + Term term = facet.getTerms().get(0); + assertThat(term.getTerm(), is(Integer.toString(YEAR_2000))); + assertThat(term.getCount(), is(3)); + + term = facet.getTerms().get(1); + assertThat(term.getTerm(), is(Integer.toString(YEAR_2001))); + assertThat(term.getCount(), is(2)); + + term = facet.getTerms().get(2); + assertThat(term.getTerm(), is(Integer.toString(YEAR_2002))); + assertThat(term.getCount(), is(1)); + } + + @Test + public void shouldFilterResultByRegexForGivenQuery() { + // given + String facetName = "regex_authors"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) + .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").regex("Art.*").build()).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(3))); + + TermResult facet = (TermResult) result.getFacet(facetName); + + assertThat(facet.getTerms().size(), is(1)); + + Term term = facet.getTerms().get(0); + assertThat(term.getTerm(), is(ARTUR_KONCZAK)); + assertThat(term.getCount(), is(2)); + } + + @Test + public void shouldReturnAllTermsForGivenQuery() { + // given + String facetName = "all_authors"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) + .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").allTerms().build()).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(3))); + + TermResult facet = (TermResult) result.getFacet(facetName); + + assertThat(facet.getTerms().size(), is(4)); + } + + + @Test + public void shouldReturnRangeFacetForGivenQuery() { + // given + String facetName = "rangeYears"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet( + new RangeFacetRequestBuilder(facetName).field(PUBLISHED_YEARS) + .to(YEAR_2000).range(YEAR_2000, YEAR_2002).from(YEAR_2002).build() + ).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + RangeResult facet = (RangeResult) result.getFacet(facetName); + assertThat(facet.getRanges().size(), is(equalTo(3))); + + Range range = facet.getRanges().get(0); + assertThat(range.getFrom(), nullValue()); + assertThat(range.getTo(), is((double) YEAR_2000)); + assertThat(range.getCount(), is(0L)); + assertThat(range.getTotal(), is(0.0)); + + range = facet.getRanges().get(1); + assertThat(range.getFrom(), is((double) YEAR_2000)); + assertThat(range.getTo(), is((double) YEAR_2002)); + assertThat(range.getCount(), is(3L)); + assertThat(range.getTotal(), is(6000.0)); + + range = facet.getRanges().get(2); + assertThat(range.getFrom(), is((double) YEAR_2002)); + assertThat(range.getTo(), nullValue()); + assertThat(range.getCount(), is(1L)); + assertThat(range.getTotal(), is(2002.0)); + } + + @Test + public void shouldReturnKeyValueRangeFacetForGivenQuery() { + // given + String facetName = "rangeScoreOverYears"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet( + new RangeFacetRequestBuilder(facetName).fields(PUBLISHED_YEARS, "score") + .to(YEAR_2000).range(YEAR_2000, YEAR_2002).from(YEAR_2002).build() + ).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + RangeResult facet = (RangeResult) result.getFacet(facetName); + assertThat(facet.getRanges().size(), is(equalTo(3))); + + Range range = facet.getRanges().get(0); + assertThat(range.getFrom(), nullValue()); + assertThat(range.getTo(), is((double) YEAR_2000)); + assertThat(range.getCount(), is(0L)); + assertThat(range.getTotal(), is(0.0)); + + range = facet.getRanges().get(1); + assertThat(range.getFrom(), is((double) YEAR_2000)); + assertThat(range.getTo(), is((double) YEAR_2002)); + assertThat(range.getCount(), is(3L)); + assertThat(range.getTotal(), is(90.0)); + + range = facet.getRanges().get(2); + assertThat(range.getFrom(), is((double) YEAR_2002)); + assertThat(range.getTo(), nullValue()); + assertThat(range.getCount(), is(1L)); + assertThat(range.getTotal(), is(40.0)); + } + + @Test + public void shouldReturnStatisticalFacetForGivenQuery() { + // given + String facetName = "statPublishedYear"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new StatisticalFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).build() + ).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + StatisticalResult facet = (StatisticalResult) result.getFacet(facetName); + assertThat(facet.getCount(), is(equalTo(6L))); + assertThat(facet.getMax(), is(equalTo(2002.0))); + assertThat(facet.getMin(), is(equalTo(2000.0))); + } + + @Test + public void shouldReturnHistogramFacetForGivenQuery() { + // given + String facetName = "numberPublicationPerYear"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new HistogramFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).interval(1).build() + ).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); + + HistogramResult facet = (HistogramResult) result.getFacet(facetName); + assertThat(facet.getIntervalUnit().size(), is(equalTo(3))); + + IntervalUnit unit = facet.getIntervalUnit().get(0); + assertThat(unit.getKey(), is(Long.valueOf(YEAR_2000))); + assertThat(unit.getCount(), is(3L)); + + unit = facet.getIntervalUnit().get(1); + assertThat(unit.getKey(), is(Long.valueOf(YEAR_2001))); + assertThat(unit.getCount(), is(2L)); + + unit = facet.getIntervalUnit().get(2); + assertThat(unit.getKey(), is(Long.valueOf(YEAR_2002))); + assertThat(unit.getCount(), is(1L)); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateHistogramFacetTests.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateHistogramFacetTests.java index afd09a333..289c7fe5f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateHistogramFacetTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/facet/ElasticsearchTemplateHistogramFacetTests.java @@ -15,6 +15,14 @@ */ package org.springframework.data.elasticsearch.core.facet; +import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.concurrent.TimeUnit; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -22,21 +30,14 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.FacetedPage; import org.springframework.data.elasticsearch.core.facet.request.HistogramFacetRequestBuilder; -import org.springframework.data.elasticsearch.core.facet.result.*; +import org.springframework.data.elasticsearch.core.facet.result.HistogramResult; +import org.springframework.data.elasticsearch.core.facet.result.IntervalUnit; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.concurrent.TimeUnit; - -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 @@ -47,93 +48,92 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateHistogramFacetTests { - public static final long SEQUECE_CODE_INSERT = 1; - public static final long SEQUECE_CODE_UPDATE = 2; - public static final long SEQUECE_CODE_DELETE = 3; - public static final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - public static final String DATE_18 = "2013-10-18 18:01"; - public static final String DATE_17 = "2013-10-18 17:01"; - public static final String DATE_16 = "2013-10-18 16:01"; + public static final long SEQUECE_CODE_INSERT = 1; + public static final long SEQUECE_CODE_UPDATE = 2; + public static final long SEQUECE_CODE_DELETE = 3; + public static final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + public static final String DATE_18 = "2013-10-18 18:01"; + public static final String DATE_17 = "2013-10-18 17:01"; + public static final String DATE_16 = "2013-10-18 16:01"; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; - @Before - public void before() throws ParseException { - elasticsearchTemplate.deleteIndex(LogEntity.class); - elasticsearchTemplate.createIndex(LogEntity.class); - elasticsearchTemplate.putMapping(LogEntity.class); - elasticsearchTemplate.refresh(LogEntity.class, true); + @Before + public void before() throws ParseException { + elasticsearchTemplate.deleteIndex(LogEntity.class); + elasticsearchTemplate.createIndex(LogEntity.class); + elasticsearchTemplate.putMapping(LogEntity.class); + elasticsearchTemplate.refresh(LogEntity.class, true); - IndexQuery entry1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse(DATE_18)).code(SEQUECE_CODE_UPDATE).buildIndex(); - IndexQuery entry2 = new LogEntityBuilder("2").action("insert").date(dateFormatter.parse(DATE_17)).code(SEQUECE_CODE_INSERT).buildIndex(); - IndexQuery entry3 = new LogEntityBuilder("3").action("update").date(dateFormatter.parse(DATE_17)).code(SEQUECE_CODE_UPDATE).buildIndex(); - IndexQuery entry4 = new LogEntityBuilder("4").action("delete").date(dateFormatter.parse(DATE_16)).code(SEQUECE_CODE_DELETE).buildIndex(); + IndexQuery entry1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse(DATE_18)).code(SEQUECE_CODE_UPDATE).buildIndex(); + IndexQuery entry2 = new LogEntityBuilder("2").action("insert").date(dateFormatter.parse(DATE_17)).code(SEQUECE_CODE_INSERT).buildIndex(); + IndexQuery entry3 = new LogEntityBuilder("3").action("update").date(dateFormatter.parse(DATE_17)).code(SEQUECE_CODE_UPDATE).buildIndex(); + IndexQuery entry4 = new LogEntityBuilder("4").action("delete").date(dateFormatter.parse(DATE_16)).code(SEQUECE_CODE_DELETE).buildIndex(); + + elasticsearchTemplate.index(entry1); + elasticsearchTemplate.index(entry2); + elasticsearchTemplate.index(entry3); + elasticsearchTemplate.index(entry4); + + elasticsearchTemplate.refresh(LogEntity.class, true); + } - elasticsearchTemplate.index(entry1); - elasticsearchTemplate.index(entry2); - elasticsearchTemplate.index(entry3); - elasticsearchTemplate.index(entry4); + @Test + public void shouldReturnSimpleHistogramFacetForGivenQuery() { + // given + String facetName = "sequenceCodeFacet"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new HistogramFacetRequestBuilder(facetName).field("sequenceCode").interval(1).build() + ).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, LogEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); - elasticsearchTemplate.refresh(LogEntity.class, true); - } + HistogramResult facet = (HistogramResult) result.getFacet(facetName); + assertThat(facet.getIntervalUnit().size(), is(equalTo(3))); + IntervalUnit unit = facet.getIntervalUnit().get(0); + assertThat(unit.getKey(), is(SEQUECE_CODE_INSERT)); + assertThat(unit.getCount(), is(1L)); - @Test - public void shouldReturnSimpleHistogramFacetForGivenQuery() { - // given - String facetName = "sequenceCodeFacet"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new HistogramFacetRequestBuilder(facetName).field("sequenceCode").interval(1).build() - ).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, LogEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + unit = facet.getIntervalUnit().get(1); + assertThat(unit.getKey(), is(SEQUECE_CODE_UPDATE)); + assertThat(unit.getCount(), is(2L)); - HistogramResult facet = (HistogramResult) result.getFacet(facetName); - assertThat(facet.getIntervalUnit().size(), is(equalTo(3))); + unit = facet.getIntervalUnit().get(2); + assertThat(unit.getKey(), is(SEQUECE_CODE_DELETE)); + assertThat(unit.getCount(), is(1L)); + } - IntervalUnit unit = facet.getIntervalUnit().get(0); - assertThat(unit.getKey(), is(SEQUECE_CODE_INSERT)); - assertThat(unit.getCount(), is(1L)); + @Test + public void shouldReturnDateHistogramFacetForGivenQuery() throws ParseException { + // given + String facetName = "sequenceCodeFacet"; + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) + .withFacet(new HistogramFacetRequestBuilder(facetName).field("date").interval(1).timeUnit(TimeUnit.HOURS).build() + ).build(); + // when + FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, LogEntity.class); + // then + assertThat(result.getNumberOfElements(), is(equalTo(4))); - unit = facet.getIntervalUnit().get(1); - assertThat(unit.getKey(), is(SEQUECE_CODE_UPDATE)); - assertThat(unit.getCount(), is(2L)); + HistogramResult facet = (HistogramResult) result.getFacet(facetName); + assertThat(facet.getIntervalUnit().size(), is(equalTo(3))); - unit = facet.getIntervalUnit().get(2); - assertThat(unit.getKey(), is(SEQUECE_CODE_DELETE)); - assertThat(unit.getCount(), is(1L)); - } + IntervalUnit unit = facet.getIntervalUnit().get(0); + assertThat(unit.getKey(), is(dateFormatter.parse("2013-10-18 16:00").getTime())); + assertThat(unit.getCount(), is(1L)); - @Test - public void shouldReturnDateHistogramFacetForGivenQuery() throws ParseException { - // given - String facetName = "sequenceCodeFacet"; - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) - .withFacet(new HistogramFacetRequestBuilder(facetName).field("date").interval(1).timeUnit(TimeUnit.HOURS).build() - ).build(); - // when - FacetedPage result = elasticsearchTemplate.queryForPage(searchQuery, LogEntity.class); - // then - assertThat(result.getNumberOfElements(), is(equalTo(4))); + unit = facet.getIntervalUnit().get(1); + assertThat(unit.getKey(), is(dateFormatter.parse("2013-10-18 17:00").getTime())); + assertThat(unit.getCount(), is(2L)); - HistogramResult facet = (HistogramResult) result.getFacet(facetName); - assertThat(facet.getIntervalUnit().size(), is(equalTo(3))); - - IntervalUnit unit = facet.getIntervalUnit().get(0); - assertThat(unit.getKey(),is(dateFormatter.parse("2013-10-18 16:00").getTime())); - assertThat(unit.getCount(), is(1L)); - - unit = facet.getIntervalUnit().get(1); - assertThat(unit.getKey(),is(dateFormatter.parse("2013-10-18 17:00").getTime())); - assertThat(unit.getCount(), is(2L)); - - unit = facet.getIntervalUnit().get(2); - assertThat(unit.getKey(),is(dateFormatter.parse("2013-10-18 18:00").getTime())); - assertThat(unit.getCount(), is(1L)); - } + unit = facet.getIntervalUnit().get(2); + assertThat(unit.getKey(), is(dateFormatter.parse("2013-10-18 18:00").getTime())); + assertThat(unit.getCount(), is(1L)); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntity.java index 7be56b4a3..139b7c45a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntity.java @@ -1,14 +1,14 @@ package org.springframework.data.elasticsearch.core.facet; +import java.text.SimpleDateFormat; +import java.util.Date; + import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.DateFormat; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; -import java.text.SimpleDateFormat; -import java.util.Date; - /** * User: Artur Konczak * Date: 18/10/13 @@ -17,58 +17,58 @@ import java.util.Date; @Document(indexName = "logs", type = "log", shards = 1, replicas = 0, refreshInterval = "-1", indexStoreType = "memory") public class LogEntity { - private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); + private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm"); - @Id - private String id; + @Id + private String id; - private String action; + private String action; - private long sequenceCode; + private long sequenceCode; - @Field(type = FieldType.Date, format = DateFormat.basic_date_time) - private Date date; + @Field(type = FieldType.Date, format = DateFormat.basic_date_time) + private Date date; - private LogEntity() { - } + private LogEntity() { + } - public LogEntity(String id) { - this.id = id; - } + public LogEntity(String id) { + this.id = 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; + } - public String getAction() { - return action; - } + public String getAction() { + return action; + } - public String toString(){ - return new StringBuffer().append("{id:").append(id).append(",action:").append(action).append(",code:").append(sequenceCode).append(",date:").append(format.format(date)).append("}").toString(); - } + public String toString() { + return new StringBuffer().append("{id:").append(id).append(",action:").append(action).append(",code:").append(sequenceCode).append(",date:").append(format.format(date)).append("}").toString(); + } - public void setAction(String action) { - this.action = action; - } + public void setAction(String action) { + this.action = action; + } - public long getSequenceCode() { - return sequenceCode; - } + public long getSequenceCode() { + return sequenceCode; + } - public void setSequenceCode(long sequenceCode) { - this.sequenceCode = sequenceCode; - } + public void setSequenceCode(long sequenceCode) { + this.sequenceCode = sequenceCode; + } - public Date getDate() { - return date; - } + public Date getDate() { + return date; + } - public void setDate(Date date) { - this.date = date; - } + public void setDate(Date date) { + this.date = date; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntityBuilder.java index d1200ee39..4811fb499 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntityBuilder.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/facet/LogEntityBuilder.java @@ -1,9 +1,9 @@ package org.springframework.data.elasticsearch.core.facet; -import org.springframework.data.elasticsearch.core.query.IndexQuery; - import java.util.Date; +import org.springframework.data.elasticsearch.core.query.IndexQuery; + /** * User: Artur Konczak * Date: 18/10/13 @@ -11,36 +11,35 @@ import java.util.Date; */ public class LogEntityBuilder { - private LogEntity result; + private LogEntity result; - public LogEntityBuilder(String id) { - result = new LogEntity(id); - } + public LogEntityBuilder(String id) { + result = new LogEntity(id); + } - public LogEntityBuilder action(String action) { - result.setAction(action); - return this; - } + public LogEntityBuilder action(String action) { + result.setAction(action); + return this; + } - public LogEntityBuilder code(long sequenceCode) { - result.setSequenceCode(sequenceCode); - return this; - } + public LogEntityBuilder code(long sequenceCode) { + result.setSequenceCode(sequenceCode); + return this; + } - public LogEntityBuilder date(Date date) { - result.setDate(date); - return this; - } + public LogEntityBuilder date(Date date) { + result.setDate(date); + return this; + } - public LogEntity build() { - return result; - } - - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } + public LogEntity build() { + return result; + } + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerAnnotatedEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerAnnotatedEntity.java index fad86fbca..640963254 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerAnnotatedEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerAnnotatedEntity.java @@ -25,53 +25,53 @@ import org.springframework.data.elasticsearch.annotations.GeoPointField; @Document(indexName = "test-geo-index", type = "geo-annotation-point-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class AuthorMarkerAnnotatedEntity { - @Id - private String id; - private String name; + @Id + private String id; + private String name; - @GeoPointField - private String location; + @GeoPointField + private String location; - @GeoPointField - private double[] additionalLocation; + @GeoPointField + private double[] additionalLocation; - private AuthorMarkerAnnotatedEntity() { + private AuthorMarkerAnnotatedEntity() { - } + } - public AuthorMarkerAnnotatedEntity(String id) { - this.id = id; - } + public AuthorMarkerAnnotatedEntity(String id) { + this.id = 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; + } - 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 String getLocation() { - return location; - } + public String getLocation() { + return location; + } - public void setLocation(String location) { - this.location = location; - } + public void setLocation(String location) { + this.location = location; + } - public double[] getAdditionalLocation() { - return additionalLocation; - } + public double[] getAdditionalLocation() { + return additionalLocation; + } - public void setAdditionalLocation(double... additionalLocation) { - this.additionalLocation = additionalLocation; - } + public void setAdditionalLocation(double... additionalLocation) { + this.additionalLocation = additionalLocation; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerAnnotatedEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerAnnotatedEntityBuilder.java index 2912d88f5..26af154ac 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerAnnotatedEntityBuilder.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerAnnotatedEntityBuilder.java @@ -19,35 +19,35 @@ import org.springframework.data.elasticsearch.core.query.IndexQuery; public class AuthorMarkerAnnotatedEntityBuilder { - private AuthorMarkerAnnotatedEntity result; + private AuthorMarkerAnnotatedEntity result; - public AuthorMarkerAnnotatedEntityBuilder(String id) { - result = new AuthorMarkerAnnotatedEntity(id); - } + public AuthorMarkerAnnotatedEntityBuilder(String id) { + result = new AuthorMarkerAnnotatedEntity(id); + } - public AuthorMarkerAnnotatedEntityBuilder name(String name) { - result.setName(name); - return this; - } + public AuthorMarkerAnnotatedEntityBuilder name(String name) { + result.setName(name); + return this; + } - public AuthorMarkerAnnotatedEntityBuilder location(String location) { - result.setLocation(location); - return this; - } + public AuthorMarkerAnnotatedEntityBuilder location(String location) { + result.setLocation(location); + return this; + } - public AuthorMarkerAnnotatedEntityBuilder additionalLocation(double... location) { - result.setAdditionalLocation(location); - return this; - } + public AuthorMarkerAnnotatedEntityBuilder additionalLocation(double... location) { + result.setAdditionalLocation(location); + return this; + } - public AuthorMarkerAnnotatedEntity build() { - return result; - } + public AuthorMarkerAnnotatedEntity build() { + return result; + } - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntity.java b/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntity.java index 0ab35ac0d..cd22f897c 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntity.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntity.java @@ -25,40 +25,40 @@ import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "test-geo-index", type = "geo-class-point-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class AuthorMarkerEntity { - @Id - private String id; - private String name; + @Id + private String id; + private String name; - private GeoPoint location; + private GeoPoint location; - private AuthorMarkerEntity(){ - } + private AuthorMarkerEntity() { + } - public AuthorMarkerEntity(String id){ - this.id = id; - } + public AuthorMarkerEntity(String id) { + this.id = 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; + } - 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 GeoPoint getLocation() { - return location; - } + public GeoPoint getLocation() { + return location; + } - public void setLocation(GeoPoint location) { - this.location = location; - } + public void setLocation(GeoPoint location) { + this.location = location; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntityBuilder.java b/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntityBuilder.java index 637e1a79d..209e5e5a2 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntityBuilder.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/geo/AuthorMarkerEntityBuilder.java @@ -24,30 +24,30 @@ import org.springframework.data.elasticsearch.core.query.IndexQuery; public class AuthorMarkerEntityBuilder { - private AuthorMarkerEntity result; + private AuthorMarkerEntity result; - public AuthorMarkerEntityBuilder(String id) { - result = new AuthorMarkerEntity(id); - } + public AuthorMarkerEntityBuilder(String id) { + result = new AuthorMarkerEntity(id); + } - public AuthorMarkerEntityBuilder name(String name) { - result.setName(name); - return this; - } + public AuthorMarkerEntityBuilder name(String name) { + result.setName(name); + return this; + } - public AuthorMarkerEntityBuilder location(double latitude, double longitude) { - result.setLocation(new GeoPoint(latitude, longitude)); - return this; - } + public AuthorMarkerEntityBuilder location(double latitude, double longitude) { + result.setLocation(new GeoPoint(latitude, longitude)); + return this; + } - public AuthorMarkerEntity build() { - return result; - } + public AuthorMarkerEntity build() { + return result; + } - public IndexQuery buildIndex() { - IndexQuery indexQuery = new IndexQuery(); - indexQuery.setId(result.getId()); - indexQuery.setObject(result); - return indexQuery; - } + public IndexQuery buildIndex() { + IndexQuery indexQuery = new IndexQuery(); + indexQuery.setId(result.getId()); + indexQuery.setObject(result); + return indexQuery; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java b/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java index 5c881c0ba..d8e6fff4b 100644 --- a/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/core/geo/ElasticsearchTemplateGeoTests.java @@ -15,6 +15,13 @@ */ package org.springframework.data.elasticsearch.core.geo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + import org.elasticsearch.index.query.FilterBuilders; import org.junit.Before; import org.junit.Test; @@ -28,13 +35,6 @@ import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilde import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.util.ArrayList; -import java.util.List; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -45,190 +45,189 @@ import static org.junit.Assert.assertEquals; @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class ElasticsearchTemplateGeoTests { - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; - @Before - public void before() { + @Before + public void before() { - } + } - private void loadClassBaseEntities() { - elasticsearchTemplate.deleteIndex(AuthorMarkerEntity.class); - elasticsearchTemplate.createIndex(AuthorMarkerEntity.class); - elasticsearchTemplate.refresh(AuthorMarkerEntity.class, true); - elasticsearchTemplate.putMapping(AuthorMarkerEntity.class); + private void loadClassBaseEntities() { + elasticsearchTemplate.deleteIndex(AuthorMarkerEntity.class); + elasticsearchTemplate.createIndex(AuthorMarkerEntity.class); + elasticsearchTemplate.refresh(AuthorMarkerEntity.class, true); + elasticsearchTemplate.putMapping(AuthorMarkerEntity.class); - List indexQueries = new ArrayList(); - indexQueries.add(new AuthorMarkerEntityBuilder("1").name("Franck Marchand").location(45.7806d, 3.0875d).buildIndex()); - indexQueries.add(new AuthorMarkerEntityBuilder("2").name("Mohsin Husen").location(51.5171d, 0.1062d).buildIndex()); - indexQueries.add(new AuthorMarkerEntityBuilder("3").name("Rizwan Idrees").location(51.5171d, 0.1062d).buildIndex()); - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(AuthorMarkerEntity.class, true); - } + List indexQueries = new ArrayList(); + indexQueries.add(new AuthorMarkerEntityBuilder("1").name("Franck Marchand").location(45.7806d, 3.0875d).buildIndex()); + indexQueries.add(new AuthorMarkerEntityBuilder("2").name("Mohsin Husen").location(51.5171d, 0.1062d).buildIndex()); + indexQueries.add(new AuthorMarkerEntityBuilder("3").name("Rizwan Idrees").location(51.5171d, 0.1062d).buildIndex()); + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(AuthorMarkerEntity.class, true); + } - private void loadAnnotationBaseEntities() { - elasticsearchTemplate.deleteIndex(AuthorMarkerAnnotatedEntity.class); - elasticsearchTemplate.createIndex(AuthorMarkerAnnotatedEntity.class); - elasticsearchTemplate.refresh(AuthorMarkerAnnotatedEntity.class, true); - elasticsearchTemplate.putMapping(AuthorMarkerAnnotatedEntity.class); + private void loadAnnotationBaseEntities() { + elasticsearchTemplate.deleteIndex(AuthorMarkerAnnotatedEntity.class); + elasticsearchTemplate.createIndex(AuthorMarkerAnnotatedEntity.class); + elasticsearchTemplate.refresh(AuthorMarkerAnnotatedEntity.class, true); + elasticsearchTemplate.putMapping(AuthorMarkerAnnotatedEntity.class); - List indexQueries = new ArrayList(); - double[] latLonArray = {0.100000, 51.000000}; - String lonLatString = "51.000000, 0.100000"; - String geohash = "u1044k2bd6u"; - indexQueries.add(new AuthorMarkerAnnotatedEntityBuilder("2").name("Mohsin Husen").location(geohash.substring(0,5)).additionalLocation(latLonArray).buildIndex()); - indexQueries.add(new AuthorMarkerAnnotatedEntityBuilder("1").name("Artur Konczak").location(lonLatString).additionalLocation(latLonArray).buildIndex()); - indexQueries.add(new AuthorMarkerAnnotatedEntityBuilder("3").name("Rizwan Idrees").location(geohash).additionalLocation(latLonArray).buildIndex()); + List indexQueries = new ArrayList(); + double[] latLonArray = {0.100000, 51.000000}; + String lonLatString = "51.000000, 0.100000"; + String geohash = "u1044k2bd6u"; + indexQueries.add(new AuthorMarkerAnnotatedEntityBuilder("2").name("Mohsin Husen").location(geohash.substring(0, 5)).additionalLocation(latLonArray).buildIndex()); + indexQueries.add(new AuthorMarkerAnnotatedEntityBuilder("1").name("Artur Konczak").location(lonLatString).additionalLocation(latLonArray).buildIndex()); + indexQueries.add(new AuthorMarkerAnnotatedEntityBuilder("3").name("Rizwan Idrees").location(geohash).additionalLocation(latLonArray).buildIndex()); - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(AuthorMarkerEntity.class, true); - } + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(AuthorMarkerEntity.class, true); + } - @Test - public void shouldPutMappingForGivenEntityWithGeoLocation() throws Exception { - //given - Class entity = AuthorMarkerEntity.class; - elasticsearchTemplate.createIndex(entity); - //when - assertThat(elasticsearchTemplate.putMapping(entity), is(true)); - } + @Test + public void shouldPutMappingForGivenEntityWithGeoLocation() throws Exception { + //given + Class entity = AuthorMarkerEntity.class; + elasticsearchTemplate.createIndex(entity); + //when + assertThat(elasticsearchTemplate.putMapping(entity), is(true)); + } - @Test - public void shouldFindAuthorMarkersInRangeForGivenCriteriaQuery() { - //given - loadClassBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( - new Criteria("location").within(new GeoPoint(45.7806d, 3.0875d), "20km")); - //when - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerEntity.class); + @Test + public void shouldFindAuthorMarkersInRangeForGivenCriteriaQuery() { + //given + loadClassBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( + new Criteria("location").within(new GeoPoint(45.7806d, 3.0875d), "20km")); + //when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria.size(), is(1)); - assertEquals("Franck Marchand", geoAuthorsForGeoCriteria.get(0).getName()); - } + //then + assertThat(geoAuthorsForGeoCriteria.size(), is(1)); + assertEquals("Franck Marchand", geoAuthorsForGeoCriteria.get(0).getName()); + } - @Test - public void shouldFindSelectedAuthorMarkerInRangeForGivenCriteriaQuery() { - //given - loadClassBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery2 = new CriteriaQuery( - new Criteria("name").is("Mohsin Husen").and("location").within(new GeoPoint(51.5171d, 0.1062d), "20km")); - //when - List geoAuthorsForGeoCriteria2 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery2, AuthorMarkerEntity.class); + @Test + public void shouldFindSelectedAuthorMarkerInRangeForGivenCriteriaQuery() { + //given + loadClassBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery2 = new CriteriaQuery( + new Criteria("name").is("Mohsin Husen").and("location").within(new GeoPoint(51.5171d, 0.1062d), "20km")); + //when + List geoAuthorsForGeoCriteria2 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery2, AuthorMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria2.size(), is(1)); - assertEquals("Mohsin Husen", geoAuthorsForGeoCriteria2.get(0).getName()); - } + //then + assertThat(geoAuthorsForGeoCriteria2.size(), is(1)); + assertEquals("Mohsin Husen", geoAuthorsForGeoCriteria2.get(0).getName()); + } - @Test - public void shouldFindStringAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { - //given - loadAnnotationBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( - new Criteria("location").within(new GeoPoint(51.000000, 0.100000), "1km")); - //when - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerAnnotatedEntity.class); + @Test + public void shouldFindStringAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { + //given + loadAnnotationBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( + new Criteria("location").within(new GeoPoint(51.000000, 0.100000), "1km")); + //when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerAnnotatedEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria.size(), is(3)); - } + //then + assertThat(geoAuthorsForGeoCriteria.size(), is(3)); + } - @Test - public void shouldFindDoubleAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { - //given - loadAnnotationBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( - new Criteria("additionalLocation").within(new GeoPoint(51.001000, 0.10100), "1km")); - //when - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerAnnotatedEntity.class); + @Test + public void shouldFindDoubleAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { + //given + loadAnnotationBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( + new Criteria("additionalLocation").within(new GeoPoint(51.001000, 0.10100), "1km")); + //when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerAnnotatedEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria.size(), is(3)); - } + //then + assertThat(geoAuthorsForGeoCriteria.size(), is(3)); + } - @Test - public void shouldFindAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { - //given - loadAnnotationBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( - new Criteria("additionalLocation").within("51.001000, 0.10100", "1km")); - //when - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerAnnotatedEntity.class); + @Test + public void shouldFindAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() { + //given + loadAnnotationBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( + new Criteria("additionalLocation").within("51.001000, 0.10100", "1km")); + //when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerAnnotatedEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria.size(), is(3)); - } + //then + assertThat(geoAuthorsForGeoCriteria.size(), is(3)); + } - @Test - public void shouldFindAnnotatedGeoMarkersInRangeForGivenCriteriaQueryUsingGeohashLocation() { - //given - loadAnnotationBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( - new Criteria("additionalLocation").within("u1044", "1km")); - //when - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerAnnotatedEntity.class); + @Test + public void shouldFindAnnotatedGeoMarkersInRangeForGivenCriteriaQueryUsingGeohashLocation() { + //given + loadAnnotationBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery( + new Criteria("additionalLocation").within("u1044", "1km")); + //when + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerAnnotatedEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria.size(), is(3)); - } + //then + assertThat(geoAuthorsForGeoCriteria.size(), is(3)); + } - @Test - public void shouldFindAllMarkersForNativeSearchQuery() { - //Given - loadAnnotationBaseEntities(); - NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withFilter(FilterBuilders.geoBoundingBoxFilter("additionalLocation").topLeft("52, -1").bottomRight("50,1")); - //When - List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(queryBuilder.build(), AuthorMarkerAnnotatedEntity.class); - //Then - assertThat(geoAuthorsForGeoCriteria.size(), is(3)); - } + @Test + public void shouldFindAllMarkersForNativeSearchQuery() { + //Given + loadAnnotationBaseEntities(); + NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withFilter(FilterBuilders.geoBoundingBoxFilter("additionalLocation").topLeft("52, -1").bottomRight("50,1")); + //When + List geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(queryBuilder.build(), AuthorMarkerAnnotatedEntity.class); + //Then + assertThat(geoAuthorsForGeoCriteria.size(), is(3)); + } - @Test - public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoBox() { - //given - loadClassBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( - new Criteria("location").boundedBy( - new GeoBox(new GeoPoint(53.5171d, 0), - new GeoPoint(49.5171d, 0.2062d)))); - //when - List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); + @Test + public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoBox() { + //given + loadClassBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( + new Criteria("location").boundedBy( + new GeoBox(new GeoPoint(53.5171d, 0), + new GeoPoint(49.5171d, 0.2062d)))); + //when + List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria3.size(), is(2)); - assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees")))); - } + //then + assertThat(geoAuthorsForGeoCriteria3.size(), is(2)); + assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees")))); + } - @Test - public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingString() { - //given - loadClassBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( - new Criteria("location").boundedBy("53.5171d, 0", "49.5171d, 0.2062d")); - //when - List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); + @Test + public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingString() { + //given + loadClassBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( + new Criteria("location").boundedBy("53.5171d, 0", "49.5171d, 0.2062d")); + //when + List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); - //then - assertThat(geoAuthorsForGeoCriteria3.size(), is(2)); - assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees")))); - } + //then + assertThat(geoAuthorsForGeoCriteria3.size(), is(2)); + assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees")))); + } - @Test - public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoPoints() { - //given - loadClassBaseEntities(); - CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( - new Criteria("location").boundedBy( - new GeoPoint(53.5171d, 0), - new GeoPoint(49.5171d, 0.2062d))); - //when - List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); - - //then - assertThat(geoAuthorsForGeoCriteria3.size(), is(2)); - assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees")))); - } + @Test + public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoPoints() { + //given + loadClassBaseEntities(); + CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery( + new Criteria("location").boundedBy( + new GeoPoint(53.5171d, 0), + new GeoPoint(49.5171d, 0.2062d))); + //when + List geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class); + //then + assertThat(geoAuthorsForGeoCriteria3.size(), is(2)); + assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees")))); + } } 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 5124dc871..f0206d885 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 @@ -15,6 +15,9 @@ */ package org.springframework.data.elasticsearch.core.mapping; +import java.beans.IntrospectionException; +import java.beans.PropertyDescriptor; + import org.junit.Test; import org.springframework.data.annotation.Version; import org.springframework.data.mapping.model.MappingException; @@ -22,9 +25,6 @@ import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.util.ClassTypeInformation; import org.springframework.data.util.TypeInformation; -import java.beans.IntrospectionException; -import java.beans.PropertyDescriptor; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -37,8 +37,8 @@ public class SimpleElasticsearchPersistentEntityTests { TypeInformation typeInformation = ClassTypeInformation.from(EntityWithWrongVersionType.class); SimpleElasticsearchPersistentProperty persistentProperty = new SimpleElasticsearchPersistentProperty( EntityWithWrongVersionType.class.getDeclaredField("version"), new PropertyDescriptor("version", - EntityWithWrongVersionType.class), new SimpleElasticsearchPersistentEntity( - typeInformation), new SimpleTypeHolder()); + EntityWithWrongVersionType.class), new SimpleElasticsearchPersistentEntity( + typeInformation), new SimpleTypeHolder()); // when new SimpleElasticsearchPersistentEntity(typeInformation).addPersistentProperty(persistentProperty); @@ -51,13 +51,13 @@ public class SimpleElasticsearchPersistentEntityTests { TypeInformation typeInformation = ClassTypeInformation.from(EntityWithMultipleVersionField.class); SimpleElasticsearchPersistentProperty persistentProperty1 = new SimpleElasticsearchPersistentProperty( EntityWithMultipleVersionField.class.getDeclaredField("version1"), new PropertyDescriptor("version1", - EntityWithMultipleVersionField.class), + EntityWithMultipleVersionField.class), new SimpleElasticsearchPersistentEntity(typeInformation), new SimpleTypeHolder()); SimpleElasticsearchPersistentProperty persistentProperty2 = new SimpleElasticsearchPersistentProperty( EntityWithMultipleVersionField.class.getDeclaredField("version2"), new PropertyDescriptor("version2", - EntityWithMultipleVersionField.class), + EntityWithMultipleVersionField.class), new SimpleElasticsearchPersistentEntity(typeInformation), new SimpleTypeHolder()); @@ -69,6 +69,7 @@ public class SimpleElasticsearchPersistentEntityTests { } private class EntityWithWrongVersionType { + @Version private String version; @@ -104,5 +105,4 @@ public class SimpleElasticsearchPersistentEntityTests { 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 4502a0f14..3839bf19d 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 @@ -15,10 +15,18 @@ */ package org.springframework.data.elasticsearch.core.query; +import static org.apache.commons.lang.RandomStringUtils.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.elasticsearch.SampleEntity; import org.springframework.data.elasticsearch.SampleEntityBuilder; @@ -26,14 +34,6 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.List; - -import static org.apache.commons.lang.RandomStringUtils.randomNumeric; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -42,12 +42,12 @@ import static org.junit.Assert.*; @ContextConfiguration("classpath:elasticsearch-template-test.xml") public class CriteriaQueryTests { - @Resource + @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); + elasticsearchTemplate.deleteIndex(SampleEntity.class); elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.refresh(SampleEntity.class, true); } @@ -74,7 +74,7 @@ public class CriteriaQueryTests { assertThat(sampleEntity1, is(notNullValue())); } - @Ignore("DATAES-30") + @Ignore("DATAES-30") @Test public void shouldPerformOrOperation() { // given @@ -140,7 +140,7 @@ public class CriteriaQueryTests { assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); } - @Ignore("DATAES-30") + @Ignore("DATAES-30") @Test public void shouldPerformOrOperationWithinCriteria() { // given @@ -702,24 +702,24 @@ public class CriteriaQueryTests { assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); } - @Test - public void shouldReturnDocumentAboveMinimalScoreGivenCriteria() { - // given - List indexQueries = new ArrayList(); + @Test + public void shouldReturnDocumentAboveMinimalScoreGivenCriteria() { + // given + List indexQueries = new ArrayList(); - indexQueries.add(new SampleEntityBuilder("1").message("ab").buildIndex()); - indexQueries.add(new SampleEntityBuilder("2").message("bc").buildIndex()); - indexQueries.add(new SampleEntityBuilder("3").message("ac").buildIndex()); + indexQueries.add(new SampleEntityBuilder("1").message("ab").buildIndex()); + indexQueries.add(new SampleEntityBuilder("2").message("bc").buildIndex()); + indexQueries.add(new SampleEntityBuilder("3").message("ac").buildIndex()); - elasticsearchTemplate.bulkIndex(indexQueries); - elasticsearchTemplate.refresh(SampleEntity.class, true); + elasticsearchTemplate.bulkIndex(indexQueries); + elasticsearchTemplate.refresh(SampleEntity.class, true); - // when - CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("a").or(new Criteria("message").contains("b"))); - criteriaQuery.setMinScore(0.5F); - Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); - // then - assertThat(page.getTotalElements(),is(1L)); - assertThat(page.getContent().get(0).getMessage(), is("ab")); - } + // when + CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("a").or(new Criteria("message").contains("b"))); + criteriaQuery.setMinScore(0.5F); + Page page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); + // then + assertThat(page.getTotalElements(), is(1L)); + assertThat(page.getContent().get(0).getMessage(), is("ab")); + } } 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 1ae94bc99..3e1f947f8 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/CustomMethodRepositoryTests.java @@ -15,6 +15,13 @@ */ package org.springframework.data.elasticsearch.repositories; +import static org.apache.commons.lang.RandomStringUtils.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.Arrays; +import java.util.List; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,15 +34,6 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; -import java.util.Arrays; -import java.util.List; - -import static org.apache.commons.lang.RandomStringUtils.random; -import static org.apache.commons.lang.RandomStringUtils.randomNumeric; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertThat; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -44,7 +42,7 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:custom-method-repository-test.xml") public class CustomMethodRepositoryTests { - @Resource + @Autowired private SampleCustomMethodRepository repository; @Autowired @@ -52,7 +50,7 @@ public class CustomMethodRepositoryTests { @Before public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); + elasticsearchTemplate.deleteIndex(SampleEntity.class); elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.refresh(SampleEntity.class, true); } @@ -487,5 +485,4 @@ public class CustomMethodRepositoryTests { assertThat(sampleEntities.isEmpty(), is(false)); assertThat(sampleEntities.size(), is(1)); } - } 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 8d911ab1f..e766db2da 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/NonDocumentEntityRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/NonDocumentEntityRepository.java @@ -26,4 +26,5 @@ import org.springframework.data.elasticsearch.repository.ElasticsearchRepository */ @Lazy 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 c31d8d26a..3999a689f 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/SampleCustomMethodRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/SampleCustomMethodRepository.java @@ -15,14 +15,14 @@ */ package org.springframework.data.elasticsearch.repositories; +import java.util.List; + import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.SampleEntity; import org.springframework.data.elasticsearch.annotations.Query; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; -import java.util.List; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -64,5 +64,4 @@ public interface SampleCustomMethodRepository extends ElasticsearchRepository findByAvailableFalse(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 6bb10dda3..bb7b2f7a6 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/SampleElasticSearchBookRepository.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/SampleElasticSearchBookRepository.java @@ -23,4 +23,5 @@ import org.springframework.data.elasticsearch.repository.ElasticsearchRepository * @author Mohsin Husen */ public interface SampleElasticSearchBookRepository extends ElasticsearchRepository { + } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryClient.java b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryClient.java index cc2a6b9fa..ec3b3214a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryClient.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryClient.java @@ -23,7 +23,7 @@ import javax.inject.Inject; */ class CdiRepositoryClient { - private CdiProductRepository repository; + private CdiProductRepository repository; public CdiProductRepository getRepository() { return repository; @@ -33,5 +33,4 @@ class CdiRepositoryClient { public void setRepository(CdiProductRepository repository) { this.repository = repository; } - } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryTests.java index 7f2770500..cf579b1df 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/CdiRepositoryTests.java @@ -15,13 +15,16 @@ */ package org.springframework.data.elasticsearch.repositories.cdi; +import static org.junit.Assert.*; + import org.apache.webbeans.cditest.CdiTestContainer; import org.apache.webbeans.cditest.CdiTestContainerLoader; -import org.junit.*; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; import org.springframework.data.elasticsearch.Product; -import static org.junit.Assert.*; - /** * @author Mohsin Husen */ @@ -77,5 +80,4 @@ public class CdiRepositoryTests { retrieved = repository.findOne(bean.getId()); assertNull(retrieved); } - } diff --git a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/ElasticsearchTemplateProducer.java b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/ElasticsearchTemplateProducer.java index 825e8707c..97e5e9181 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/ElasticsearchTemplateProducer.java +++ b/src/test/java/org/springframework/data/elasticsearch/repositories/cdi/ElasticsearchTemplateProducer.java @@ -15,6 +15,14 @@ */ package org.springframework.data.elasticsearch.repositories.cdi; +import static org.elasticsearch.node.NodeBuilder.*; + +import javax.annotation.PreDestroy; +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Produces; +import javax.xml.parsers.ParserConfigurationException; +import java.io.IOException; + import org.elasticsearch.client.node.NodeClient; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.index.query.QueryBuilders; @@ -23,25 +31,17 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.DeleteQuery; import org.xml.sax.SAXException; -import javax.annotation.PreDestroy; -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.inject.Produces; -import javax.xml.parsers.ParserConfigurationException; -import java.io.IOException; - -import static org.elasticsearch.node.NodeBuilder.nodeBuilder; - /** * @author Mohsin Husen */ @ApplicationScoped class ElasticsearchTemplateProducer { - @Produces + @Produces public ElasticsearchOperations createElasticsearchTemplate() throws IOException, ParserConfigurationException, SAXException { - ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder().put("http.enabled","false" ); - NodeClient client = (NodeClient) nodeBuilder().settings(settings).clusterName("testClusterForCDI").local(true).node() - .client(); + ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder().put("http.enabled", "false"); + NodeClient client = (NodeClient) nodeBuilder().settings(settings).clusterName("testClusterForCDI").local(true).node() + .client(); return new ElasticsearchTemplate(client); } @@ -55,10 +55,10 @@ class ElasticsearchTemplateProducer { ElasticsearchOperations template; try { template = createElasticsearchTemplate(); - DeleteQuery deleteQuery = new DeleteQuery(); - deleteQuery.setQuery(QueryBuilders.matchAllQuery()); - deleteQuery.setIndex("test-product-index"); - deleteQuery.setType("test-product-type"); + DeleteQuery deleteQuery = new DeleteQuery(); + deleteQuery.setQuery(QueryBuilders.matchAllQuery()); + deleteQuery.setIndex("test-product-index"); + deleteQuery.setType("test-product-type"); template.delete(deleteQuery); } catch (IOException e) { throw new RuntimeException(e); @@ -67,7 +67,5 @@ class ElasticsearchTemplateProducer { } catch (SAXException e) { throw new RuntimeException(e); } - } - } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryManualWiringTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryManualWiringTests.java index 72276bac7..192554df4 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryManualWiringTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryManualWiringTests.java @@ -15,6 +15,9 @@ */ package org.springframework.data.elasticsearch.repository.complex; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,11 +27,6 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - /** * @author Artur Konczak */ @@ -36,28 +34,26 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:complex-custom-method-repository-manual-wiring-test.xml") public class ComplexCustomMethodRepositoryManualWiringTests { - @Resource - private ComplexElasticsearchRepositoryManualWiring complexRepository; + @Autowired + private ComplexElasticsearchRepositoryManualWiring complexRepository; @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); + elasticsearchTemplate.deleteIndex(SampleEntity.class); elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.refresh(SampleEntity.class, true); } - @Test - public void shouldExecuteComplexCustomMethod() { - //Given - - //When - String result = complexRepository.doSomethingSpecial(); - //Then - assertThat(result, is("3+3=6")); - - } + @Test + public void shouldExecuteComplexCustomMethod() { + //Given + //When + String result = complexRepository.doSomethingSpecial(); + //Then + assertThat(result, is("3+3=6")); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryTests.java b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryTests.java index d8167d034..f29aa5991 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryTests.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexCustomMethodRepositoryTests.java @@ -15,6 +15,9 @@ */ package org.springframework.data.elasticsearch.repository.complex; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,11 +27,6 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - /** * @author Artur Konczak * @author Mohsin Husen @@ -37,28 +35,26 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:complex-custom-method-repository-test.xml") public class ComplexCustomMethodRepositoryTests { - @Resource - private ComplexElasticsearchRepository complexRepository; + @Autowired + private ComplexElasticsearchRepository complexRepository; @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); + elasticsearchTemplate.deleteIndex(SampleEntity.class); elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.refresh(SampleEntity.class, true); } - @Test - public void shouldExecuteComplexCustomMethod() { - //Given - - //When - String result = complexRepository.doSomethingSpecial(); - //Then - assertThat(result, is("2+2=4")); - - } + @Test + public void shouldExecuteComplexCustomMethod() { + //Given + //When + String result = complexRepository.doSomethingSpecial(); + //Then + assertThat(result, is("2+2=4")); + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryCustom.java b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryCustom.java index 424b5f9d2..4c7f47a80 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryCustom.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryCustom.java @@ -21,6 +21,5 @@ package org.springframework.data.elasticsearch.repository.complex; */ public interface ComplexElasticsearchRepositoryCustom { - public String doSomethingSpecial(); - + public String doSomethingSpecial(); } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryImpl.java b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryImpl.java index 27a4bb94d..d51e41a0a 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryImpl.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryImpl.java @@ -8,14 +8,12 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; */ public class ComplexElasticsearchRepositoryImpl implements ComplexElasticsearchRepositoryCustom { - @Autowired - private ElasticsearchTemplate template; - - @Override - public String doSomethingSpecial() { - assert(template.getElasticsearchConverter()!=null); - return "2+2=4"; - } - + @Autowired + private ElasticsearchTemplate template; + @Override + public String doSomethingSpecial() { + assert (template.getElasticsearchConverter() != null); + return "2+2=4"; + } } diff --git a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryManualWiringImpl.java b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryManualWiringImpl.java index 9dd400893..5ac910472 100644 --- a/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryManualWiringImpl.java +++ b/src/test/java/org/springframework/data/elasticsearch/repository/complex/ComplexElasticsearchRepositoryManualWiringImpl.java @@ -23,15 +23,15 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; */ public class ComplexElasticsearchRepositoryManualWiringImpl implements ComplexElasticsearchRepositoryCustom { - private ElasticsearchTemplate template; + private ElasticsearchTemplate template; - @Override - public String doSomethingSpecial() { - assert(template.getElasticsearchConverter()!=null); - return "3+3=6"; - } + @Override + public String doSomethingSpecial() { + assert (template.getElasticsearchConverter() != null); + return "3+3=6"; + } - public void setTemplate(ElasticsearchTemplate template) { - this.template = template; - } + public void setTemplate(ElasticsearchTemplate template) { + this.template = template; + } } 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 f2772e6d5..719cdca4e 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 @@ -15,6 +15,11 @@ */ package org.springframework.data.elasticsearch.repository.support; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.Arrays; + import org.apache.commons.lang.math.RandomUtils; import org.junit.Before; import org.junit.Test; @@ -25,11 +30,6 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.repositories.DoubleIDRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; -import java.util.Arrays; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; /** * @author Rizwan Idrees @@ -40,18 +40,18 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:/simple-repository-test.xml") public class DoubleIDRepositoryTests { - @Resource + @Autowired private DoubleIDRepository repository; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { elasticsearchTemplate.deleteIndex(DoubleIDEntity.class); - elasticsearchTemplate.createIndex(DoubleIDEntity.class); - elasticsearchTemplate.refresh(DoubleIDEntity.class, true); + elasticsearchTemplate.createIndex(DoubleIDEntity.class); + elasticsearchTemplate.refresh(DoubleIDEntity.class, true); } @Test 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 c150f4fdc..860fa4492 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,6 +15,8 @@ */ package org.springframework.data.elasticsearch.repository.support; +import static org.mockito.Mockito.*; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,8 +33,6 @@ import org.springframework.data.querydsl.QueryDslPredicateExecutor; 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 @@ -60,5 +60,4 @@ public class ElasticsearchRepositoryFactoryTests { // 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 036e62ea8..294deddbb 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 @@ -15,6 +15,11 @@ */ package org.springframework.data.elasticsearch.repository.support; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.Arrays; + import org.apache.commons.lang.math.RandomUtils; import org.junit.Before; import org.junit.Test; @@ -25,11 +30,6 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.repositories.IntegerIDRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; -import java.util.Arrays; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; /** * @author Rizwan Idrees @@ -40,19 +40,19 @@ import static org.junit.Assert.assertThat; @ContextConfiguration("classpath:/simple-repository-test.xml") public class IntegerIDRepositoryTests { - @Resource + @Autowired private IntegerIDRepository repository; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; - @Before - public void before() { - elasticsearchTemplate.deleteIndex(IntegerIDEntity.class); - elasticsearchTemplate.createIndex(IntegerIDEntity.class); - elasticsearchTemplate.refresh(IntegerIDEntity.class, true); - } + @Before + public void before() { + elasticsearchTemplate.deleteIndex(IntegerIDEntity.class); + elasticsearchTemplate.createIndex(IntegerIDEntity.class); + elasticsearchTemplate.refresh(IntegerIDEntity.class, true); + } @Test public void shouldDoBulkIndexDocument() { 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 430e79018..fe83aa266 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,6 +15,15 @@ */ package org.springframework.data.elasticsearch.repository.support; +import static org.apache.commons.lang.RandomStringUtils.*; +import static org.elasticsearch.index.query.QueryBuilders.*; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + import org.junit.Before; import org.junit.Ignore; import org.junit.Test; @@ -31,16 +40,6 @@ import org.springframework.data.elasticsearch.repositories.SampleElasticsearchRe import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.annotation.Resource; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.apache.commons.lang.RandomStringUtils.randomNumeric; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - /** * @author Rizwan Idrees * @author Mohsin Husen @@ -50,19 +49,19 @@ import static org.junit.Assert.*; @ContextConfiguration("classpath:/simple-repository-test.xml") public class SimpleElasticsearchRepositoryTests { - @Resource + @Autowired private SampleElasticsearchRepository repository; - @Autowired - private ElasticsearchTemplate elasticsearchTemplate; + @Autowired + private ElasticsearchTemplate elasticsearchTemplate; - @Before - public void before() { - elasticsearchTemplate.deleteIndex(SampleEntity.class); - elasticsearchTemplate.createIndex(SampleEntity.class); - elasticsearchTemplate.refresh(SampleEntity.class, true); - } + @Before + public void before() { + elasticsearchTemplate.deleteIndex(SampleEntity.class); + elasticsearchTemplate.createIndex(SampleEntity.class); + elasticsearchTemplate.refresh(SampleEntity.class, true); + } @Test public void shouldDoBulkIndexDocument() { @@ -105,16 +104,16 @@ public class SimpleElasticsearchRepositoryTests { } @Test - public void shouldSaveDocumentWithoutId() { - // given - SampleEntity sampleEntity = new SampleEntity(); - sampleEntity.setMessage("some message"); - sampleEntity.setVersion(System.currentTimeMillis()); - // when - repository.save(sampleEntity); - // then - assertThat(sampleEntity.getId(), is(notNullValue())); - } + public void shouldSaveDocumentWithoutId() { + // given + SampleEntity sampleEntity = new SampleEntity(); + sampleEntity.setMessage("some message"); + sampleEntity.setVersion(System.currentTimeMillis()); + // when + repository.save(sampleEntity); + // then + assertThat(sampleEntity.getId(), is(notNullValue())); + } @Test public void shouldFindDocumentById() { @@ -410,7 +409,7 @@ public class SimpleElasticsearchRepositoryTests { repository.save(sampleEntities); // when - Page results = repository.searchSimilar(sampleEntities.get(0), new String[]{"message"} ,new PageRequest(0, 5)); + Page results = repository.searchSimilar(sampleEntities.get(0), new String[]{"message"}, new PageRequest(0, 5)); // then assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L))); diff --git a/src/test/resources/META-INF/beans.xml b/src/test/resources/META-INF/beans.xml index 7b5940532..cc7c5873c 100644 --- a/src/test/resources/META-INF/beans.xml +++ b/src/test/resources/META-INF/beans.xml @@ -1,5 +1,5 @@ - + diff --git a/src/test/resources/complex-custom-method-repository-manual-wiring-test.xml b/src/test/resources/complex-custom-method-repository-manual-wiring-test.xml index 3eab6f43b..774ab9cac 100644 --- a/src/test/resources/complex-custom-method-repository-manual-wiring-test.xml +++ b/src/test/resources/complex-custom-method-repository-manual-wiring-test.xml @@ -1,21 +1,22 @@ - + - - - + + + - + - + diff --git a/src/test/resources/complex-custom-method-repository-test.xml b/src/test/resources/complex-custom-method-repository-test.xml index a382dd09a..fef0776dc 100644 --- a/src/test/resources/complex-custom-method-repository-test.xml +++ b/src/test/resources/complex-custom-method-repository-test.xml @@ -1,18 +1,18 @@ - + - - - + + + - + \ No newline at end of file diff --git a/src/test/resources/custom-method-repository-test.xml b/src/test/resources/custom-method-repository-test.xml index 6d4eaecc8..87f82d868 100644 --- a/src/test/resources/custom-method-repository-test.xml +++ b/src/test/resources/custom-method-repository-test.xml @@ -1,20 +1,20 @@ - + - - - + + + - + \ No newline at end of file diff --git a/src/test/resources/elasticsearch-template-custom-mapper.xml b/src/test/resources/elasticsearch-template-custom-mapper.xml index 57e9877e4..60c54eae7 100644 --- a/src/test/resources/elasticsearch-template-custom-mapper.xml +++ b/src/test/resources/elasticsearch-template-custom-mapper.xml @@ -1,9 +1,7 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> diff --git a/src/test/resources/elasticsearch-template-test.xml b/src/test/resources/elasticsearch-template-test.xml index c793b4809..afc5bbd2b 100644 --- a/src/test/resources/elasticsearch-template-test.xml +++ b/src/test/resources/elasticsearch-template-test.xml @@ -1,15 +1,13 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> - + - - - + + + \ No newline at end of file diff --git a/src/test/resources/infrastructure.xml b/src/test/resources/infrastructure.xml index 7c17a094d..c02c5973e 100644 --- a/src/test/resources/infrastructure.xml +++ b/src/test/resources/infrastructure.xml @@ -1,11 +1,11 @@ - + diff --git a/src/test/resources/logback.xml b/src/test/resources/logback.xml index bccb2dc4f..e03b673a5 100644 --- a/src/test/resources/logback.xml +++ b/src/test/resources/logback.xml @@ -1,14 +1,14 @@ - - - %d %5p %40.40c:%4L - %m%n - - + + + %d %5p %40.40c:%4L - %m%n + + - - - + + + \ 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 e16874b6e..3af90c844 100644 --- a/src/test/resources/org/springframework/data/elasticsearch/config/namespace.xml +++ b/src/test/resources/org/springframework/data/elasticsearch/config/namespace.xml @@ -1,22 +1,22 @@ - + - - - + + + - + - + \ 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 85002d6b6..af1135eff 100644 --- a/src/test/resources/repository-non-document-entity.xml +++ b/src/test/resources/repository-non-document-entity.xml @@ -1,17 +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 85002d6b6..af1135eff 100644 --- a/src/test/resources/repository-test-nested-object.xml +++ b/src/test/resources/repository-test-nested-object.xml @@ -1,17 +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 6d4eaecc8..87f82d868 100644 --- a/src/test/resources/simple-repository-test.xml +++ b/src/test/resources/simple-repository-test.xml @@ -1,20 +1,20 @@ - + - - - + + + - + \ No newline at end of file