1
0
mirror of synced 2026-09-06 07:59:39 +00:00

Compare commits

..

58 Commits

Author SHA1 Message Date
Oliver Gierke 15c5415276 DATAES-336 - Release version 2.0.9 (Hopper SR9). 2017-04-19 12:38:29 +02:00
Oliver Gierke c895ea43cf DATAES-336 - Prepare 2.0.9 (Hopper SR9). 2017-04-19 12:37:53 +02:00
Oliver Gierke 7d479090dc DATAES-336 - Updated changelog. 2017-04-19 12:37:50 +02:00
Oliver Gierke 1422c290d9 DATAES-335 - Updated changelog. 2017-04-19 11:50:52 +02:00
Oliver Gierke 38c571e49b DATAES-311 - Updated changelog. 2017-04-19 09:42:53 +02:00
Oliver Gierke e16be395ce DATAES-326 - After release cleanups. 2017-03-02 12:05:58 +01:00
Oliver Gierke 0040779053 DATAES-326 - Prepare next development iteration. 2017-03-02 12:05:55 +01:00
Oliver Gierke 113cb52fbc DATAES-326 - Release version 2.0.8 (Hopper SR8). 2017-03-02 11:30:06 +01:00
Oliver Gierke 388a77d51e DATAES-326 - Prepare 2.0.8 (Hopper SR8). 2017-03-02 11:29:34 +01:00
Oliver Gierke 78e25b8ddf DATAES-326 - Updated changelog. 2017-03-02 11:29:31 +01:00
Oliver Gierke 01067d1127 DATAES-327 - Updated changelog. 2017-03-02 11:11:07 +01:00
Mark Paluch 242460df4c DATAES-329 - Remove references to Assert single-arg methods.
Replace references to Assert single-arg methods with references to methods accepting the test object and message.

Related ticket: SPR-15196.
2017-02-02 08:45:34 +01:00
Mark Paluch 85a95219a1 DATAES-325 - Replace references to GenericCollectionTypeResolver with ResolvableType.
Using ResolvableType instead of GenericCollectionTypeResolver that is removed with Spring 5.

Related ticket: SPR-15160.
2017-01-26 14:05:07 +01:00
Oliver Gierke f55e2e33f5 DATAES-319 - After release cleanups. 2017-01-26 12:04:58 +01:00
Oliver Gierke 667cd84350 DATAES-319 - Prepare next development iteration. 2017-01-26 12:04:55 +01:00
Oliver Gierke 130625cd00 DATAES-319 - Release version 2.0.7 (Hopper SR7). 2017-01-26 11:33:52 +01:00
Oliver Gierke 640e24821c DATAES-319 - Prepare 2.0.7 (Hopper SR7). 2017-01-26 11:33:08 +01:00
Oliver Gierke 52afb8d9a2 DATAES-319 - Updated changelog. 2017-01-26 11:33:05 +01:00
Oliver Gierke 64bcce6784 DATAES-320 - Updated changelog. 2017-01-26 11:23:34 +01:00
Oliver Gierke 78c7668681 DATAES-304 - After release cleanups. 2016-12-21 19:33:45 +01:00
Oliver Gierke 634c0e8b1f DATAES-304 - Prepare next development iteration. 2016-12-21 19:33:41 +01:00
Oliver Gierke 51ca555470 DATAES-304 - Release version 2.0.6 (Hopper SR6). 2016-12-21 19:04:47 +01:00
Oliver Gierke bc4891907e DATAES-304 - Prepare 2.0.6 (Hopper SR6). 2016-12-21 19:03:40 +01:00
Oliver Gierke 96934676ae DATAES-304 - Updated changelog. 2016-12-21 19:03:36 +01:00
Oliver Gierke 90348459e7 DATAES-275 - Updated changelog. 2016-12-21 18:43:08 +01:00
Oliver Gierke e2a868ef97 DATAES-306 - Updated changelog. 2016-11-23 13:52:50 +01:00
Oliver Gierke 0c146bb47c DATAES-300 - After release cleanups. 2016-11-03 18:20:12 +01:00
Oliver Gierke 35ad47da4a DATAES-300 - Prepare next development iteration. 2016-11-03 18:20:10 +01:00
Oliver Gierke fd33ad40d7 DATAES-300 - Release version 2.0.5 (Hopper SR5). 2016-11-03 17:56:33 +01:00
Oliver Gierke ac7ee3e986 DATAES-300 - Prepare 2.0.5 (Hopper SR5). 2016-11-03 17:56:00 +01:00
Oliver Gierke 729ecb2ed9 DATAES-300 - Updated changelog. 2016-11-03 17:55:57 +01:00
Oliver Gierke 89b99c7687 DATAES-297 - After release cleanups. 2016-09-29 14:20:14 +02:00
Oliver Gierke 4498805d0d DATAES-297 - Prepare next development iteration. 2016-09-29 14:20:10 +02:00
Oliver Gierke c781fde4b4 DATAES-297 - Release version 2.0.4 (Hopper SR4). 2016-09-29 13:54:04 +02:00
Oliver Gierke 67385a9c51 DATAES-297 - Prepare 2.0.4 (Hopper SR4). 2016-09-29 13:53:27 +02:00
Oliver Gierke 30cf3b5172 DATAES-297 - Updated changelog. 2016-09-29 13:53:23 +02:00
Oliver Gierke baa52a82e4 DATAES-299 - Updated changelog. 2016-09-29 11:42:12 +02:00
Oliver Gierke 397d3b89f8 DATAES-296 - Updated changelog. 2016-09-21 07:28:59 +02:00
Oliver Gierke abd6ad3536 DATAES-268 - After release cleanups. 2016-09-20 11:19:05 +02:00
Oliver Gierke 0510b06ee4 DATAES-268 - Prepare next development iteration. 2016-09-20 11:19:01 +02:00
Oliver Gierke ff1f7676b2 DATAES-268 - Release version 2.0.3 (Hopper SR3). 2016-09-20 10:54:51 +02:00
Oliver Gierke 10a11ad22f DATAES-268 - Prepare 2.0.3 (Hopper SR3). 2016-09-20 10:54:17 +02:00
Oliver Gierke 0978c47fb9 DATAES-268 - Updated changelog. 2016-09-20 10:54:14 +02:00
Oliver Gierke acc81f89fb DATAES-281 - Polishing.
Added unit test for change in DefaultResultMapperTests. Tweaked and simplified integration tests.

Make use of IdentifierAccessor in ElasticsearcTemplate.getPersistentEntityId(…). Added missing generics in DefaultResultMapper.

Removed unused imports, fixed copyright ranges, authors.

Original pull request: #156.
2016-08-20 10:07:59 +02:00
Young Gu 4fb2b33066 DATAES-281 - Setting identifier values now uses PersistentPropertyAccessor API.
DefaultResultMapper and ElasticsearchTemplate now use the PersistentPropertyAccessor API to set identifier values on objects instead of using reflection.

Original pull request: #156.
2016-08-20 10:04:09 +02:00
Oliver Gierke 20d8103a19 DATAES-250 - Updated changelog. 2016-07-28 08:50:39 +02:00
Artur Konczak c799e8d1c8 DATAES-262 - added profile to build project with ES 2.3.3 2016-06-17 09:31:49 +01:00
Oliver Gierke e4e6b09161 DATAES-251 - After release cleanups. 2016-06-15 14:17:54 +02:00
Oliver Gierke 511da0fadf DATAES-251 - Prepare next development iteration. 2016-06-15 14:17:52 +02:00
Oliver Gierke 6090f4a5db DATAES-251 - Release version 2.0.2 (Hopper SR2). 2016-06-15 13:45:53 +02:00
Oliver Gierke c964ce5dac DATAES-251 - Prepare 2.0.2 (Hopper SR2). 2016-06-15 13:44:54 +02:00
Oliver Gierke 2f50462857 DATAES-251 - Updated changelog. 2016-06-15 13:44:49 +02:00
Oliver Gierke eab54cb546 DATAES-249 - After release cleanups. 2016-04-06 22:51:45 +02:00
Oliver Gierke 6bdb45a0f8 DATAES-249 - Prepare next development iteration. 2016-04-06 22:51:43 +02:00
Oliver Gierke 793e6ab843 DATAES-249 - Release version 2.0.1 (Hopper SR1). 2016-04-06 22:32:15 +02:00
Oliver Gierke 182684e56c DATAES-249 - Prepare 2.0.1 (Hopper SR1). 2016-04-06 22:31:41 +02:00
Oliver Gierke 33e1611186 DATAES-249 - Updated changelog. 2016-04-06 22:31:38 +02:00
Oliver Gierke 55ccfe5c0b DATAES-245 - Prepare next development iteration. 2016-04-06 16:38:19 +02:00
129 changed files with 1159 additions and 3742 deletions
+1 -4
View File
@@ -1,12 +1,9 @@
<!--
Thank you for proposing a pull request. This template will guide you through the essential steps necessary for a pull request.
Make sure that:
-->
- [ ] You have read the [Spring Data contribution guidelines](https://github.com/spring-projects/spring-data-build/blob/master/CONTRIBUTING.adoc).
- [ ] There is a ticket in the bug tracker for the project in our [JIRA](https://jira.spring.io/browse/DATAES).
- [ ] You use the code formatters provided [here](https://github.com/spring-projects/spring-data-build/tree/master/etc/ide) and have them applied to your changes. Dont submit any formatting related changes.
- [ ] You submit test cases (unit or integration tests) that back your changes.
- [ ] You added yourself as author in the headers of the classes you touched. Amend the date range in the Apache license header if needed. For new types, add the license header (copy from another file and set the current year only).
- [ ] You provide your full name and an email address registered with your GitHub account. If youre a first-time submitter, make sure you have completed the [Contributors License Agreement form](https://support.springsource.com/spring_committer_signup).
+10 -5
View File
@@ -31,7 +31,7 @@ Add the Maven dependency:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>x.y.z.RELEASE</version>
<version>1.3.4.RELEASE</version>
</dependency>
```
@@ -42,7 +42,7 @@ the appropriate dependency version.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>x.y.z.BUILD-SNAPSHOT</version>
<version>2.0.0.BUILD-SNAPSHOT</version>
</dependency>
<repository>
@@ -52,10 +52,15 @@ the appropriate dependency version.
</repository>
```
### Note:
1) Spring data elaticsearch until 1.0.0.RELEASE version is on elasticsearch 1.1.x library, which uses java 1.6 or later version.
2) From spring data elasticsearch 1.1.0.RELEASE the version of elasticsearch is 1.3.x which is supporting java 1.7 or later.
| spring data elasticsearch | elasticsearch |
|:-----------------------------------:|:-------------:|
| 2.0.4.RELEASE | 2.4.0 |
| 2.0.0.RELEASE | 2.2.0 |
| 2.0.0.RC1 | 2.2.0 |
| 1.4.0.M1 | 1.7.3 |
| 1.3.0.RELEASE | 1.5.2 |
| 1.2.0.RELEASE | 1.4.4 |
@@ -245,7 +250,7 @@ Here are some ways for you to get involved in the community:
* Github is for social coding: if you want to write code, we encourage contributions through pull requests from [forks of this repository](http://help.github.com/forking/). If you want to contribute code this way, please reference a JIRA ticket as well covering the specific issue you are addressing.
* Watch for upcoming articles on Spring by [subscribing](http://www.springsource.org/node/feed) to springframework.org
Before we accept a non-trivial patch or pull request we will need you to [sign the Contributor License Agreement](https://cla.pivotal.io/sign/spring). Signing the contributors 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. If you forget to do so, you'll be reminded when you submit a pull request. Active contributors might be asked to join the core team, and given the ability to merge pull requests.
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)
+35 -8
View File
@@ -4,12 +4,13 @@
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>3.0.0.M3</version>
<version>2.0.9.RELEASE</version>
<parent>
<groupId>org.springframework.data.build</groupId>
<artifactId>spring-data-parent</artifactId>
<version>2.0.0.M3</version>
<version>1.8.9.RELEASE</version>
<relativePath>../spring-data-build/parent/pom.xml</relativePath>
</parent>
<name>Spring Data Elasticsearch</name>
@@ -17,10 +18,14 @@
<url>https://github.com/spring-projects/spring-data-elasticsearch</url>
<properties>
<dist.key>DATAES</dist.key>
<commonscollections>3.2.1</commonscollections>
<commonslang>2.6</commonslang>
<elasticsearch>2.4.0</elasticsearch>
<springdata.commons>2.0.0.M3</springdata.commons>
<elasticsearch>2.2.0</elasticsearch>
<springdata.commons>1.12.9.RELEASE</springdata.commons>
</properties>
<dependencies>
@@ -95,6 +100,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -144,9 +150,30 @@
<artifactId>asciidoctor-maven-plugin</artifactId>
</plugin>
</plugins>
<testResources>
<testResource>
<directory>${basedir}/src/test/resources</directory>
</testResource>
<testResource>
<targetPath>${basedir}/target/test-home-dir</targetPath>
<directory>${basedir}/src/test/es-modules/${elasticsearch}</directory>
<includes>
<include>**/*</include>
</includes>
</testResource>
</testResources>
</build>
<profiles>
<profile>
<id>es2.3.3</id>
<properties>
<elasticsearch>2.3.3</elasticsearch>
</properties>
</profile>
<profile>
<id>release</id>
<build>
@@ -171,8 +198,8 @@
<repositories>
<repository>
<id>spring-libs-milestone</id>
<url>https://repo.spring.io/libs-milestone</url>
<id>spring-libs-release</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
@@ -192,12 +219,12 @@
<ciManagement>
<system>Bamboo</system>
<url>https://build.spring.io/browse/SPRINGDATAES</url>
<url>http://build.springsource.org/browse/SPRINGDATAES</url>
</ciManagement>
<issueManagement>
<system>JIRA</system>
<url>https://jira.spring.io/browse/DATAES</url>
<url>https://jira.springsource.org/browse/DATAES</url>
</issueManagement>
</project>
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,7 +45,7 @@ class CriteriaFilterProcessor {
QueryBuilder createFilterFromCriteria(Criteria criteria) {
List<QueryBuilder> fbList = new LinkedList<>();
List<QueryBuilder> fbList = new LinkedList<QueryBuilder>();
QueryBuilder filter = null;
ListIterator<Criteria> chainIterator = criteria.getCriteriaChain().listIterator();
@@ -86,7 +86,7 @@ class CriteriaFilterProcessor {
private List<QueryBuilder> createFilterFragmentForCriteria(Criteria chainedCriteria) {
Iterator<Criteria.CriteriaEntry> it = chainedCriteria.getFilterCriteriaEntries().iterator();
List<QueryBuilder> filterList = new LinkedList<>();
List<QueryBuilder> filterList = new LinkedList<QueryBuilder>();
String fieldName = chainedCriteria.getField().getName();
Assert.notNull(fieldName, "Unknown field");
@@ -235,7 +235,7 @@ class CriteriaFilterProcessor {
}
private List<QueryBuilder> buildNegationFilter(String fieldName, Iterator<Criteria.CriteriaEntry> it) {
List<QueryBuilder> notFilterList = new LinkedList<>();
List<QueryBuilder> notFilterList = new LinkedList<QueryBuilder>();
while (it.hasNext()) {
Criteria.CriteriaEntry criteriaEntry = it.next();
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,9 +46,9 @@ class CriteriaQueryProcessor {
if (criteria == null)
return null;
List<QueryBuilder> shouldQueryBuilderList = new LinkedList<>();
List<QueryBuilder> mustNotQueryBuilderList = new LinkedList<>();
List<QueryBuilder> mustQueryBuilderList = new LinkedList<>();
List<QueryBuilder> shouldQueryBuilderList = new LinkedList<QueryBuilder>();
List<QueryBuilder> mustNotQueryBuilderList = new LinkedList<QueryBuilder>();
List<QueryBuilder> mustQueryBuilderList = new LinkedList<QueryBuilder>();
ListIterator<Criteria> chainIterator = criteria.getCriteriaChain().listIterator();
@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,7 @@
*/
package org.springframework.data.elasticsearch.core;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
@@ -22,35 +23,32 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchResponse;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.context.MappingContext;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
/**
* @author Artur Konczak
* @author Petar Tahchiev
* @author Young Gu
* @author Oliver Gierke
* @author Mark Paluch
*/
public class DefaultResultMapper extends AbstractResultMapper {
@@ -77,9 +75,9 @@ public class DefaultResultMapper extends AbstractResultMapper {
}
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
long totalHits = response.getHits().totalHits();
List<T> results = new ArrayList<>();
List<T> results = new ArrayList<T>();
for (SearchHit hit : response.getHits()) {
if (hit != null) {
T result = null;
@@ -89,38 +87,38 @@ public class DefaultResultMapper extends AbstractResultMapper {
result = mapEntity(hit.getFields().values(), clazz);
}
setPersistentEntityId(result, hit.getId(), clazz);
populateScriptFields(result, hit);
populateScriptFields(result, hit);
results.add(result);
}
}
return new AggregatedPageImpl<>(results, pageable, totalHits, response.getAggregations());
return new PageImpl<T>(results, pageable, totalHits);
}
private <T> void populateScriptFields(T result, SearchHit hit) {
if (hit.getFields() != null && !hit.getFields().isEmpty() && result != null) {
for (java.lang.reflect.Field field : result.getClass().getDeclaredFields()) {
ScriptedField scriptedField = field.getAnnotation(ScriptedField.class);
if (scriptedField != null) {
String name = scriptedField.name().isEmpty() ? field.getName() : scriptedField.name();
SearchHitField searchHitField = hit.getFields().get(name);
if (searchHitField != null) {
field.setAccessible(true);
try {
field.set(result, searchHitField.getValue());
} catch (IllegalArgumentException e) {
throw new ElasticsearchException("failed to set scripted field: " + name + " with value: "
+ searchHitField.getValue(), e);
} catch (IllegalAccessException e) {
throw new ElasticsearchException("failed to access scripted field: " + name, e);
}
}
}
}
}
}
private <T> void populateScriptFields(T result, SearchHit hit) {
if (hit.getFields() != null && !hit.getFields().isEmpty() && result != null) {
for (java.lang.reflect.Field field : result.getClass().getDeclaredFields()) {
ScriptedField scriptedField = field.getAnnotation(ScriptedField.class);
if (scriptedField != null) {
String name = scriptedField.name().isEmpty() ? field.getName() : scriptedField.name();
SearchHitField searchHitField = hit.getFields().get(name);
if (searchHitField != null) {
field.setAccessible(true);
try {
field.set(result, searchHitField.getValue());
} catch (IllegalArgumentException e) {
throw new ElasticsearchException("failed to set scripted field: " + name + " with value: "
+ searchHitField.getValue(), e);
} catch (IllegalAccessException e) {
throw new ElasticsearchException("failed to access scripted field: " + name, e);
}
}
}
}
}
}
private <T> T mapEntity(Collection<SearchHitField> values, Class<T> clazz) {
private <T> T mapEntity(Collection<SearchHitField> values, Class<T> clazz) {
return mapEntity(buildJSONFromFields(values), clazz);
}
@@ -160,7 +158,7 @@ public class DefaultResultMapper extends AbstractResultMapper {
@Override
public <T> LinkedList<T> mapResults(MultiGetResponse responses, Class<T> clazz) {
LinkedList<T> list = new LinkedList<>();
LinkedList<T> list = new LinkedList<T>();
for (MultiGetItemResponse response : responses.getResponses()) {
if (!response.isFailed() && response.getResponse().isExists()) {
T result = mapEntity(response.getResponse().getSourceAsString(), clazz);
@@ -175,17 +173,13 @@ public class DefaultResultMapper extends AbstractResultMapper {
if (mappingContext != null && clazz.isAnnotationPresent(Document.class)) {
ElasticsearchPersistentEntity<?> persistentEntity = mappingContext.getRequiredPersistentEntity(clazz);
Optional<ElasticsearchPersistentProperty> idProperty = persistentEntity.getIdProperty();
ElasticsearchPersistentEntity<?> persistentEntity = mappingContext.getPersistentEntity(clazz);
PersistentProperty<?> idProperty = persistentEntity.getIdProperty();
// Only deal with String because ES generated Ids are strings !
idProperty.ifPresent(property -> {
if (property.getType().isAssignableFrom(String.class)) {
persistentEntity.getPropertyAccessor(result).setProperty(property, Optional.ofNullable(id));
}
});
if (idProperty != null && idProperty.getType().isAssignableFrom(String.class)) {
persistentEntity.getPropertyAccessor(result).setProperty(idProperty, id);
}
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,7 +15,8 @@
*/
package org.springframework.data.elasticsearch.core;
import static org.apache.commons.lang.StringUtils.*;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.apache.commons.lang.StringUtils.isBlank;
import static org.elasticsearch.action.search.SearchType.*;
import static org.elasticsearch.client.Requests.*;
import static org.elasticsearch.cluster.metadata.AliasAction.Type.*;
@@ -27,14 +28,7 @@ import static org.springframework.util.CollectionUtils.isEmpty;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.*;
import org.elasticsearch.action.ListenableActionFuture;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
@@ -81,23 +75,17 @@ import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.*;
import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Mapping;
import org.springframework.data.elasticsearch.annotations.Setting;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.util.CloseableIterator;
import org.springframework.util.Assert;
@@ -111,9 +99,8 @@ import org.springframework.util.Assert;
* @author Mason Chan
* @author Young Gu
* @author Oliver Gierke
* @author Mark Janssen
* @author Mark Paluch
*/
public class ElasticsearchTemplate implements ElasticsearchOperations, ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(ElasticsearchTemplate.class);
@@ -130,10 +117,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
this(client, new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext()), entityMapper);
}
public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter,
EntityMapper entityMapper) {
this(client, elasticsearchConverter,
new DefaultResultMapper(elasticsearchConverter.getMappingContext(), entityMapper));
public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter, EntityMapper entityMapper) {
this(client, elasticsearchConverter, new DefaultResultMapper(elasticsearchConverter.getMappingContext(), entityMapper));
}
public ElasticsearchTemplate(Client client, ResultsMapper resultsMapper) {
@@ -144,8 +129,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
this(client, elasticsearchConverter, new DefaultResultMapper(elasticsearchConverter.getMappingContext()));
}
public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter,
ResultsMapper resultsMapper) {
public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter, ResultsMapper resultsMapper) {
Assert.notNull(client, "Client must not be null!");
Assert.notNull(elasticsearchConverter, "ElasticsearchConverter must not be null!");
@@ -173,7 +157,9 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override
public boolean createIndex(String indexName) {
Assert.notNull(indexName, "No index defined for Query");
return client.admin().indices().create(Requests.createIndexRequest(indexName)).actionGet().isAcknowledged();
return client.admin().indices()
.create(Requests.createIndexRequest(indexName))
.actionGet().isAcknowledged();
}
@Override
@@ -192,13 +178,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
XContentBuilder xContentBuilder = null;
try {
Optional<ElasticsearchPersistentProperty> idProperty = persistentEntity.getIdProperty();
ElasticsearchPersistentProperty property = idProperty.orElseThrow(() -> new IllegalArgumentException(String.format("No Id property for %s found", clazz.getSimpleName())));
xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(),
property.getFieldName(), persistentEntity.getParentType().orElse(null));
xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(), persistentEntity
.getIdProperty().getFieldName(), persistentEntity.getParentType());
} catch (Exception e) {
throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e);
}
@@ -207,15 +188,15 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override
public <T> boolean putMapping(Class<T> clazz, Object mapping) {
return putMapping(getPersistentEntityFor(clazz).getIndexName(), getPersistentEntityFor(clazz).getIndexType(),
mapping);
return putMapping(getPersistentEntityFor(clazz).getIndexName(), getPersistentEntityFor(clazz).getIndexType(), mapping);
}
@Override
public boolean putMapping(String indexName, String type, Object mapping) {
Assert.notNull(indexName, "No index defined for putMapping()");
Assert.notNull(type, "No type defined for putMapping()");
PutMappingRequestBuilder requestBuilder = client.admin().indices().preparePutMapping(indexName).setType(type);
PutMappingRequestBuilder requestBuilder = client.admin().indices()
.preparePutMapping(indexName).setType(type);
if (mapping instanceof String) {
requestBuilder.setSource(String.valueOf(mapping));
} else if (mapping instanceof Map) {
@@ -235,8 +216,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
mappings = client.admin().indices().getMappings(new GetMappingsRequest().indices(indexName).types(type))
.actionGet().getMappings().get(indexName).get(type).getSourceAsMap();
} catch (Exception e) {
throw new ElasticsearchException(
"Error while getting mapping for indexName : " + indexName + " type : " + type + " " + e.getMessage());
throw new ElasticsearchException("Error while getting mapping for indexName : " + indexName + " type : " + type + " " + e.getMessage());
}
return mappings;
}
@@ -282,12 +262,12 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
}
@Override
public <T> AggregatedPage<T> queryForPage(SearchQuery query, Class<T> clazz) {
public <T> Page<T> queryForPage(SearchQuery query, Class<T> clazz) {
return queryForPage(query, clazz, resultsMapper);
}
@Override
public <T> AggregatedPage<T> queryForPage(SearchQuery query, Class<T> clazz, SearchResultMapper mapper) {
public <T> Page<T> queryForPage(SearchQuery query, Class<T> clazz, SearchResultMapper mapper) {
SearchResponse response = doSearch(prepareSearch(query, clazz), query);
return mapper.mapResults(response, clazz, query.getPageable());
}
@@ -326,8 +306,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override
public <T> Page<T> queryForPage(CriteriaQuery criteriaQuery, Class<T> clazz) {
QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria());
QueryBuilder elasticsearchFilter = new CriteriaFilterProcessor()
.createFilterFromCriteria(criteriaQuery.getCriteria());
QueryBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria());
SearchRequestBuilder searchRequestBuilder = prepareSearch(criteriaQuery, clazz);
if (elasticsearchQuery != null) {
@@ -346,7 +325,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
logger.debug("doSearch query:\n" + searchRequestBuilder.toString());
}
SearchResponse response = getSearchResponse(searchRequestBuilder.execute());
SearchResponse response = getSearchResponse(searchRequestBuilder
.execute());
return resultsMapper.mapResults(response, clazz, criteriaQuery.getPageable());
}
@@ -380,8 +360,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
return doStream(initScrollId, scrollTimeInMillis, clazz, mapper);
}
private <T> CloseableIterator<T> doStream(final String initScrollId, final long scrollTimeInMillis,
final Class<T> clazz, final SearchResultMapper mapper) {
private <T> CloseableIterator<T> doStream(final String initScrollId, final long scrollTimeInMillis, final Class<T> clazz, final SearchResultMapper mapper) {
return new CloseableIterator<T>() {
/** As we couldn't retrieve single result with scroll, store current hits. */
@@ -415,10 +394,10 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
// Test if it remains hits
if (currentHits == null || !currentHits.hasNext()) {
// Do a new request
SearchResponse response = getSearchResponse(
client.prepareSearchScroll(scrollId).setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute());
SearchResponse response = getSearchResponse(client.prepareSearchScroll(scrollId)
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute());
// Save hits and scroll id
currentHits = mapper.mapResults(response, clazz, Pageable.unpaged()).iterator();
currentHits = mapper.mapResults(response, clazz, null).iterator();
finished = !currentHits.hasNext();
scrollId = response.getScrollId();
}
@@ -432,19 +411,13 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
@Override
public <T> long count(CriteriaQuery criteriaQuery, Class<T> clazz) {
QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria());
QueryBuilder elasticsearchFilter = new CriteriaFilterProcessor()
.createFilterFromCriteria(criteriaQuery.getCriteria());
QueryBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria());
if (elasticsearchFilter == null) {
return doCount(prepareCount(criteriaQuery, clazz), elasticsearchQuery);
@@ -484,8 +457,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
return countRequestBuilder.execute().actionGet().getCount();
}
private long doCount(SearchRequestBuilder searchRequestBuilder, QueryBuilder elasticsearchQuery,
QueryBuilder elasticsearchFilter) {
private long doCount(SearchRequestBuilder searchRequestBuilder, QueryBuilder elasticsearchQuery, QueryBuilder elasticsearchFilter) {
if (elasticsearchQuery != null) {
searchRequestBuilder.setQuery(elasticsearchQuery);
} else {
@@ -499,11 +471,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
}
private <T> CountRequestBuilder prepareCount(Query query, Class<T> clazz) {
String indexName[] = !isEmpty(query.getIndices())
? query.getIndices().toArray(new String[query.getIndices().size()])
: retrieveIndexNameFromPersistentEntity(clazz);
String types[] = !isEmpty(query.getTypes()) ? query.getTypes().toArray(new String[query.getTypes().size()])
: retrieveTypeFromPersistentEntity(clazz);
String indexName[] = !isEmpty(query.getIndices()) ? query.getIndices().toArray(new String[query.getIndices().size()]) : retrieveIndexNameFromPersistentEntity(clazz);
String types[] = !isEmpty(query.getTypes()) ? query.getTypes().toArray(new String[query.getTypes().size()]) : retrieveTypeFromPersistentEntity(clazz);
Assert.notNull(indexName, "No index defined for Query");
@@ -522,10 +491,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
private <T> MultiGetResponse getMultiResponse(Query searchQuery, Class<T> clazz) {
String indexName = !isEmpty(searchQuery.getIndices()) ? searchQuery.getIndices().get(0)
: getPersistentEntityFor(clazz).getIndexName();
String type = !isEmpty(searchQuery.getTypes()) ? searchQuery.getTypes().get(0)
: getPersistentEntityFor(clazz).getIndexType();
String indexName = !isEmpty(searchQuery.getIndices()) ? searchQuery.getIndices().get(0) : getPersistentEntityFor(clazz).getIndexName();
String type = !isEmpty(searchQuery.getTypes()) ? searchQuery.getTypes().get(0) : getPersistentEntityFor(clazz).getIndexType();
Assert.notNull(indexName, "No index defined for Query");
Assert.notNull(type, "No type define for Query");
@@ -570,10 +537,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
}
private UpdateRequestBuilder prepareUpdate(UpdateQuery query) {
String indexName = isNotBlank(query.getIndexName()) ? query.getIndexName()
: getPersistentEntityFor(query.getClazz()).getIndexName();
String type = isNotBlank(query.getType()) ? query.getType()
: getPersistentEntityFor(query.getClazz()).getIndexType();
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");
@@ -584,7 +549,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
if (query.getUpdateRequest().script() == null) {
// doc
if (query.DoUpsert()) {
updateRequestBuilder.setDocAsUpsert(true).setDoc(query.getUpdateRequest().doc());
updateRequestBuilder.setDocAsUpsert(true)
.setDoc(query.getUpdateRequest().doc());
} else {
updateRequestBuilder.setDoc(query.getUpdateRequest().doc());
}
@@ -604,15 +570,15 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
Map<String, String> failedDocuments = new HashMap<>();
Map<String, String> failedDocuments = new HashMap<String, String>();
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);
+ failedDocuments + "]", failedDocuments
);
}
}
@@ -624,15 +590,15 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
Map<String, String> failedDocuments = new HashMap<>();
Map<String, String> failedDocuments = new HashMap<String, String>();
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);
+ failedDocuments + "]", failedDocuments
);
}
}
@@ -648,8 +614,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override
public boolean typeExists(String index, String type) {
return client.admin().cluster().prepareState().execute().actionGet().getState().metaData().index(index)
.getMappings().containsKey(type);
return client.admin().cluster().prepareState().execute().actionGet()
.getState().metaData().index(index).getMappings().containsKey(type);
}
@Override
@@ -680,33 +646,33 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override
public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) {
String indexName = isNotBlank(deleteQuery.getIndex()) ? deleteQuery.getIndex()
: getPersistentEntityFor(clazz).getIndexName();
String typeName = isNotBlank(deleteQuery.getType()) ? deleteQuery.getType()
: getPersistentEntityFor(clazz).getIndexType();
String indexName = isNotBlank(deleteQuery.getIndex()) ? deleteQuery.getIndex() : getPersistentEntityFor(clazz).getIndexName();
String typeName = isNotBlank(deleteQuery.getType()) ? deleteQuery.getType() : getPersistentEntityFor(clazz).getIndexType();
Integer pageSize = deleteQuery.getPageSize() != null ? deleteQuery.getPageSize() : 1000;
Long scrollTimeInMillis = deleteQuery.getScrollTimeInMillis() != null ? deleteQuery.getScrollTimeInMillis()
: 10000l;
Long scrollTimeInMillis = deleteQuery.getScrollTimeInMillis() != null ? deleteQuery.getScrollTimeInMillis() : 10000l;
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(deleteQuery.getQuery()).withIndices(indexName)
.withTypes(typeName).withPageable(PageRequest.of(0, pageSize)).build();
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(deleteQuery.getQuery())
.withIndices(indexName)
.withTypes(typeName)
.withPageable(new PageRequest(0, pageSize))
.build();
String scrollId = scan(searchQuery, scrollTimeInMillis, true);
BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
List<String> ids = new ArrayList<>();
List<String> ids = new ArrayList<String>();
boolean hasRecords = true;
while (hasRecords) {
Page<String> page = scroll(scrollId, scrollTimeInMillis, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<String> result = new ArrayList<>();
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<String> result = new ArrayList<String>();
for (SearchHit searchHit : response.getHits()) {
String id = searchHit.getId();
result.add(id);
}
if (result.size() > 0) {
return new AggregatedPageImpl<>((List<T>) result);
return new PageImpl<T>((List<T>) result);
}
return null;
}
@@ -718,11 +684,11 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
}
}
for (String id : ids) {
for(String id : ids) {
bulkRequestBuilder.add(client.prepareDelete(indexName, typeName, id));
}
if (bulkRequestBuilder.numberOfActions() > 0) {
if(bulkRequestBuilder.numberOfActions() > 0) {
bulkRequestBuilder.execute().actionGet();
}
@@ -772,11 +738,9 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
private SearchRequestBuilder prepareScan(Query query, long scrollTimeInMillis, boolean noFields) {
SearchRequestBuilder requestBuilder = client.prepareSearch(toArray(query.getIndices())).setSearchType(SCAN)
.setTypes(toArray(query.getTypes())).setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).setFrom(0);
if(query.getPageable().isPaged()){
requestBuilder.setSize(query.getPageable().getPageSize());
}
.setTypes(toArray(query.getTypes()))
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).setFrom(0)
.setSize(query.getPageable().getPageSize());
if (!isEmpty(query.getFields())) {
requestBuilder.addFields(toArray(query.getFields()));
@@ -794,8 +758,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
Assert.notNull(criteriaQuery.getPageable(), "Query.pageable is required for scan & scroll");
QueryBuilder elasticsearchQuery = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria());
QueryBuilder elasticsearchFilter = new CriteriaFilterProcessor()
.createFilterFromCriteria(criteriaQuery.getCriteria());
QueryBuilder elasticsearchFilter = new CriteriaFilterProcessor().createFilterFromCriteria(criteriaQuery.getCriteria());
if (elasticsearchQuery != null) {
requestBuilder.setQuery(elasticsearchQuery);
@@ -824,16 +787,16 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override
public <T> Page<T> scroll(String scrollId, long scrollTimeInMillis, Class<T> clazz) {
SearchResponse response = getSearchResponse(
client.prepareSearchScroll(scrollId).setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute());
return resultsMapper.mapResults(response, clazz, Pageable.unpaged());
SearchResponse response = getSearchResponse(client.prepareSearchScroll(scrollId)
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute());
return resultsMapper.mapResults(response, clazz, null);
}
@Override
public <T> Page<T> scroll(String scrollId, long scrollTimeInMillis, SearchResultMapper mapper) {
SearchResponse response = getSearchResponse(
client.prepareSearchScroll(scrollId).setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute());
return mapper.mapResults(response, null, Pageable.unpaged());
SearchResponse response = getSearchResponse(client.prepareSearchScroll(scrollId)
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute());
return mapper.mapResults(response, null, null);
}
@Override
@@ -918,12 +881,6 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
searchRequest.addAggregation(aggregationBuilder);
}
}
if (!isEmpty(searchQuery.getFacets())) {
for (FacetRequest aggregatedFacet : searchQuery.getFacets()) {
searchRequest.addAggregation(aggregatedFacet.getFacet());
}
}
return getSearchResponse(searchRequest.setQuery(searchQuery.getQuery()).execute());
}
@@ -987,8 +944,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
@Override
public Map getSetting(String indexName) {
Assert.notNull(indexName, "No index defined for getSettings");
return client.admin().indices().getSettings(new GetSettingsRequest()).actionGet().getIndexToSettings()
.get(indexName).getAsMap();
return client.admin().indices().getSettings(new GetSettingsRequest())
.actionGet().getIndexToSettings().get(indexName).getAsMap();
}
private <T> SearchRequestBuilder prepareSearch(Query query, Class<T> clazz) {
@@ -1009,7 +966,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
searchRequestBuilder.setFetchSource(sourceFilter.getIncludes(), sourceFilter.getExcludes());
}
if (query.getPageable().isPaged()) {
if (query.getPageable() != null) {
startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
searchRequestBuilder.setSize(query.getPageable().getPageSize());
}
@@ -1021,8 +978,8 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
if (query.getSort() != null) {
for (Sort.Order order : query.getSort()) {
searchRequestBuilder.addSort(order.getProperty(),
order.getDirection() == Sort.Direction.DESC ? SortOrder.DESC : SortOrder.ASC);
searchRequestBuilder.addSort(order.getProperty(), order.getDirection() == Sort.Direction.DESC ? SortOrder.DESC
: SortOrder.ASC);
}
}
@@ -1034,18 +991,21 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
private IndexRequestBuilder prepareIndex(IndexQuery query) {
try {
String indexName = isBlank(query.getIndexName())
? retrieveIndexNameFromPersistentEntity(query.getObject().getClass())[0] : query.getIndexName();
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) {
String id = isBlank(query.getId()) ? getPersistentEntityId(query.getObject()) : query.getId();
String entityId = null;
if (isDocument(query.getObject().getClass())) {
entityId = getPersistentEntityId(query.getObject());
}
// If we have a query id and a document id, do not ask ES to generate one.
if (id != null) {
indexRequestBuilder = client.prepareIndex(indexName, type, id);
if (query.getId() != null && entityId != null) {
indexRequestBuilder = client.prepareIndex(indexName, type, query.getId());
} else {
indexRequestBuilder = client.prepareIndex(indexName, type);
}
@@ -1053,8 +1013,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
} 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() + "]");
throw new ElasticsearchException("object or source is null, failed to index the document [id: " + query.getId() + "]");
}
if (query.getVersion() != null) {
indexRequestBuilder.setVersion(query.getVersion());
@@ -1105,44 +1064,40 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
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();
return client.admin().indices().prepareAliases().removeAlias(query.getIndexName(), query.getAliasName())
.execute().actionGet().isAcknowledged();
}
@Override
public List<AliasMetaData> queryForAlias(String indexName) {
return client.admin().indices().getAliases(new GetAliasesRequest().indices(indexName)).actionGet().getAliases()
.get(indexName);
return client.admin().indices().getAliases(new GetAliasesRequest().indices(indexName))
.actionGet().getAliases().get(indexName);
}
@Override
public 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().getRequiredPersistentEntity(clazz);
return elasticsearchConverter.getMappingContext().getPersistentEntity(clazz);
}
private String getPersistentEntityId(Object entity) {
ElasticsearchPersistentEntity<?> persistentEntity = getPersistentEntityFor(entity.getClass());
Optional<Object> identifier = persistentEntity.getIdentifierAccessor(entity).getIdentifier();
return identifier.map(String::valueOf).orElse(null);
Object identifier = persistentEntity.getIdentifierAccessor(entity).getIdentifier();
return identifier == null ? null : String.valueOf(identifier);
}
private void setPersistentEntityId(Object entity, String id) {
ElasticsearchPersistentEntity<?> persistentEntity = getPersistentEntityFor(entity.getClass());
Optional<ElasticsearchPersistentProperty> idProperty = persistentEntity.getIdProperty();
PersistentProperty<?> idProperty = persistentEntity.getIdProperty();
// Only deal with String because ES generated Ids are strings !
idProperty.ifPresent(property -> {
if (property.getType().isAssignableFrom(String.class)) {
persistentEntity.getPropertyAccessor(entity).setProperty(property, Optional.ofNullable(id));
}
});
if (idProperty != null && idProperty.getType().isAssignableFrom(String.class)) {
persistentEntity.getPropertyAccessor(entity).setProperty(idProperty,id);
}
}
private void setPersistentEntityIndexAndType(Query query, Class clazz) {
@@ -1156,20 +1111,20 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
private String[] retrieveIndexNameFromPersistentEntity(Class clazz) {
if (clazz != null) {
return new String[] { getPersistentEntityFor(clazz).getIndexName() };
return new String[]{getPersistentEntityFor(clazz).getIndexName()};
}
return null;
}
private String[] retrieveTypeFromPersistentEntity(Class clazz) {
if (clazz != null) {
return new String[] { getPersistentEntityFor(clazz).getIndexType() };
return new String[]{getPersistentEntityFor(clazz).getIndexType()};
}
return null;
}
private List<String> extractIds(SearchResponse response) {
List<String> ids = new ArrayList<>();
List<String> ids = new ArrayList<String>();
for (SearchHit hit : response.getHits()) {
if (hit != null) {
ids.add(hit.getId());
@@ -1194,6 +1149,10 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
return resultsMapper;
}
private boolean isDocument(Class clazz) {
return clazz.isAnnotationPresent(Document.class);
}
public static String readFileFromClasspath(String url) {
StringBuilder stringBuilder = new StringBuilder();
@@ -1,37 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.facet.FacetResult;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Jonathan Yan
*/
@Deprecated
public interface FacetedPage<T> extends Page<T> {
boolean hasFacets();
List<FacetResult> getFacets();
FacetResult getFacet(String name);
}
@@ -1,130 +0,0 @@
/*
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStats;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.joda.time.DateTime;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest;
import org.springframework.data.elasticsearch.core.facet.FacetResult;
import org.springframework.data.elasticsearch.core.facet.request.RangeFacetRequest;
import org.springframework.data.elasticsearch.core.facet.result.*;
/**
* Container for query result and facet results
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Jonathan Yan
*/
@Deprecated
public abstract class FacetedPageImpl<T> extends PageImpl<T> implements FacetedPage<T>, AggregatedPage<T> {
private List<FacetResult> facets;
private Map<String, FacetResult> mapOfFacets = new HashMap<>();
public FacetedPageImpl(List<T> content) {
super(content);
}
public FacetedPageImpl(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
}
@Override
public boolean hasFacets() {
processAggregations();
return facets != null && facets.size() > 0;
}
@Override
public List<FacetResult> getFacets() {
processAggregations();
return facets;
}
@Override
public FacetResult getFacet(String name) {
processAggregations();
return mapOfFacets.get(name);
}
private void addFacet(FacetResult facetResult) {
facets.add(facetResult);
mapOfFacets.put(facetResult.getName(), facetResult);
}
/**
* Lazy conversion from aggregation to old facets
*/
private void processAggregations() {
if (facets == null) {
facets = new ArrayList<>();
for (Aggregation agg : getAggregations()) {
if (agg instanceof Terms) {
List<Term> terms = new ArrayList<>();
for (Terms.Bucket t : ((Terms) agg).getBuckets()) {
terms.add(new Term(t.getKeyAsString(), t.getDocCount()));
}
addFacet(new TermResult(agg.getName(), terms, terms.size(), ((Terms) agg).getSumOfOtherDocCounts(), 0));
}
if (agg instanceof Range) {
List<? extends Range.Bucket> buckets = ((Range) agg).getBuckets();
List<org.springframework.data.elasticsearch.core.facet.result.Range> ranges = new ArrayList<>();
for (Range.Bucket b : buckets) {
ExtendedStats rStats = (ExtendedStats) b.getAggregations().get(AbstractFacetRequest.INTERNAL_STATS);
if (rStats != null) {
Sum sum = (Sum) b.getAggregations().get(RangeFacetRequest.RANGE_INTERNAL_SUM);
ranges.add(new org.springframework.data.elasticsearch.core.facet.result.Range((Double) b.getFrom(), (Double) b.getTo(), b.getDocCount(), sum != null ? sum.getValue() : rStats.getSum(), rStats.getCount(), rStats.getMin(), rStats.getMax()));
} else {
ranges.add(new org.springframework.data.elasticsearch.core.facet.result.Range((Double) b.getFrom(), (Double) b.getTo(), b.getDocCount(), 0, 0, 0, 0));
}
}
addFacet(new RangeResult(agg.getName(), ranges));
}
if (agg instanceof ExtendedStats) {
ExtendedStats stats = (ExtendedStats) agg;
addFacet(new StatisticalResult(agg.getName(), stats.getCount(), stats.getMax(), stats.getMin(), stats.getAvg(), stats.getStdDeviation(), stats.getSumOfSquares(), stats.getSum(), stats.getVariance()));
}
if (agg instanceof Histogram) {
List<IntervalUnit> intervals = new ArrayList<>();
for (Histogram.Bucket h : ((Histogram) agg).getBuckets()) {
ExtendedStats hStats = (ExtendedStats) h.getAggregations().get(AbstractFacetRequest.INTERNAL_STATS);
if (hStats != null) {
intervals.add(new IntervalUnit(((DateTime) h.getKey()).getMillis(), h.getDocCount(), h.getDocCount(), hStats.getSum(), hStats.getAvg(), hStats.getMin(), hStats.getMax()));
} else {
intervals.add(new IntervalUnit(((DateTime) h.getKey()).getMillis(), h.getDocCount(), h.getDocCount(), 0, 0, 0, 0));
}
}
addFacet(new HistogramResult(agg.getName(), intervals));
}
}
}
}
}
@@ -32,7 +32,6 @@ import org.springframework.core.ResolvableType;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.annotation.Transient;
import org.springframework.data.elasticsearch.annotations.*;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.completion.Completion;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.mapping.model.SimpleTypeHolder;
@@ -46,7 +45,6 @@ import org.springframework.data.util.TypeInformation;
* @author Kevin Leturc
* @author Alexander Volz
* @author Dennis Maaß
* @author Pavel Luhin
* @author Mark Paluch
*/
class MappingBuilder {
@@ -72,7 +70,7 @@ class MappingBuilder {
public static final String TYPE_VALUE_GEO_HASH_PREFIX = "geohash_prefix";
public static final String TYPE_VALUE_GEO_HASH_PRECISION = "geohash_precision";
private static SimpleTypeHolder SIMPLE_TYPE_HOLDER = SimpleTypeHolder.DEFAULT;
private static SimpleTypeHolder SIMPLE_TYPE_HOLDER = new SimpleTypeHolder();
static XContentBuilder buildMapping(Class clazz, String indexType, String idFieldName, String parentType) throws IOException {
@@ -110,7 +108,7 @@ class MappingBuilder {
for (java.lang.reflect.Field field : fields) {
if (field.isAnnotationPresent(Transient.class) || isInIgnoreFields(field, fieldAnnotation)) {
if (field.isAnnotationPresent(Transient.class) || isInIgnoreFields(field)) {
continue;
}
@@ -167,7 +165,7 @@ class MappingBuilder {
private static java.lang.reflect.Field[] retrieveFields(Class clazz) {
// Create list of fields.
List<java.lang.reflect.Field> fields = new ArrayList<>();
List<java.lang.reflect.Field> fields = new ArrayList<java.lang.reflect.Field>();
// Keep backing up the inheritance hierarchy.
Class targetClass = clazz;
@@ -346,9 +344,10 @@ class MappingBuilder {
return idFieldName.equals(field.getName());
}
private static boolean isInIgnoreFields(java.lang.reflect.Field field, Field parentFieldAnnotation) {
if (null != parentFieldAnnotation) {
String[] ignoreFields = parentFieldAnnotation.ignoreFields();
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;
@@ -16,14 +16,13 @@
package org.springframework.data.elasticsearch.core;
import org.elasticsearch.action.search.SearchResponse;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
/**
* @author Artur Konczak
* @author Petar Tahchiev
*/
public interface SearchResultMapper {
<T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable);
<T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable);
}
@@ -1,17 +0,0 @@
package org.springframework.data.elasticsearch.core.aggregation;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.springframework.data.elasticsearch.core.FacetedPage;
/**
* @author Petar Tahchiev
*/
public interface AggregatedPage<T> extends FacetedPage<T> {
boolean hasAggregations();
Aggregations getAggregations();
Aggregation getAggregation(String name);
}
@@ -1,70 +0,0 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.aggregation.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.FacetedPageImpl;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
/**
* @author Petar Tahchiev
* @author Artur Konczak
* @author Mohsin Husen
*/
public class AggregatedPageImpl<T> extends FacetedPageImpl<T> implements AggregatedPage<T> {
private Aggregations aggregations;
private Map<String, Aggregation> mapOfAggregations = new HashMap<>();
public AggregatedPageImpl(List<T> content) {
super(content);
}
public AggregatedPageImpl(List<T> content, Pageable pageable, long total) {
super(content, pageable, total);
}
public AggregatedPageImpl(List<T> content, Pageable pageable, long total, Aggregations aggregations) {
super(content, pageable, total);
this.aggregations = aggregations;
if (aggregations != null) {
for (Aggregation aggregation : aggregations) {
mapOfAggregations.put(aggregation.getName(), aggregation);
}
}
}
@Override
public boolean hasAggregations() {
return aggregations != null && mapOfAggregations.size() > 0;
}
@Override
public Aggregations getAggregations() {
return aggregations;
}
@Override
public Aggregation getAggregation(String name) {
return aggregations == null ? null : aggregations.get(name);
}
}
@@ -1,50 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet;
import org.springframework.util.Assert;
/**
* @author Artur Konczak
*/
@Deprecated
public abstract class AbstractFacetRequest implements FacetRequest {
public static final String INTERNAL_STATS = "internal-stats";
private String name;
private boolean applyQueryFilter;
public AbstractFacetRequest(String name) {
Assert.hasText(name, "Facet can't be null or empty !!!");
this.name = name;
}
protected String getName() {
return name;
}
public void setApplyQueryFilter(boolean applyQueryFilter) {
this.applyQueryFilter = applyQueryFilter;
}
@Override
public boolean applyQueryFilter() {
return applyQueryFilter;
}
}
@@ -1,47 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet;
import org.springframework.util.Assert;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Jonathan Yan
*/
@Deprecated
public class AbstractFacetResult implements FacetResult {
private final String name;
private final FacetType 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 FacetType getType() {
return type;
}
}
@@ -1,33 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
/**
* @author Artur Koczak
*/
@Deprecated
public interface FacetRequest {
public static final String FIELD_UNTOUCHED = "untouched";
public static final String FIELD_SORT = "sort";
AbstractAggregationBuilder getFacet();
boolean applyQueryFilter();
}
@@ -1,32 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet;
/**
* Generic interface for all facets
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Jonathan Yan
*/
@Deprecated
public interface FacetResult {
String getName();
FacetType getType();
}
@@ -1,27 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet;
/**
* @author Artur Konczak
* @author Petar Tahchiev
*/
@Deprecated
public enum FacetType {
term, range, histogram, statistical
}
@@ -1,73 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.request;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest;
import org.springframework.util.Assert;
/**
* @author Artur Konczak
* @author Mohsin Husen
*/
@Deprecated
public class HistogramFacetRequest extends AbstractFacetRequest {
private String field;
private long interval;
private DateHistogramInterval timeUnit;
public HistogramFacetRequest(String name) {
super(name);
}
public void setField(String field) {
this.field = field;
}
public void setInterval(long interval) {
this.interval = interval;
}
public void setTimeUnit(DateHistogramInterval timeUnit) {
this.timeUnit = timeUnit;
}
public AbstractAggregationBuilder 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 !!!");
DateHistogramBuilder dateHistogramBuilder = AggregationBuilders.dateHistogram(getName());
dateHistogramBuilder.field(field);
if (timeUnit != null) {
dateHistogramBuilder.interval(timeUnit);
} else {
dateHistogramBuilder.interval(interval);
}
dateHistogramBuilder.subAggregation(AggregationBuilders.extendedStats(INTERNAL_STATS));
return dateHistogramBuilder;
}
}
@@ -1,58 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.request;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
/**
* @author Artur Konczak
*/
@Deprecated
public class HistogramFacetRequestBuilder {
HistogramFacetRequest result;
public HistogramFacetRequestBuilder(String name) {
result = new HistogramFacetRequest(name);
}
public HistogramFacetRequestBuilder field(String field) {
result.setField(field);
return this;
}
public HistogramFacetRequestBuilder interval(long interval) {
result.setInterval(interval);
return this;
}
public HistogramFacetRequestBuilder timeUnit(DateHistogramInterval timeUnit) {
result.setTimeUnit(timeUnit);
return this;
}
public FacetRequest build() {
return result;
}
public HistogramFacetRequestBuilder applyQueryFilter() {
result.setApplyQueryFilter(true);
return this;
}
}
@@ -1,43 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.request;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
/**
* @author Artur Konczak
* @author Mohsin Husen
*/
@Deprecated
public class NativeFacetRequest implements FacetRequest {
public NativeFacetRequest() {
throw new UnsupportedOperationException("Native Facet are not supported in Elasticsearch 2.x - use Aggregation");
}
@Override
public AbstractAggregationBuilder getFacet() {
return null;
}
@Override
public boolean applyQueryFilter() {
return false;
}
}
@@ -1,132 +0,0 @@
/*
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.request;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.range.RangeBuilder;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest;
import org.springframework.util.Assert;
/**
* Range facet for numeric fields
*
* @author Artur Konczak
* @author Akos Bordas
*/
@Deprecated
public class RangeFacetRequest extends AbstractFacetRequest {
public static final String RANGE_INTERNAL_SUM = "range-internal-sum";
private String field;
private String keyField;
private String valueField;
private List<Entry> entries = new ArrayList<>();
public RangeFacetRequest(String name) {
super(name);
}
public void setField(String field) {
this.field = field;
}
public void setFields(String keyField, String valueField) {
this.keyField = keyField;
this.valueField = valueField;
}
public void range(Double from, Double to) {
entries.add(new DoubleEntry(from, to));
}
public void range(String from, String to) {
throw new UnsupportedOperationException("Native Facet are not supported in Elasticsearch 2.x - use Aggregation");
}
public void addRange(Double from, Double to) {
entries.add(new DoubleEntry(from, to));
}
public void addRange(String from, String to) {
throw new UnsupportedOperationException("Native Facet are not supported in Elasticsearch 2.x - use Aggregation");
}
@Override
public AbstractAggregationBuilder getFacet() {
Assert.notNull(getName(), "Facet name can't be a null !!!");
RangeBuilder rangeBuilder = AggregationBuilders.range(getName());
rangeBuilder.field(StringUtils.isNotBlank(keyField) ? keyField : field );
for (Entry entry : entries) {
DoubleEntry doubleEntry = (DoubleEntry) entry;
rangeBuilder.addRange(validateValue(doubleEntry.getFrom(), Double.NEGATIVE_INFINITY), validateValue(doubleEntry.getTo(), Double.POSITIVE_INFINITY));
}
rangeBuilder.subAggregation(AggregationBuilders.extendedStats(INTERNAL_STATS));
if(StringUtils.isNotBlank(valueField)){
rangeBuilder.subAggregation(AggregationBuilders.sum(RANGE_INTERNAL_SUM).field(valueField));
}
return rangeBuilder;
}
private double validateValue(Double value, double defaultValue) {
return value == null ? defaultValue : value;
}
static class DoubleEntry extends Entry<Double> {
DoubleEntry(Double from, Double to) {
super(from, to);
}
}
static class StringEntry extends Entry<String> {
StringEntry(String from, String to) {
super(from, to);
}
}
static class Entry<T> {
T from;
T to;
Entry(T from, T to) {
this.from = from;
this.to = to;
}
public T getFrom() {
return from;
}
public T getTo() {
return to;
}
}
}
@@ -1,85 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.request;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
/**
* Basic range facet
*
* @author Artur Konczak
*/
@Deprecated
public class RangeFacetRequestBuilder {
RangeFacetRequest result;
public RangeFacetRequestBuilder(String name) {
result = new RangeFacetRequest(name);
}
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 range(double from, double to) {
result.range(from, to);
return this;
}
public RangeFacetRequestBuilder range(String from, String to) {
result.range(from, to);
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 from(String from) {
result.range(from, null);
return this;
}
public RangeFacetRequestBuilder to(String to) {
result.range(null, to);
return this;
}
public RangeFacetRequestBuilder applyQueryFilter() {
result.setApplyQueryFilter(true);
return this;
}
public FacetRequest build() {
return result;
}
}
@@ -1,53 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.request;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest;
import org.springframework.util.Assert;
/**
* @author Petar Tahchiev
*/
@Deprecated
public class StatisticalFacetRequest extends AbstractFacetRequest {
private String field;
private String[] fields;
public StatisticalFacetRequest(String name) {
super(name);
}
public void setField(String field) {
this.field = field;
}
public void setFields(String... fields) {
throw new UnsupportedOperationException("Native Facet are not supported in Elasticsearch 2.x - use Aggregation");
}
public AbstractAggregationBuilder 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 !!!");
return AggregationBuilders.extendedStats(getName()).field(field);
}
}
@@ -1,52 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.request;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
/**
* @author Petar Tahchiev
*/
@Deprecated
public class StatisticalFacetRequestBuilder {
StatisticalFacetRequest result;
public StatisticalFacetRequestBuilder(String name) {
result = new StatisticalFacetRequest(name);
}
public StatisticalFacetRequestBuilder field(String field) {
result.setField(field);
return this;
}
public StatisticalFacetRequestBuilder fields(String... fields) {
result.setFields(fields);
return this;
}
public StatisticalFacetRequestBuilder applyQueryFilter() {
result.setApplyQueryFilter(true);
return this;
}
public FacetRequest build() {
return result;
}
}
@@ -1,27 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.request;
/**
* @author Artur Konczak
* @author Mohsin Husen
*/
@Deprecated
public enum TermFacetOrder {
ascTerm, descTerm, ascCount, descCount;
}
@@ -1,107 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.request;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetRequest;
import org.springframework.util.Assert;
/**
* Term facet
*
* @author Artur Konczak
*/
@Deprecated
public class TermFacetRequest extends AbstractFacetRequest {
private String[] fields;
private String[] excludeTerms;
private int size = 10;
private TermFacetOrder order = TermFacetOrder.descCount;
private boolean allTerms = false;
private String regex = null;
public TermFacetRequest(String name) {
super(name);
}
public void setFields(String... fields) {
Assert.isTrue(ArrayUtils.isNotEmpty(fields), "Term agg need one field only");
Assert.isTrue(ArrayUtils.getLength(fields) == 1, "Term agg need one field only");
this.fields = fields;
}
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 setExcludeTerms(String... excludeTerms) {
this.excludeTerms = excludeTerms;
}
public void setAllTerms(boolean allTerms) {
this.allTerms = allTerms;
}
public void setRegex(String regex) {
this.regex = regex;
}
@Override
public AbstractAggregationBuilder getFacet() {
Assert.notEmpty(fields, "Please select at last one field !!!");
TermsBuilder termsBuilder = AggregationBuilders.terms(getName()).field(fields[0]).size(this.size);
switch (order) {
case descTerm:
termsBuilder.order(Terms.Order.term(false));
break;
case ascTerm:
termsBuilder.order(Terms.Order.term(true));
break;
case descCount:
termsBuilder.order(Terms.Order.count(false));
break;
default:
termsBuilder.order(Terms.Order.count(true));
}
if (ArrayUtils.isNotEmpty(excludeTerms)) {
termsBuilder.exclude(excludeTerms);
}
if (allTerms) {
termsBuilder.size(Integer.MAX_VALUE);
}
if (StringUtils.isNotBlank(regex)) {
termsBuilder.include(regex);
}
return termsBuilder;
}
}
@@ -1,88 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.request;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
/**
* Basic term facet
*
* @author Artur Konczak
*/
@Deprecated
public class TermFacetRequestBuilder {
private TermFacetRequest result;
public TermFacetRequestBuilder(String name) {
result = new TermFacetRequest(name);
}
public TermFacetRequestBuilder fields(String... fields) {
result.setFields(fields);
return this;
}
public TermFacetRequestBuilder size(int size) {
result.setSize(size);
return this;
}
public TermFacetRequestBuilder excludeTerms(String... terms) {
result.setExcludeTerms(terms);
return this;
}
public TermFacetRequestBuilder allTerms() {
result.setAllTerms(true);
return this;
}
public TermFacetRequestBuilder regex(String regex) {
result.setRegex(regex);
return this;
}
public TermFacetRequestBuilder ascTerm() {
result.setOrder(TermFacetOrder.ascTerm);
return this;
}
public TermFacetRequestBuilder descTerm() {
result.setOrder(TermFacetOrder.descTerm);
return this;
}
public TermFacetRequestBuilder ascCount() {
result.setOrder(TermFacetOrder.ascCount);
return this;
}
public TermFacetRequestBuilder descCount() {
result.setOrder(TermFacetOrder.descCount);
return this;
}
public TermFacetRequestBuilder applyQueryFilter() {
result.setApplyQueryFilter(true);
return this;
}
public FacetRequest build() {
return result;
}
}
@@ -1,39 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.result;
import java.util.List;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetResult;
import org.springframework.data.elasticsearch.core.facet.FacetType;
/**
* @author Artur Konczak
*/
@Deprecated
public class HistogramResult extends AbstractFacetResult {
private List<IntervalUnit> terms;
public HistogramResult(String name, List<IntervalUnit> terms) {
super(name, FacetType.term);
this.terms = terms;
}
public List<IntervalUnit> getIntervalUnit() {
return terms;
}
}
@@ -1,92 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.result;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Single term
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Jonathan Yan
*/
@Deprecated
public class IntervalUnit {
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;
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 getCount() {
return count;
}
public long getTotalCount() {
return totalCount;
}
public double getTotal() {
return total;
}
public double getMean() {
return mean;
}
public double getMin() {
return min;
}
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 +
'}';
}
}
@@ -1,79 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.result;
/**
* Single range
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Jonathan Yan
*/
@Deprecated
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;
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 getTo() {
return to;
}
/**
* Return number of documents in range
*
* @return
*/
public long getCount() {
return count;
}
public double getTotal() {
return total;
}
public double getTotalCount() {
return totalCount;
}
public double getMin() {
return min;
}
public double getMax() {
return max;
}
}
@@ -1,44 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.result;
import java.util.List;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetResult;
import org.springframework.data.elasticsearch.core.facet.FacetType;
/**
* Basic term facet result
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Jonathan Yan
*/
@Deprecated
public class RangeResult extends AbstractFacetResult {
private List<Range> ranges;
public RangeResult(String name, List<Range> ranges) {
super(name, FacetType.range);
this.ranges = ranges;
}
public List<Range> getRanges() {
return ranges;
}
}
@@ -1,86 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.result;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetResult;
import org.springframework.data.elasticsearch.core.facet.FacetType;
/**
* @author Petar Tahchiev
*/
@Deprecated
public class StatisticalResult extends AbstractFacetResult {
private long count;
private double max;
private double min;
private double mean;
private double stdDeviation;
private double sumOfSquares;
private double total;
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 long getCount() {
return count;
}
public double getMax() {
return max;
}
public double getMin() {
return min;
}
public double getMean() {
return mean;
}
public double getStdDeviation() {
return stdDeviation;
}
public double getSumOfSquares() {
return sumOfSquares;
}
public double getTotal() {
return total;
}
public double getVariance() {
return variance;
}
}
@@ -1,44 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.result;
/**
* Single term
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Jonathan Yan
*/
@Deprecated
public class Term {
private String term;
private long count;
public Term(String term, long count) {
this.term = term;
this.count = count;
}
public String getTerm() {
return term;
}
public long getCount() {
return count;
}
}
@@ -1,63 +0,0 @@
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet.result;
import java.util.List;
import org.springframework.data.elasticsearch.core.facet.AbstractFacetResult;
import org.springframework.data.elasticsearch.core.facet.FacetType;
/**
* Basic term facet result
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Jonathan Yan
* @author Matija Obreza
*/
@Deprecated
public class TermResult extends AbstractFacetResult {
private List<Term> terms;
private long total;
private long other;
private long missing;
public TermResult(String name, List<Term> terms, long total, long other, long missing) {
super(name, FacetType.term);
this.terms = terms;
this.total = total;
this.other = other;
this.missing = missing;
}
public List<Term> getTerms() {
return terms;
}
public long getTotal() {
return total;
}
public long getOther() {
return other;
}
public long getMissing() {
return missing;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,8 +15,6 @@
*/
package org.springframework.data.elasticsearch.core.mapping;
import java.util.Optional;
import org.springframework.data.mapping.PersistentEntity;
/**
@@ -24,8 +22,8 @@ import org.springframework.data.mapping.PersistentEntity;
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public interface ElasticsearchPersistentEntity<T> extends PersistentEntity<T, ElasticsearchPersistentProperty> {
String getIndexName();
@@ -42,11 +40,11 @@ public interface ElasticsearchPersistentEntity<T> extends PersistentEntity<T, El
String getIndexStoreType();
Optional<ElasticsearchPersistentProperty> getVersionProperty();
ElasticsearchPersistentProperty getVersionProperty();
Optional<String> getParentType();
String getParentType();
Optional<ElasticsearchPersistentProperty> getParentIdProperty();
ElasticsearchPersistentProperty getParentIdProperty();
String settingPath();
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,11 +15,13 @@
*/
package org.springframework.data.elasticsearch.core.mapping;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.mapping.context.AbstractMappingContext;
import org.springframework.data.mapping.model.Property;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.util.TypeInformation;
@@ -28,8 +30,8 @@ import org.springframework.data.util.TypeInformation;
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public class SimpleElasticsearchMappingContext extends
AbstractMappingContext<SimpleElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> implements ApplicationContextAware {
@@ -37,8 +39,8 @@ public class SimpleElasticsearchMappingContext extends
@Override
protected <T> SimpleElasticsearchPersistentEntity<?> createPersistentEntity(TypeInformation<T> typeInformation) {
final SimpleElasticsearchPersistentEntity<T> persistentEntity = new SimpleElasticsearchPersistentEntity<>(
typeInformation);
final SimpleElasticsearchPersistentEntity<T> persistentEntity =
new SimpleElasticsearchPersistentEntity<T>(typeInformation);
if (context != null) {
persistentEntity.setApplicationContext(context);
}
@@ -46,9 +48,9 @@ public class SimpleElasticsearchMappingContext extends
}
@Override
protected ElasticsearchPersistentProperty createPersistentProperty(Property property,
SimpleElasticsearchPersistentEntity<?> owner, SimpleTypeHolder simpleTypeHolder) {
return new SimpleElasticsearchPersistentProperty(property, owner, simpleTypeHolder);
protected ElasticsearchPersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor,
SimpleElasticsearchPersistentEntity<?> owner, SimpleTypeHolder simpleTypeHolder) {
return new SimpleElasticsearchPersistentProperty(field, descriptor, owner, simpleTypeHolder);
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package org.springframework.data.elasticsearch.core.mapping;
import static org.springframework.util.StringUtils.*;
import java.util.Locale;
import java.util.Optional;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
@@ -42,7 +41,6 @@ import org.springframework.util.Assert;
* @param <T>
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntity<T, ElasticsearchPersistentProperty>
implements ElasticsearchPersistentEntity<T>, ApplicationContextAware {
@@ -57,8 +55,8 @@ public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntit
private short replicas;
private String refreshInterval;
private String indexStoreType;
private Optional<String> parentType = Optional.empty();
private Optional<ElasticsearchPersistentProperty> parentIdProperty = Optional.empty();
private String parentType;
private ElasticsearchPersistentProperty parentIdProperty;
private String settingPath;
private boolean createIndexAndMapping;
@@ -131,12 +129,12 @@ public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntit
}
@Override
public Optional<String> getParentType() {
public String getParentType() {
return parentType;
}
@Override
public Optional<ElasticsearchPersistentProperty> getParentIdProperty() {
public ElasticsearchPersistentProperty getParentIdProperty() {
return parentIdProperty;
}
@@ -154,15 +152,16 @@ public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntit
public void addPersistentProperty(ElasticsearchPersistentProperty property) {
super.addPersistentProperty(property);
Optional<Parent> annotation = property.findAnnotation(Parent.class);
annotation.ifPresent(parent -> {
Assert.isTrue(!this.parentIdProperty.isPresent(), "Only one field can hold a @Parent annotation");
Assert.isTrue(!this.parentType.isPresent(), "Only one field can hold a @Parent annotation");
Assert.isTrue(property.getType() == String.class, "Parent ID property should be String");
this.parentIdProperty = Optional.of(property);
this.parentType = Optional.of(parent.type());
});
if (property.getField() != null) {
Parent parent = property.getField().getAnnotation(Parent.class);
if (parent != null) {
Assert.isNull(this.parentIdProperty, "Only one field can hold a @Parent annotation");
Assert.isNull(this.parentType, "Only one field can hold a @Parent annotation");
Assert.isTrue(property.getType() == String.class, "Parent ID property should be String");
this.parentIdProperty = property;
this.parentType = parent.type();
}
}
if (property.isVersionProperty()) {
Assert.isTrue(property.getType() == Long.class, "Version property should be Long");
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,13 +15,14 @@
*/
package org.springframework.data.elasticsearch.core.mapping;
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.Property;
import org.springframework.data.mapping.model.SimpleTypeHolder;
/**
@@ -29,13 +30,12 @@ import org.springframework.data.mapping.model.SimpleTypeHolder;
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public class SimpleElasticsearchPersistentProperty extends
AnnotationBasedPersistentProperty<ElasticsearchPersistentProperty> implements ElasticsearchPersistentProperty {
private static final Set<Class<?>> SUPPORTED_ID_TYPES = new HashSet<>();
private static final Set<String> SUPPORTED_ID_PROPERTY_NAMES = new HashSet<>();
private static final Set<Class<?>> SUPPORTED_ID_TYPES = new HashSet<Class<?>>();
private static final Set<String> SUPPORTED_ID_PROPERTY_NAMES = new HashSet<String>();
static {
SUPPORTED_ID_TYPES.add(String.class);
@@ -43,19 +43,19 @@ public class SimpleElasticsearchPersistentProperty extends
SUPPORTED_ID_PROPERTY_NAMES.add("documentId");
}
public SimpleElasticsearchPersistentProperty(Property property,
PersistentEntity<?, ElasticsearchPersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
super(property, owner, simpleTypeHolder);
public SimpleElasticsearchPersistentProperty(Field field, PropertyDescriptor propertyDescriptor,
PersistentEntity<?, ElasticsearchPersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
super(field, propertyDescriptor, owner, simpleTypeHolder);
}
@Override
public String getFieldName() {
return getProperty().getName();
return field.getName();
}
@Override
public boolean isIdProperty() {
return super.isIdProperty() || SUPPORTED_ID_PROPERTY_NAMES.contains(getFieldName());
return super.isIdProperty() || (field != null ? SUPPORTED_ID_PROPERTY_NAMES.contains(getFieldName()) : false);
}
@Override
@@ -35,9 +35,9 @@ abstract class AbstractQuery implements Query {
protected Pageable pageable = DEFAULT_PAGE;
protected Sort sort;
protected List<String> indices = new ArrayList<>();
protected List<String> types = new ArrayList<>();
protected List<String> fields = new ArrayList<>();
protected List<String> indices = new ArrayList<String>();
protected List<String> types = new ArrayList<String>();
protected List<String> fields = new ArrayList<String>();
protected SourceFilter sourceFilter;
protected float minScore;
protected Collection<String> ids;
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -57,11 +57,11 @@ public class Criteria {
private float boost = Float.NaN;
private boolean negating = false;
private List<Criteria> criteriaChain = new ArrayList<>(1);
private List<Criteria> criteriaChain = new ArrayList<Criteria>(1);
private Set<CriteriaEntry> queryCriteria = new LinkedHashSet<>();
private Set<CriteriaEntry> queryCriteria = new LinkedHashSet<CriteriaEntry>();
private Set<CriteriaEntry> filterCriteria = new LinkedHashSet<>();
private Set<CriteriaEntry> filterCriteria = new LinkedHashSet<CriteriaEntry>();
public Criteria() {
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,26 +23,24 @@ import org.springframework.util.Assert;
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public class CriteriaQuery extends AbstractQuery {
private Criteria criteria;
private CriteriaQuery() {}
private CriteriaQuery() {
}
public CriteriaQuery(Criteria criteria) {
this(criteria, Pageable.unpaged());
this(criteria, null);
}
public CriteriaQuery(Criteria criteria, Pageable pageable) {
Assert.notNull(criteria, "Criteria must not be null!");
Assert.notNull(pageable, "Pageable must not be null!");
this.criteria = criteria;
this.pageable = pageable;
this.addSort(pageable.getSort());
if (pageable != null) {
this.addSort(pageable.getSort());
}
}
public static final Query fromQuery(CriteriaQuery source) {
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,19 +29,20 @@ import org.springframework.data.domain.Pageable;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class MoreLikeThisQuery {
private String id;
private String indexName;
private String type;
private List<String> searchIndices = new ArrayList<>();
private List<String> searchTypes = new ArrayList<>();
private List<String> fields = new ArrayList<>();
private List<String> searchIndices = new ArrayList<String>();
private List<String> searchTypes = new ArrayList<String>();
private List<String> fields = new ArrayList<String>();
private String routing;
private Float percentTermsToMatch;
private Integer minTermFreq;
private Integer maxQueryTerms;
private List<String> stopWords = new ArrayList<>();
private List<String> stopWords = new ArrayList<String>();
private Integer minDocFreq;
private Integer maxDocFreq;
private Integer minWordLen;
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,7 +22,6 @@ import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
import java.util.Arrays;
@@ -38,8 +37,8 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
private QueryBuilder query;
private QueryBuilder filter;
private List<SortBuilder> sorts;
private final List<ScriptField> scriptFields = new ArrayList<>();
private List<FacetRequest> facets;
private final List<ScriptField> scriptFields = new ArrayList<ScriptField>();
/*private List<FacetRequest> facets;*/
private List<AbstractAggregationBuilder> aggregations;
private HighlightBuilder.Field[] highlightFields;
private List<IndexBoost> indicesBoost;
@@ -95,9 +94,9 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
scriptFields.addAll(Arrays.asList(scriptField));
}
public void addFacet(FacetRequest facetRequest) {
/* public void addFacet(FacetRequest facetRequest) {
if (facets == null) {
facets = new ArrayList<>();
facets = new ArrayList<FacetRequest>();
}
facets.add(facetRequest);
}
@@ -109,7 +108,7 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
@Override
public List<FacetRequest> getFacets() {
return facets;
}
}*/
@Override
public List<AbstractAggregationBuilder> getAggregations() {
@@ -119,7 +118,7 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
public void addAggregation(AbstractAggregationBuilder aggregationBuilder) {
if (aggregations == null) {
aggregations = new ArrayList<>();
aggregations = new ArrayList<AbstractAggregationBuilder>();
}
aggregations.add(aggregationBuilder);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,6 @@ import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
/**
* NativeSearchQuery
@@ -33,18 +32,17 @@ import org.springframework.data.elasticsearch.core.facet.FacetRequest;
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Mark Paluch
*/
public class NativeSearchQueryBuilder {
private QueryBuilder queryBuilder;
private QueryBuilder filterBuilder;
private List<ScriptField> scriptFields = new ArrayList<>();
private List<SortBuilder> sortBuilders = new ArrayList<>();
private List<FacetRequest> facetRequests = new ArrayList<>();
private List<AbstractAggregationBuilder> aggregationBuilders = new ArrayList<>();
private List<ScriptField> scriptFields = new ArrayList<ScriptField>();
private List<SortBuilder> sortBuilders = new ArrayList<SortBuilder>();
private List<AbstractAggregationBuilder> aggregationBuilders = new ArrayList<AbstractAggregationBuilder>();
private HighlightBuilder.Field[] highlightFields;
private Pageable pageable = Pageable.unpaged();
private Pageable pageable;
private String[] indices;
private String[] types;
private String[] fields;
@@ -80,10 +78,10 @@ public class NativeSearchQueryBuilder {
return this;
}
public NativeSearchQueryBuilder withFacet(FacetRequest facetRequest) {
/* public NativeSearchQueryBuilder withFacet(FacetRequest facetRequest) {
facetRequests.add(facetRequest);
return this;
}
}*/
public NativeSearchQueryBuilder withHighlightFields(HighlightBuilder.Field... highlightFields) {
this.highlightFields = highlightFields;
@@ -142,7 +140,9 @@ public class NativeSearchQueryBuilder {
public NativeSearchQuery build() {
NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryBuilder, filterBuilder, sortBuilders, highlightFields);
nativeSearchQuery.setPageable(pageable);
if (pageable != null) {
nativeSearchQuery.setPageable(pageable);
}
if (indices != null) {
nativeSearchQuery.addIndices(indices);
@@ -159,19 +159,15 @@ public class NativeSearchQueryBuilder {
if (sourceFilter != null) {
nativeSearchQuery.addSourceFilter(sourceFilter);
}
if(indicesBoost != null) {
nativeSearchQuery.setIndicesBoost(indicesBoost);
}
if (!isEmpty(scriptFields)) {
nativeSearchQuery.setScriptFields(scriptFields);
}
if (!isEmpty(facetRequests)) {
nativeSearchQuery.setFacets(facetRequests);
}
if (!isEmpty(aggregationBuilders)) {
nativeSearchQuery.setAggregations(aggregationBuilders);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,12 +28,11 @@ import org.springframework.data.domain.Sort;
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public interface Query {
int DEFAULT_PAGE_SIZE = 10;
Pageable DEFAULT_PAGE = PageRequest.of(0, DEFAULT_PAGE_SIZE);
public static final int DEFAULT_PAGE_SIZE = 10;
public static final Pageable DEFAULT_PAGE = new PageRequest(0, DEFAULT_PAGE_SIZE);
/**
* restrict result to entries on given page. Corresponds to the 'start' and 'rows' parameter in elasticsearch
@@ -21,7 +21,6 @@ import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
/**
* NativeSearchQuery
@@ -38,8 +37,7 @@ public interface SearchQuery extends Query {
List<SortBuilder> getElasticsearchSorts();
@Deprecated
List<FacetRequest> getFacets();
/*List<FacetRequest> getFacets();*/
List<AbstractAggregationBuilder> getAggregations();
@@ -43,6 +43,4 @@ public interface ElasticsearchRepository<T, ID extends Serializable> extends Ela
Page<T> searchSimilar(T entity, String[] fields, Pageable pageable);
void refresh();
Class<T> getEntityClass();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,13 +15,11 @@
*/
package org.springframework.data.elasticsearch.repository.cdi;
import java.lang.annotation.Annotation;
import java.util.Optional;
import java.util.Set;
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;
@@ -30,8 +28,7 @@ import org.springframework.data.repository.config.CustomRepositoryImplementation
import org.springframework.util.Assert;
/**
* Uses {@link CdiRepositoryBean} to create
* {@link org.springframework.data.elasticsearch.repository.ElasticsearchRepository} instances.
* Uses CdiRepositoryBean to create ElasticsearchRepository instances.
*
* @author Rizwan Idrees
* @author Mohsin Husen
@@ -49,37 +46,24 @@ public class ElasticsearchRepositoryBean<T> extends CdiRepositoryBean<T> {
* @param repositoryType must not be {@literal null}.
* @param beanManager must not be {@literal null}.
* @param detector detector for the custom {@link org.springframework.data.repository.Repository} implementations
* {@link CustomRepositoryImplementationDetector}, can be {@literal null}.
* {@link CustomRepositoryImplementationDetector}, can be {@literal null}.
*/
public ElasticsearchRepositoryBean(Bean<ElasticsearchOperations> operations, Set<Annotation> qualifiers,
Class<T> repositoryType, BeanManager beanManager, CustomRepositoryImplementationDetector detector) {
super(qualifiers, repositoryType, beanManager, Optional.of(detector));
Class<T> repositoryType, BeanManager beanManager, CustomRepositoryImplementationDetector detector) {
super(qualifiers, repositoryType, beanManager, detector);
Assert.notNull(operations, "Cannot create repository with 'null' for ElasticsearchOperations.");
this.elasticsearchOperationsBean = operations;
}
/* (non-Javadoc)
* @see org.springframework.data.repository.cdi.CdiRepositoryBean#create(javax.enterprise.context.spi.CreationalContext, java.lang.Class, java.util.Optional)
*/
@Override
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType,
Optional<Object> customImplementation) {
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType, Object customImplementation) {
ElasticsearchOperations elasticsearchOperations = getDependencyInstance(elasticsearchOperationsBean,
ElasticsearchOperations.class);
ElasticsearchRepositoryFactory factory = new ElasticsearchRepositoryFactory(elasticsearchOperations);
return customImplementation //
.map(o -> factory.getRepository(repositoryType, o)) //
.orElseGet(() -> factory.getRepository(repositoryType));
return new ElasticsearchRepositoryFactory(elasticsearchOperations).getRepository(repositoryType,
customImplementation);
}
/* (non-Javadoc)
* @see org.springframework.data.repository.cdi.CdiRepositoryBean#getScope()
*/
@Override
public Class<? extends Annotation> getScope() {
return elasticsearchOperationsBean.getScope();
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,19 +15,18 @@
*/
package org.springframework.data.elasticsearch.repository.cdi;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.UnsatisfiedResolutionException;
import javax.enterprise.inject.spi.AfterBeanDiscovery;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.ProcessBean;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.HashMap;
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;
@@ -43,7 +42,7 @@ import org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport;
*/
public class ElasticsearchRepositoryExtension extends CdiRepositoryExtensionSupport {
private final Map<Set<Annotation>, Bean<ElasticsearchOperations>> elasticsearchOperationsMap = new HashMap<>();
private final Map<Set<Annotation>, Bean<ElasticsearchOperations>> elasticsearchOperationsMap = new HashMap<Set<Annotation>, Bean<ElasticsearchOperations>>();
@SuppressWarnings("unchecked")
<T> void processBean(@Observes ProcessBean<T> processBean) {
@@ -68,16 +67,16 @@ public class ElasticsearchRepositoryExtension extends CdiRepositoryExtensionSupp
}
private <T> CdiRepositoryBean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers,
BeanManager beanManager) {
BeanManager beanManager) {
if (!this.elasticsearchOperationsMap.containsKey(qualifiers)) {
Bean<ElasticsearchOperations> elasticsearchOperationsBean = this.elasticsearchOperationsMap.get(qualifiers);
if (elasticsearchOperationsBean == null) {
throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.",
ElasticsearchOperations.class.getName(), qualifiers));
}
Bean<ElasticsearchOperations> elasticsearchOperationsBean = this.elasticsearchOperationsMap.get(qualifiers);
return new ElasticsearchRepositoryBean<>(elasticsearchOperationsBean, qualifiers, repositoryType, beanManager,
return new ElasticsearchRepositoryBean<T>(elasticsearchOperationsBean, qualifiers, repositoryType, beanManager,
getCustomImplementationDetector());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,16 +38,15 @@ import org.w3c.dom.Element;
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public class ElasticsearchRepositoryConfigExtension extends RepositoryConfigurationExtensionSupport {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.config.RepositoryConfigurationExtension#getRepositoryFactoryBeanClassName()
* @see org.springframework.data.repository.config.RepositoryConfigurationExtension#getRepositoryFactoryClassName()
*/
@Override
public String getRepositoryFactoryBeanClassName() {
public String getRepositoryFactoryClassName() {
return ElasticsearchRepositoryFactoryBean.class.getName();
}
@@ -60,7 +59,7 @@ public class ElasticsearchRepositoryConfigExtension extends RepositoryConfigurat
return "elasticsearch";
}
/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#postProcess(org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource)
*/
@@ -71,7 +70,7 @@ public class ElasticsearchRepositoryConfigExtension extends RepositoryConfigurat
builder.addPropertyReference("elasticsearchOperations", attributes.getString("elasticsearchTemplateRef"));
}
/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.config.RepositoryConfigurationExtensionSupport#postProcess(org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.data.repository.config.XmlRepositoryConfigurationSource)
*/
@@ -88,7 +87,7 @@ public class ElasticsearchRepositoryConfigExtension extends RepositoryConfigurat
*/
@Override
protected Collection<Class<? extends Annotation>> getIdentifyingAnnotations() {
return Collections.<Class<? extends Annotation>> singleton(Document.class);
return Collections.<Class<? extends Annotation>>singleton(Document.class);
}
/*
@@ -97,6 +96,6 @@ public class ElasticsearchRepositoryConfigExtension extends RepositoryConfigurat
*/
@Override
protected Collection<Class<?>> getIdentifyingTypes() {
return Arrays.<Class<?>> asList(ElasticsearchRepository.class, ElasticsearchCrudRepository.class);
return Arrays.<Class<?>>asList(ElasticsearchRepository.class, ElasticsearchCrudRepository.class);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.data.elasticsearch.repository.query;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
@@ -34,7 +33,6 @@ import org.springframework.data.util.StreamUtils;
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Kevin Leturc
* @author Mark Paluch
*/
public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery {
@@ -60,8 +58,8 @@ public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery
return elasticsearchOperations.queryForPage(query, queryMethod.getEntityInformation().getJavaType());
} else if (queryMethod.isStreamQuery()) {
Class<?> entityType = queryMethod.getEntityInformation().getJavaType();
if (query.getPageable().isUnpaged()) {
query.setPageable(PageRequest.of(0, 20));
if (query.getPageable() == null) {
query.setPageable(new PageRequest(0, 20));
}
return StreamUtils.createStreamFromIterator((CloseableIterator<Object>) elasticsearchOperations.stream(query, entityType));
@@ -69,7 +67,7 @@ public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery
} else if (queryMethod.isCollectionQuery()) {
if (accessor.getPageable() == null) {
int itemCount = (int) elasticsearchOperations.count(query, queryMethod.getEntityInformation().getJavaType());
query.setPageable(PageRequest.of(0, Math.max(1, itemCount)));
query.setPageable(new PageRequest(0, Math.max(1, itemCount)));
} else {
query.setPageable(accessor.getPageable());
}
@@ -85,9 +83,9 @@ public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery
Object result = null;
if (queryMethod.isCollectionQuery()) {
if (accessor.getPageable().isUnpaged()) {
if (accessor.getPageable() == null) {
int itemCount = (int) elasticsearchOperations.count(query, queryMethod.getEntityInformation().getJavaType());
query.setPageable(PageRequest.of(0, Math.max(1, itemCount)));
query.setPageable(new PageRequest(0, Math.max(1, itemCount)));
} else {
query.setPageable(accessor.getPageable());
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@ import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.query.QueryMethod;
import org.springframework.util.StringUtils;
/**
* ElasticsearchQueryMethod
@@ -29,7 +30,6 @@ import org.springframework.data.repository.query.QueryMethod;
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Oliver Gierke
* @author Mark Paluch
*/
public class ElasticsearchQueryMethod extends QueryMethod {
@@ -45,6 +45,7 @@ public class ElasticsearchQueryMethod extends QueryMethod {
}
public String getAnnotatedQuery() {
return (String) AnnotationUtils.getValue(queryAnnotation, "value");
String query = (String) AnnotationUtils.getValue(queryAnnotation, "value");
return StringUtils.hasText(query) ? query : null;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,7 +19,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.convert.DateTimeConverters;
import org.springframework.data.elasticsearch.core.query.StringQuery;
@@ -31,7 +30,6 @@ import org.springframework.util.Assert;
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQuery {
@@ -52,8 +50,8 @@ public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQue
}
}
public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod, ElasticsearchOperations elasticsearchOperations,
String query) {
public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod,
ElasticsearchOperations elasticsearchOperations, String query) {
super(queryMethod, elasticsearchOperations);
Assert.notNull(query, "Query cannot be empty");
this.query = query;
@@ -67,7 +65,7 @@ public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQue
stringQuery.setPageable(accessor.getPageable());
return elasticsearchOperations.queryForPage(stringQuery, queryMethod.getEntityInformation().getJavaType());
} else if (queryMethod.isCollectionQuery()) {
if (accessor.getPageable().isPaged()) {
if (accessor.getPageable() != null) {
stringQuery.setPageable(accessor.getPageable());
}
return elasticsearchOperations.queryForList(stringQuery, queryMethod.getEntityInformation().getJavaType());
@@ -23,25 +23,15 @@ import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.index.query.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.*;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.query.DeleteQuery;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.MoreLikeThisQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.util.Assert;
@@ -54,31 +44,31 @@ import org.springframework.util.Assert;
* @author Ryan Henszey
* @author Kevin Leturc
* @author Mark Paluch
* @author Christoph Strobl
*/
public abstract class AbstractElasticsearchRepository<T, ID extends Serializable>
implements ElasticsearchRepository<T, ID> {
public abstract class AbstractElasticsearchRepository<T, ID extends Serializable> implements
ElasticsearchRepository<T, ID> {
static final Logger LOGGER = LoggerFactory.getLogger(AbstractElasticsearchRepository.class);
protected ElasticsearchOperations elasticsearchOperations;
protected Class<T> entityClass;
protected ElasticsearchEntityInformation<T, ID> entityInformation;
public AbstractElasticsearchRepository() {}
public AbstractElasticsearchRepository() {
}
public AbstractElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations, "ElasticsearchOperations must not be null!");
this.setElasticsearchOperations(elasticsearchOperations);
}
public AbstractElasticsearchRepository(ElasticsearchEntityInformation<T, ID> metadata,
ElasticsearchOperations elasticsearchOperations) {
ElasticsearchOperations elasticsearchOperations) {
this(elasticsearchOperations);
Assert.notNull(metadata, "ElasticsearchEntityInformation must not be null!");
this.entityInformation = metadata;
setEntityClass(this.entityInformation.getJavaType());
try {
@@ -104,19 +94,19 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
}
@Override
public Optional<T> findById(ID id) {
public T findOne(ID id) {
GetQuery query = new GetQuery();
query.setId(stringIdRepresentation(id));
return Optional.ofNullable(elasticsearchOperations.queryForObject(query, getEntityClass()));
return elasticsearchOperations.queryForObject(query, getEntityClass());
}
@Override
public Iterable<T> findAll() {
int itemCount = (int) this.count();
if (itemCount == 0) {
return new PageImpl<>(Collections.<T> emptyList());
return new PageImpl<T>(Collections.<T>emptyList());
}
return this.findAll(PageRequest.of(0, Math.max(1, itemCount)));
return this.findAll(new PageRequest(0, Math.max(1, itemCount)));
}
@Override
@@ -129,17 +119,19 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
public Iterable<T> findAll(Sort sort) {
int itemCount = (int) this.count();
if (itemCount == 0) {
return new PageImpl<>(Collections.<T> emptyList());
return new PageImpl<T>(Collections.<T>emptyList());
}
SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withPageable(PageRequest.of(0, itemCount, sort)).build();
.withPageable(new PageRequest(0, itemCount, sort)).build();
return elasticsearchOperations.queryForPage(query, getEntityClass());
}
@Override
public Iterable<T> findAllById(Iterable<ID> ids) {
public Iterable<T> findAll(Iterable<ID> ids) {
Assert.notNull(ids, "ids can't be null.");
SearchQuery query = new NativeSearchQueryBuilder().withIds(stringIdsRepresentation(ids)).build();
SearchQuery query = new NativeSearchQueryBuilder()
.withIds(stringIdsRepresentation(ids))
.build();
return elasticsearchOperations.multiGet(query, getEntityClass());
}
@@ -160,7 +152,7 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
public <S extends T> List<S> save(List<S> entities) {
Assert.notNull(entities, "Cannot insert 'null' as a List.");
Assert.notEmpty(entities, "Cannot insert empty List.");
List<IndexQuery> queries = new ArrayList<>();
List<IndexQuery> queries = new ArrayList<IndexQuery>();
for (S s : entities) {
queries.add(createIndexQuery(s));
}
@@ -175,9 +167,9 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
}
@Override
public <S extends T> Iterable<S> saveAll(Iterable<S> entities) {
public <S extends T> Iterable<S> save(Iterable<S> entities) {
Assert.notNull(entities, "Cannot insert 'null' as a List.");
List<IndexQuery> queries = new ArrayList<>();
List<IndexQuery> queries = new ArrayList<IndexQuery>();
for (S s : entities) {
queries.add(createIndexQuery(s));
}
@@ -187,8 +179,8 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
}
@Override
public boolean existsById(ID id) {
return findById(id) != null;
public boolean exists(ID id) {
return findOne(id) != null;
}
@Override
@@ -196,9 +188,9 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).build();
int count = (int) elasticsearchOperations.count(searchQuery, getEntityClass());
if (count == 0) {
return new PageImpl<>(Collections.<T> emptyList());
return new PageImpl<T>(Collections.<T>emptyList());
}
searchQuery.setPageable(PageRequest.of(0, count));
searchQuery.setPageable(new PageRequest(0, count));
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
}
@@ -227,7 +219,7 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
}
@Override
public void deleteById(ID id) {
public void delete(ID id) {
Assert.notNull(id, "Cannot delete entity with id 'null'.");
elasticsearchOperations.delete(entityInformation.getIndexName(), entityInformation.getType(),
stringIdRepresentation(id));
@@ -237,12 +229,12 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
@Override
public void delete(T entity) {
Assert.notNull(entity, "Cannot delete 'null' entity.");
deleteById(extractIdFromBean(entity));
delete(extractIdFromBean(entity));
elasticsearchOperations.refresh(entityInformation.getIndexName());
}
@Override
public void deleteAll(Iterable<? extends T> entities) {
public void delete(Iterable<? extends T> entities) {
Assert.notNull(entities, "Cannot delete 'null' list.");
for (T entity : entities) {
delete(entity);
@@ -289,7 +281,6 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
return resolveReturnedClassFromGenericType(clazz.getSuperclass());
}
@Override
public Class<T> getEntityClass() {
if (!isEntityClassSet()) {
try {
@@ -316,12 +307,15 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
}
protected ID extractIdFromBean(T entity) {
return entityInformation.getId(entity).orElse(null);
if (entityInformation != null) {
return entityInformation.getId(entity);
}
return null;
}
private List<String> stringIdsRepresentation(Iterable<ID> ids) {
Assert.notNull(ids, "ids can't be null.");
List<String> stringIds = new ArrayList<>();
List<String> stringIds = new ArrayList<String>();
for (ID id : ids) {
stringIds.add(stringIdRepresentation(id));
}
@@ -331,10 +325,16 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
protected abstract String stringIdRepresentation(ID id);
private Long extractVersionFromBean(T entity) {
return entityInformation.getVersion(entity);
if (entityInformation != null) {
return entityInformation.getVersion(entity);
}
return null;
}
private String extractParentIdFromBean(T entity) {
return entityInformation.getParentId(entity);
if (entityInformation != null) {
return entityInformation.getParentId(entity);
}
return null;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,8 @@
*/
package org.springframework.data.elasticsearch.repository.support;
import java.io.Serializable;
import org.springframework.data.repository.core.EntityInformation;
/**
@@ -22,9 +24,8 @@ import org.springframework.data.repository.core.EntityInformation;
* @param <ID>
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Christoph Strobl
*/
public interface ElasticsearchEntityInformation<T, ID> extends EntityInformation<T, ID> {
public interface ElasticsearchEntityInformation<T, ID extends Serializable> extends EntityInformation<T, ID> {
String getIdAttribute();
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,14 +15,15 @@
*/
package org.springframework.data.elasticsearch.repository.support;
import java.io.Serializable;
/**
* ElasticsearchEntityInformationCreator
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Christoph Strobl
*/
public interface ElasticsearchEntityInformationCreator {
<T, ID> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass);
<T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass);
}
@@ -15,6 +15,8 @@
*/
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;
@@ -27,7 +29,6 @@ import org.springframework.util.Assert;
* @author Mohsin Husen
* @author Oliver Gierke
* @author Mark Paluch
* @author Christoph Strobl
*/
public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchEntityInformationCreator {
@@ -35,22 +36,22 @@ public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchE
public ElasticsearchEntityInformationCreatorImpl(
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
Assert.notNull(mappingContext, "MappingContext must not be null!");
this.mappingContext = mappingContext;
}
@Override
@SuppressWarnings("unchecked")
public <T, ID> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
public <T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
ElasticsearchPersistentEntity<T> persistentEntity = (ElasticsearchPersistentEntity<T>) mappingContext
.getRequiredPersistentEntity(domainClass);
.getPersistentEntity(domainClass);
Assert.notNull(persistentEntity, String.format("Unable to obtain mapping metadata for %s!", domainClass));
Assert.notNull(persistentEntity.getIdProperty(), String.format("No id property found for %s!", domainClass));
return new MappingElasticsearchEntityInformation<>(persistentEntity);
return new MappingElasticsearchEntityInformation<T, ID>(persistentEntity);
}
}
@@ -15,11 +15,10 @@
*/
package org.springframework.data.elasticsearch.repository.support;
import static org.springframework.data.querydsl.QuerydslUtils.*;
import static org.springframework.data.querydsl.QueryDslUtils.*;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Optional;
import java.util.UUID;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
@@ -27,14 +26,12 @@ import org.springframework.data.elasticsearch.repository.query.ElasticsearchPart
import org.springframework.data.elasticsearch.repository.query.ElasticsearchQueryMethod;
import org.springframework.data.elasticsearch.repository.query.ElasticsearchStringQuery;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.core.NamedQueries;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.data.repository.query.EvaluationContextProvider;
import org.springframework.data.repository.query.QueryLookupStrategy;
import org.springframework.data.repository.query.QueryLookupStrategy.Key;
import org.springframework.data.repository.query.RepositoryQuery;
import org.springframework.util.Assert;
@@ -46,7 +43,6 @@ import org.springframework.util.Assert;
* @author Ryan Henszey
* @author Gad Akuka
* @author Mark Paluch
* @author Christoph Strobl
*/
public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport {
@@ -54,24 +50,23 @@ public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport {
private final ElasticsearchEntityInformationCreator entityInformationCreator;
public ElasticsearchRepositoryFactory(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations, "ElasticsearchOperations must not be null!");
this.elasticsearchOperations = elasticsearchOperations;
this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(
elasticsearchOperations.getElasticsearchConverter().getMappingContext());
this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(elasticsearchOperations
.getElasticsearchConverter().getMappingContext());
}
@Override
public <T, ID> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
public <T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
return entityInformationCreator.getEntityInformation(domainClass);
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
@SuppressWarnings({"rawtypes", "unchecked"})
protected Object getTargetRepository(RepositoryInformation metadata) {
return getTargetRepositoryViaReflection(metadata, getEntityInformation(metadata.getDomainType()),
elasticsearchOperations);
return getTargetRepositoryViaReflection(metadata,getEntityInformation(metadata.getDomainType()), elasticsearchOperations);
}
@Override
@@ -79,31 +74,29 @@ public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport {
if (isQueryDslRepository(metadata.getRepositoryInterface())) {
throw new IllegalArgumentException("QueryDsl Support has not been implemented yet.");
}
if (Integer.class.isAssignableFrom(metadata.getIdType()) || Long.class.isAssignableFrom(metadata.getIdType())
if (Integer.class.isAssignableFrom(metadata.getIdType())
|| Long.class.isAssignableFrom(metadata.getIdType())
|| Double.class.isAssignableFrom(metadata.getIdType())) {
return NumberKeyedRepository.class;
} else if (metadata.getIdType() == String.class) {
return SimpleElasticsearchRepository.class;
} else if (metadata.getIdType() == UUID.class) {
return UUIDElasticsearchRepository.class;
} else {
throw new IllegalArgumentException("Unsupported ID type " + metadata.getIdType());
throw new IllegalArgumentException("Unsuppored ID type " + metadata.getIdType());
}
}
private static boolean isQueryDslRepository(Class<?> repositoryInterface) {
return QUERY_DSL_PRESENT && QuerydslPredicateExecutor.class.isAssignableFrom(repositoryInterface);
return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface);
}
@Override
protected Optional<QueryLookupStrategy> getQueryLookupStrategy(Key key,
EvaluationContextProvider evaluationContextProvider) {
return Optional.of(new ElasticsearchQueryLookupStrategy());
protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key) {
return new ElasticsearchQueryLookupStrategy();
}
private class ElasticsearchQueryLookupStrategy implements QueryLookupStrategy {
/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryLookupStrategy#resolveQuery(java.lang.reflect.Method, org.springframework.data.repository.core.RepositoryMetadata, org.springframework.data.projection.ProjectionFactory, org.springframework.data.repository.core.NamedQueries)
*/
@@ -36,15 +36,6 @@ public class ElasticsearchRepositoryFactoryBean<T extends Repository<S, ID>, S,
private ElasticsearchOperations operations;
/**
* Creates a new {@link ElasticsearchRepositoryFactoryBean} for the given repository interface.
*
* @param repositoryInterface must not be {@literal null}.
*/
public ElasticsearchRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
super(repositoryInterface);
}
/**
* Configures the {@link ElasticsearchOperations} to be used to create Elasticsearch repositories.
*
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,8 +15,10 @@
*/
package org.springframework.data.elasticsearch.repository.support;
import java.util.Optional;
import java.io.Serializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.repository.core.support.PersistentEntityInformation;
@@ -32,78 +34,68 @@ import org.springframework.util.Assert;
* @author Mohsin Husen
* @author Ryan Henszey
* @author Oliver Gierke
* @author Mark Paluch
* @author Christoph Strobl
*/
public class MappingElasticsearchEntityInformation<T, ID> extends PersistentEntityInformation<T, ID>
public class MappingElasticsearchEntityInformation<T, ID extends Serializable> extends PersistentEntityInformation<T, ID>
implements ElasticsearchEntityInformation<T, ID> {
private static final Logger logger = LoggerFactory.getLogger(MappingElasticsearchEntityInformation.class);
private final ElasticsearchPersistentEntity<T> entityMetadata;
private final String indexName;
private final String type;
public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity<T> entity) {
this(entity, entity.getIndexName(), entity.getIndexType());
this(entity, null, null);
}
public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity<T> entity, String indexName, String type) {
super(entity);
Assert.notNull(indexName, "IndexName must not be null!");
Assert.notNull(type, "IndexType must not be null!");
this.entityMetadata = entity;
this.indexName = indexName;
this.type = type;
}
@Override
public String getIdAttribute() {
ElasticsearchPersistentProperty property = entityMetadata.getIdProperty()
.orElseThrow(() -> new IllegalArgumentException(String.format(
"Unable to identify 'id' property in class %s. Make sure the 'id' property is annotated with @Id or named as 'id' or 'documentId'",
entityMetadata.getType().getSimpleName())));
return property.getFieldName();
Assert.notNull(entityMetadata.getIdProperty(), "Unable to identify 'id' property in class "
+ entityMetadata.getType().getSimpleName()
+ ". Make sure the 'id' property is annotated with @Id or named as 'id' or 'documentId' ");
return entityMetadata.getIdProperty().getFieldName();
}
@Override
public String getIndexName() {
return indexName;
return indexName != null ? indexName : entityMetadata.getIndexName();
}
@Override
public String getType() {
return type;
return type != null ? type : entityMetadata.getIndexType();
}
@Override
public Long getVersion(T entity) {
Optional<ElasticsearchPersistentProperty> versionProperty = entityMetadata.getVersionProperty();
ElasticsearchPersistentProperty versionProperty = entityMetadata.getVersionProperty();
try {
return (Long) versionProperty //
.flatMap(property -> entityMetadata.getPropertyAccessor(entity).getProperty(property)) //
.orElse(null);
if (versionProperty != null) {
return (Long) entityMetadata.getPropertyAccessor(entity).getProperty(versionProperty);
}
} catch (Exception e) {
throw new IllegalStateException("failed to load version field", e);
}
return null;
}
@Override
public String getParentId(T entity) {
Optional<ElasticsearchPersistentProperty> parentProperty = entityMetadata.getParentIdProperty();
ElasticsearchPersistentProperty parentProperty = entityMetadata.getParentIdProperty();
try {
return (String) parentProperty //
.flatMap(property -> entityMetadata.getPropertyAccessor(entity).getProperty(property)) //
.orElse(null);
if (parentProperty != null) {
return (String) entityMetadata.getPropertyAccessor(entity).getProperty(parentProperty);
}
} catch (Exception e) {
throw new IllegalStateException("failed to load parent ID: " + e, e);
}
return null;
}
}
@@ -1,47 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.repository.support;
import java.util.UUID;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
/**
* Elasticsearch specific repository implementation. Likely to be used as target within
* {@link ElasticsearchRepositoryFactory}
*
* @author Gad Akuka
*/
public class UUIDElasticsearchRepository<T> extends AbstractElasticsearchRepository<T, UUID> {
public UUIDElasticsearchRepository() {
super();
}
public UUIDElasticsearchRepository(ElasticsearchEntityInformation<T, UUID> metadata,
ElasticsearchOperations elasticsearchOperations) {
super(metadata, elasticsearchOperations);
}
public UUIDElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
super(elasticsearchOperations);
}
@Override
protected String stringIdRepresentation(UUID id) {
return (id != null) ? id.toString() : null;
}
}
@@ -1 +0,0 @@
org.springframework.data.repository.core.support.RepositoryFactorySupport=org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactory
-17
View File
@@ -1,23 +1,6 @@
Spring Data Elasticsearch Changelog
===================================
Changes in version 3.0.0.M3 (2017-05-09)
----------------------------------------
* DATAES-352 - Adapt to API changes in CrudRepository.
* DATAES-350 - Adapt to moved CustomConversions to Spring Data Commons.
* DATAES-344 - Release 3.0 M3 (Kay).
Changes in version 2.0.10.RELEASE (2017-04-19)
----------------------------------------------
* DATAES-347 - Release 2.0.10 (Hopper SR10).
Changes in version 2.1.3.RELEASE (2017-04-19)
---------------------------------------------
* DATAES-346 - Release 2.1.3 (Ingalls SR3).
Changes in version 2.0.9.RELEASE (2017-04-19)
---------------------------------------------
* DATAES-336 - Release 2.0.9 (Hopper SR9).
+1 -1
View File
@@ -1,4 +1,4 @@
Spring Data Elasticsearch 3.0 M3
Spring Data Elasticsearch 2.0.9
Copyright (c) [2013-2016] Pivotal Software, Inc.
This product is licensed to you under the Apache License, Version 2.0 (the "License").
@@ -34,7 +34,7 @@
description=Groovy scripting integration for Elasticsearch
#
# 'version': plugin's version
version=2.4.0
version=2.2.0
#
# 'name': the plugin name
name=lang-groovy
@@ -68,7 +68,7 @@ java.version=1.7
# elasticsearch release. This version is checked when the plugin
# is loaded so Elasticsearch will refuse to start in the presence of
# plugins with the incorrect elasticsearch.version.
elasticsearch.version=2.4.0
elasticsearch.version=2.2.0
#
### deprecated elements for jvm plugins :
#
@@ -0,0 +1,57 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
grant {
// needed to generate runtime classes
permission java.lang.RuntimePermission "createClassLoader";
// needed by IndyInterface
permission java.lang.RuntimePermission "getClassLoader";
// needed by groovy engine
permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect";
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
// needed by GroovyScriptEngineService to close its classloader (why?)
permission java.lang.RuntimePermission "closeClassLoader";
// Allow executing groovy scripts with codesource of /untrusted
permission groovy.security.GroovyCodeSourcePermission "/untrusted";
// Standard set of classes
permission org.elasticsearch.script.ClassPermission "<<STANDARD>>";
// groovy runtime
permission org.elasticsearch.script.ClassPermission "groovy.grape.GrabAnnotationTransformation";
permission org.elasticsearch.script.ClassPermission "groovy.json.JsonOutput";
permission org.elasticsearch.script.ClassPermission "groovy.lang.Binding";
permission org.elasticsearch.script.ClassPermission "groovy.lang.GroovyObject";
permission org.elasticsearch.script.ClassPermission "groovy.lang.GString";
permission org.elasticsearch.script.ClassPermission "groovy.lang.Script";
permission org.elasticsearch.script.ClassPermission "groovy.util.GroovyCollections";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.ast.builder.AstBuilderTransformation";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.reflection.ClassInfo";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.GStringImpl";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.powerassert.ValueRecorder";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.powerassert.AssertionRenderer";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.ScriptBytecodeAdapter";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.vmplugin.v7.IndyInterface";
permission org.elasticsearch.script.ClassPermission "sun.reflect.ConstructorAccessorImpl";
permission org.elasticsearch.script.ClassPermission "groovy.lang.Closure";
permission org.elasticsearch.script.ClassPermission "org.codehaus.groovy.runtime.GeneratedClosure";
permission org.elasticsearch.script.ClassPermission "groovy.lang.MetaClass";
permission org.elasticsearch.script.ClassPermission "groovy.lang.Range";
};
@@ -0,0 +1,80 @@
# Elasticsearch plugin descriptor file
# This file must exist as 'plugin-descriptor.properties' at
# the root directory of all plugins.
#
# A plugin can be 'site', 'jvm', or both.
#
### example site plugin for "foo":
#
# foo.zip <-- zip file for the plugin, with this structure:
# _site/ <-- the contents that will be served
# plugin-descriptor.properties <-- example contents below:
#
# site=true
# description=My cool plugin
# version=1.0
#
### example jvm plugin for "foo"
#
# foo.zip <-- zip file for the plugin, with this structure:
# <arbitrary name1>.jar <-- classes, resources, dependencies
# <arbitrary nameN>.jar <-- any number of jars
# plugin-descriptor.properties <-- example contents below:
#
# jvm=true
# classname=foo.bar.BazPlugin
# description=My cool plugin
# version=2.0.0-rc1
# elasticsearch.version=2.0
# java.version=1.7
#
### mandatory elements for all plugins:
#
# 'description': simple summary of the plugin
description=Groovy scripting integration for Elasticsearch
#
# 'version': plugin's version
version=2.3.3
#
# 'name': the plugin name
name=lang-groovy
### mandatory elements for site plugins:
#
# 'site': set to true to indicate contents of the _site/
# directory in the root of the plugin should be served.
site=false
#
### mandatory elements for jvm plugins :
#
# 'jvm': true if the 'classname' class should be loaded
# from jar files in the root directory of the plugin.
# Note that only jar files in the root directory are
# added to the classpath for the plugin! If you need
# other resources, package them into a resources jar.
jvm=true
#
# 'classname': the name of the class to load, fully-qualified.
classname=org.elasticsearch.script.groovy.GroovyPlugin
#
# 'java.version' version of java the code is built against
# use the system property java.specification.version
# version string must be a sequence of nonnegative decimal integers
# separated by "."'s and may have leading zeros
java.version=1.7
#
# 'elasticsearch.version' version of elasticsearch compiled against
# You will have to release a new version of the plugin for each new
# elasticsearch release. This version is checked when the plugin
# is loaded so Elasticsearch will refuse to start in the presence of
# plugins with the incorrect elasticsearch.version.
elasticsearch.version=2.3.3
#
### deprecated elements for jvm plugins :
#
# 'isolated': true if the plugin should have its own classloader.
# passing false is deprecated, and only intended to support plugins
# that have hard dependencies against each other. If this is
# not specified, then the plugin is isolated by default.
isolated=true
#
@@ -24,6 +24,8 @@ grant {
permission java.lang.RuntimePermission "getClassLoader";
// needed by groovy engine
permission java.lang.RuntimePermission "accessClassInPackage.sun.reflect";
// needed by GroovyScriptEngineService to close its classloader (why?)
permission java.lang.RuntimePermission "closeClassLoader";
// Allow executing groovy scripts with codesource of /untrusted
permission groovy.security.GroovyCodeSourcePermission "/untrusted";
@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,16 +33,17 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Mohsin Husen
* @author Christoph Strobl
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/repository-test-nested-object.xml")
public class InnerObjectTests {
@Autowired private SampleElasticSearchBookRepository bookRepository;
@Autowired
private SampleElasticSearchBookRepository bookRepository;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
@@ -66,6 +67,6 @@ public class InnerObjectTests {
// when
bookRepository.save(book);
// then
assertThat(bookRepository.findById(id), is(notNullValue()));
assertThat(bookRepository.findOne(id), is(notNullValue()));
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,11 +15,13 @@
*/
package org.springframework.data.elasticsearch;
import static org.apache.commons.lang.RandomStringUtils.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.apache.commons.lang.RandomStringUtils.randomNumeric;
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.CoreMatchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.*;
import static org.junit.Assert.assertThat;
import java.util.ArrayList;
import java.util.Arrays;
@@ -46,6 +48,7 @@ import org.springframework.data.elasticsearch.entities.Car;
import org.springframework.data.elasticsearch.entities.GirlFriend;
import org.springframework.data.elasticsearch.entities.Person;
import org.springframework.data.elasticsearch.entities.PersonMultipleLevelNested;
import org.springframework.data.geo.Point;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -81,7 +84,7 @@ public class NestedObjectTests {
@Test
public void shouldIndexInitialLevelNestedObject() {
final List<Car> cars = new ArrayList<>();
final List<Car> cars = new ArrayList<Car>();
final Car saturn = new Car();
saturn.setName("Saturn");
@@ -113,7 +116,7 @@ public class NestedObjectTests {
bar.setName("Bar");
bar.setCar(Arrays.asList(car));
final List<IndexQuery> indexQueries = new ArrayList<>();
final List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
final IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(foo.getId());
indexQuery1.setObject(foo);
@@ -162,7 +165,7 @@ public class NestedObjectTests {
//when
elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class);
elasticsearchTemplate.bulkIndex(indexQueries);
// then
// then
final Map mapping = elasticsearchTemplate.getMapping(PersonMultipleLevelNested.class);
@@ -250,7 +253,7 @@ public class NestedObjectTests {
indexQuery2.setId(person2.getId());
indexQuery2.setObject(person2);
final List<IndexQuery> indexQueries = new ArrayList<>();
final List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
indexQueries.add(indexQuery1);
indexQueries.add(indexQuery2);
@@ -260,7 +263,7 @@ public class NestedObjectTests {
@Test
public void shouldSearchBooksForPersonInitialLevelNestedType() {
final List<Car> cars = new ArrayList<>();
final List<Car> cars = new ArrayList<Car>();
final Car saturn = new Car();
saturn.setName("Saturn");
@@ -309,7 +312,7 @@ public class NestedObjectTests {
bar.setName("Bar");
bar.setCar(Arrays.asList(car));
final List<IndexQuery> indexQueries = new ArrayList<>();
final List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
final IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(foo.getId());
indexQuery1.setObject(foo);
@@ -348,16 +351,16 @@ public class NestedObjectTests {
book2.setId(randomNumeric(5));
book2.setName("testBook2");
final Map<Integer, Collection<String>> map1 = new HashMap<>();
final Map<Integer, Collection<String>> map1 = new HashMap<Integer, Collection<String>>();
map1.put(1, Arrays.asList("test1", "test2"));
final Map<Integer, Collection<String>> map2 = new HashMap<>();
final Map<Integer, Collection<String>> map2 = new HashMap<Integer, Collection<String>>();
map2.put(1, Arrays.asList("test3", "test4"));
book1.setBuckets(map1);
book2.setBuckets(map2);
final List<IndexQuery> indexQueries = new ArrayList<>();
final List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
final IndexQuery indexQuery1 = new IndexQuery();
indexQuery1.setId(book1.getId());
indexQuery1.setObject(book1);
@@ -1,140 +0,0 @@
/*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch;
import java.util.UUID;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
/**
* @author Gad Akuka
*/
@Document(indexName = "test-index", type = "test-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleEntityUUIDKeyed {
@Id
private UUID id;
private String type;
private String message;
private int rate;
@ScriptedField
private Long scriptedRate;
private boolean available;
private String highlightedMessage;
@Version
private Long version;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public Long getScriptedRate() {
return scriptedRate;
}
public void setScriptedRate(Long scriptedRate) {
this.scriptedRate = scriptedRate;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
public String getHighlightedMessage() {
return highlightedMessage;
}
public void setHighlightedMessage(String highlightedMessage) {
this.highlightedMessage = highlightedMessage;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SampleEntityUUIDKeyed)) {
return false;
}
if (this == obj) {
return true;
}
SampleEntityUUIDKeyed rhs = (SampleEntityUUIDKeyed) obj;
return new EqualsBuilder().append(this.id, rhs.id).append(this.type, rhs.type).append(this.message, rhs.message)
.append(this.rate, rhs.rate).append(this.available, rhs.available).append(this.version, rhs.version).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(id).append(type).append(message).append(rate).append(available).append(version)
.toHashCode();
}
@Override
public String toString() {
return "SampleEntity{" +
"id='" + id + '\'' +
", type='" + type + '\'' +
", message='" + message + '\'' +
", rate=" + rate +
", available=" + available +
", highlightedMessage='" + highlightedMessage + '\'' +
", version=" + version +
'}';
}
}
@@ -31,7 +31,7 @@ public class Utils {
return (NodeClient) nodeBuilder().settings(Settings.builder()
.put("http.enabled", "false")
.put("path.data", "target/elasticsearchTestData")
.put("path.home", "src/test/resources/test-home-dir"))
.put("path.home", "target/test-home-dir"))
.clusterName(UUID.randomUUID().toString()).local(true).node()
.client();
}
@@ -1,100 +1,96 @@
/*
* Copyright 2013-15 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.config;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.Utils;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.data.elasticsearch.repositories.sample.SampleElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.repository.Repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Kevin Leturc
* @author Gad Akuka
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class EnableElasticsearchRepositoriesTests implements ApplicationContextAware {
ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Configuration
@EnableElasticsearchRepositories(basePackages = {"org.springframework.data.elasticsearch.repositories.sample",
"org.springframework.data.elasticsearch.config"})
static class Config {
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(Utils.getNodeClient());
}
}
@Autowired
private SampleElasticsearchRepository repository;
@Autowired(required = false)
private SampleRepository nestedRepository;
interface SampleRepository extends Repository<SampleEntity, Long> {};
@Test
public void bootstrapsRepository() {
assertThat(repository, is(notNullValue()));
}
@Test
public void shouldScanSelectedPackage() {
//given
//when
String[] beanNamesForType = context.getBeanNamesForType(ElasticsearchRepository.class);
//then
assertThat(beanNamesForType.length, is(2));
assertTrue(Arrays.asList(beanNamesForType).contains("sampleElasticsearchRepository"));
assertTrue(Arrays.asList(beanNamesForType).contains("sampleUUIDKeyedElasticsearchRepository"));
}
@Test
public void hasNotNestedRepository() {
assertNull(nestedRepository);
}
}
/*
* Copyright 2013-15 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.config;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.Utils;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.data.elasticsearch.repositories.sample.SampleElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.repository.Repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Kevin Leturc
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class EnableElasticsearchRepositoriesTests implements ApplicationContextAware {
ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Configuration
@EnableElasticsearchRepositories(basePackages = {"org.springframework.data.elasticsearch.repositories.sample",
"org.springframework.data.elasticsearch.config"})
static class Config {
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(Utils.getNodeClient());
}
}
@Autowired
private SampleElasticsearchRepository repository;
@Autowired(required = false)
private SampleRepository nestedRepository;
interface SampleRepository extends Repository<SampleEntity, Long> {};
@Test
public void bootstrapsRepository() {
assertThat(repository, is(notNullValue()));
}
@Test
public void shouldScanSelectedPackage() {
//given
//when
String[] beanNamesForType = context.getBeanNamesForType(ElasticsearchRepository.class);
//then
assertThat(beanNamesForType.length, is(1));
assertThat(beanNamesForType[0], is("sampleElasticsearchRepository"));
}
@Test
public void hasNotNestedRepository() {
assertNull(nestedRepository);
}
}
@@ -15,8 +15,6 @@
*/
package org.springframework.data.elasticsearch.config;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -31,6 +29,8 @@ import org.springframework.data.repository.Repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertNotNull;
/**
* @author Kevin Leturc
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,22 +19,15 @@ 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.HashMap;
import java.util.List;
import java.util.Map;
import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.query.AliasBuilder;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -55,7 +48,7 @@ public class AliasTests {
@Before
public void before() {
Map<String, Object> settings = new HashMap<>();
Map<String, Object> settings = new HashMap<String, Object>();
settings.put("index.refresh_interval", "-1");
settings.put("index.number_of_replicas", "0");
settings.put("index.number_of_shards", "2");
@@ -20,8 +20,8 @@ import java.util.LinkedList;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
/**
* @author Artur Konczak
@@ -47,7 +47,7 @@ public class CustomResultMapper implements ResultsMapper {
}
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,9 +23,7 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.elasticsearch.action.get.GetResponse;
@@ -33,18 +31,13 @@ import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.internal.InternalSearchHitField;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.entities.Car;
@@ -53,7 +46,6 @@ import com.fasterxml.jackson.databind.util.ArrayIterator;
/**
* @author Artur Konczak
* @author Mohsin Husen
* @author Mark Paluch
*/
public class DefaultResultMapperTests {
@@ -68,32 +60,6 @@ public class DefaultResultMapperTests {
resultMapper = new DefaultResultMapper(new SimpleElasticsearchMappingContext());
}
@Test
public void shouldMapAggregationsToPage() {
//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);
Aggregation aggregationToReturn = createCarAggregation();
Aggregations aggregations = mock(Aggregations.class);
Iterator<Aggregation> iter = Collections.singletonList(aggregationToReturn).iterator();
when(aggregations.iterator()).thenReturn(iter).thenReturn(iter);
when(aggregations.get("engine")).thenReturn(aggregationToReturn);
when(response.getAggregations()).thenReturn(aggregations);
//When
AggregatedPage<Car> page = (AggregatedPage<Car>) resultMapper.mapResults(response, Car.class, Pageable.unpaged());
//Then
page.hasFacets();
assertThat(page.hasAggregations(), is(true));
assertThat(page.getAggregation("engine").getName(), is("Diesel"));
}
@Test
public void shouldMapSearchRequestToPage() {
//Given
@@ -104,7 +70,7 @@ public class DefaultResultMapperTests {
when(response.getHits()).thenReturn(searchHits);
//When
Page<Car> page = resultMapper.mapResults(response, Car.class, Pageable.unpaged());
Page<Car> page = resultMapper.mapResults(response, Car.class, null);
//Then
assertThat(page.hasContent(), is(true));
@@ -122,7 +88,7 @@ public class DefaultResultMapperTests {
when(response.getHits()).thenReturn(searchHits);
//When
Page<Car> page = resultMapper.mapResults(response, Car.class, Pageable.unpaged());
Page<Car> page = resultMapper.mapResults(response, Car.class, null);
//Then
assertThat(page.hasContent(), is(true));
@@ -144,29 +110,23 @@ public class DefaultResultMapperTests {
assertThat(result.getModel(), is("Grat"));
assertThat(result.getName(), is("Ford"));
}
/**
* @see DATAES-281.
*/
@Test
public void setsIdentifierOnImmutableType() {
GetResponse response = mock(GetResponse.class);
when(response.getSourceAsString()).thenReturn("{}");
when(response.getId()).thenReturn("identifier");
ImmutableEntity result = resultMapper.mapResult(response, ImmutableEntity.class);
assertThat(result, is(notNullValue()));
assertThat(result.getId(), is("identifier"));
}
private Aggregation createCarAggregation() {
Aggregation aggregation = mock(Terms.class);
when(aggregation.getName()).thenReturn("Diesel");
return aggregation;
}
private SearchHit createCarHit(String name, String model) {
SearchHit hit = mock(SearchHit.class);
when(hit.sourceAsString()).thenReturn(createJsonCar(name, model));
@@ -189,12 +149,12 @@ public class DefaultResultMapperTests {
}
private Map<String, SearchHitField> createCarFields(String name, String model) {
Map<String, SearchHitField> result = new HashMap<>();
Map<String, SearchHitField> result = new HashMap<String, SearchHitField>();
result.put("name", new InternalSearchHitField("name", Arrays.<Object>asList(name)));
result.put("model", new InternalSearchHitField("model", Arrays.<Object>asList(model)));
return result;
}
@Document(indexName = "someIndex")
@NoArgsConstructor(force = true)
@Getter
@@ -15,7 +15,7 @@
*/
package org.springframework.data.elasticsearch.core;
import static org.elasticsearch.common.xcontent.XContentFactory.*;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,13 +21,7 @@ import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.elasticsearch.utils.IndexBuilder.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.*;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.get.MultiGetItemResponse;
@@ -47,33 +41,11 @@ 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.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.*;
import org.springframework.data.elasticsearch.ElasticsearchException;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.DeleteQuery;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilterBuilder;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.MoreLikeThisQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.ScriptField;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder;
import org.springframework.data.elasticsearch.entities.HetroEntity1;
import org.springframework.data.elasticsearch.entities.HetroEntity2;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.data.elasticsearch.entities.SampleMappingEntity;
import org.springframework.data.elasticsearch.entities.UseServerConfigurationEntity;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.data.elasticsearch.entities.*;
import org.springframework.data.util.CloseableIterator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -165,7 +137,7 @@ public class ElasticsearchTemplateTests {
@Test
public void shouldReturnObjectsForGivenIdsUsingMultiGet() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId).message("some message")
@@ -193,7 +165,7 @@ public class ElasticsearchTemplateTests {
@Test
public void shouldReturnObjectsForGivenIdsUsingMultiGetWithFields() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId)
@@ -221,7 +193,7 @@ public class ElasticsearchTemplateTests {
LinkedList<SampleEntity> sampleEntities = elasticsearchTemplate.multiGet(query, SampleEntity.class, new MultiGetResultMapper() {
@Override
public <T> LinkedList<T> mapResults(MultiGetResponse responses, Class<T> clazz) {
LinkedList<T> list = new LinkedList<>();
LinkedList<T> list = new LinkedList<T>();
for (MultiGetItemResponse response : responses.getResponses()) {
SampleEntity entity = new SampleEntity();
entity.setId(response.getResponse().getId());
@@ -259,7 +231,7 @@ public class ElasticsearchTemplateTests {
@Test
public void shouldDoBulkIndex() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId).message("some message")
@@ -303,7 +275,7 @@ public class ElasticsearchTemplateTests {
UpdateQuery updateQuery = new UpdateQueryBuilder().withId(documentId)
.withClass(SampleEntity.class).withIndexRequest(indexRequest).build();
List<UpdateQuery> queries = new ArrayList<>();
List<UpdateQuery> queries = new ArrayList<UpdateQuery>();
queries.add(updateQuery);
// when
@@ -398,7 +370,7 @@ public class ElasticsearchTemplateTests {
@Test
public void shouldSortResultsGivenSortCriteria() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId)
@@ -437,7 +409,7 @@ public class ElasticsearchTemplateTests {
@Test
public void shouldSortResultsGivenMultipleSortCriteria() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId)
@@ -511,7 +483,7 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class);
Map<String, Object> params = new HashMap<>();
Map<String, Object> params = new HashMap<String, Object>();
params.put("factor", 2);
// when
SearchQuery searchQuery = new NativeSearchQueryBuilder()
@@ -660,12 +632,12 @@ public class ElasticsearchTemplateTests {
// when
Page<String> page = elasticsearchTemplate.queryForPage(searchQuery, String.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<String> values = new ArrayList<>();
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<String> values = new ArrayList<String>();
for (SearchHit searchHit : response.getHits()) {
values.add((String) searchHit.field("message").value());
}
return new AggregatedPageImpl<>((List<T>) values);
return new PageImpl<T>((List<T>) values);
}
});
// then
@@ -754,7 +726,7 @@ public class ElasticsearchTemplateTests {
criteriaQuery.setPageable(new PageRequest(0, 10));
String scrollId = elasticsearchTemplate.scan(criteriaQuery, 1000, false);
List<SampleEntity> sampleEntities = new ArrayList<>();
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
boolean hasRecords = true;
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, SampleEntity.class);
@@ -781,7 +753,7 @@ public class ElasticsearchTemplateTests {
.withTypes(TYPE_NAME).withPageable(new PageRequest(0, 10)).build();
String scrollId = elasticsearchTemplate.scan(searchQuery, 1000, false);
List<SampleEntity> sampleEntities = new ArrayList<>();
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
boolean hasRecords = true;
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, SampleEntity.class);
@@ -814,13 +786,13 @@ public class ElasticsearchTemplateTests {
criteriaQuery.setPageable(new PageRequest(0, 10));
String scrollId = elasticsearchTemplate.scan(criteriaQuery, 5000, false);
List<SampleEntity> sampleEntities = new ArrayList<>();
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
boolean hasRecords = true;
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> result = new ArrayList<>();
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> result = new ArrayList<SampleEntity>();
for (SearchHit searchHit : response.getHits()) {
String message = searchHit.getFields().get("message").getValue();
SampleEntity sampleEntity = new SampleEntity();
@@ -830,7 +802,7 @@ public class ElasticsearchTemplateTests {
}
if (result.size() > 0) {
return new AggregatedPageImpl<>((List<T>) result);
return new PageImpl<T>((List<T>) result);
}
return null;
}
@@ -866,13 +838,13 @@ public class ElasticsearchTemplateTests {
.build();
String scrollId = elasticsearchTemplate.scan(searchQuery, 10000, false);
List<SampleEntity> sampleEntities = new ArrayList<>();
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
boolean hasRecords = true;
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 10000L, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> result = new ArrayList<>();
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> result = new ArrayList<SampleEntity>();
for (SearchHit searchHit : response.getHits()) {
String message = searchHit.getFields().get("message").getValue();
SampleEntity sampleEntity = new SampleEntity();
@@ -882,7 +854,7 @@ public class ElasticsearchTemplateTests {
}
if (result.size() > 0) {
return new AggregatedPageImpl<>((List<T>) result);
return new PageImpl<T>((List<T>) result);
}
return null;
}
@@ -915,13 +887,13 @@ public class ElasticsearchTemplateTests {
criteriaQuery.setPageable(new PageRequest(0, 10));
String scrollId = elasticsearchTemplate.scan(criteriaQuery, 5000, false);
List<SampleEntity> sampleEntities = new ArrayList<>();
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
boolean hasRecords = true;
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> chunk = new ArrayList<>();
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> chunk = new ArrayList<SampleEntity>();
for (SearchHit searchHit : response.getHits()) {
if (response.getHits().getHits().length <= 0) {
return null;
@@ -932,7 +904,7 @@ public class ElasticsearchTemplateTests {
chunk.add(user);
}
if (chunk.size() > 0) {
return new AggregatedPageImpl<>((List<T>) chunk);
return new PageImpl<T>((List<T>) chunk);
}
return null;
}
@@ -960,13 +932,13 @@ public class ElasticsearchTemplateTests {
.withTypes(TYPE_NAME).withPageable(new PageRequest(0, 10)).build();
String scrollId = elasticsearchTemplate.scan(searchQuery, 1000, false);
List<SampleEntity> sampleEntities = new ArrayList<>();
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
boolean hasRecords = true;
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> chunk = new ArrayList<>();
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> chunk = new ArrayList<SampleEntity>();
for (SearchHit searchHit : response.getHits()) {
if (response.getHits().getHits().length <= 0) {
return null;
@@ -977,7 +949,7 @@ public class ElasticsearchTemplateTests {
chunk.add(user);
}
if (chunk.size() > 0) {
return new AggregatedPageImpl<>((List<T>) chunk);
return new PageImpl<T>((List<T>) chunk);
}
return null;
}
@@ -1008,7 +980,7 @@ public class ElasticsearchTemplateTests {
criteriaQuery.setPageable(new PageRequest(0, 10));
String scrollId = elasticsearchTemplate.scan(criteriaQuery, 1000, false, SampleEntity.class);
List<SampleEntity> sampleEntities = new ArrayList<>();
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
boolean hasRecords = true;
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, SampleEntity.class);
@@ -1038,7 +1010,7 @@ public class ElasticsearchTemplateTests {
.withPageable(new PageRequest(0, 10)).build();
String scrollId = elasticsearchTemplate.scan(searchQuery, 1000, false, SampleEntity.class);
List<SampleEntity> sampleEntities = new ArrayList<>();
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
boolean hasRecords = true;
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, SampleEntity.class);
@@ -1070,7 +1042,7 @@ public class ElasticsearchTemplateTests {
criteriaQuery.setPageable(new PageRequest(0, 10));
CloseableIterator<SampleEntity> stream = elasticsearchTemplate.stream(criteriaQuery, SampleEntity.class);
List<SampleEntity> sampleEntities = new ArrayList<>();
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
while (stream.hasNext()) {
sampleEntities.add(stream.next());
}
@@ -1078,7 +1050,7 @@ public class ElasticsearchTemplateTests {
}
private static List<IndexQuery> createSampleEntitiesWithMessage(String message, int numberOfEntities) {
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
for (int i = 0; i < numberOfEntities; i++) {
String documentId = UUID.randomUUID().toString();
SampleEntity sampleEntity = new SampleEntity();
@@ -1097,7 +1069,7 @@ public class ElasticsearchTemplateTests {
@Test
public void shouldReturnListForGivenCriteria() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = SampleEntity.builder().id(documentId)
@@ -1271,8 +1243,8 @@ public class ElasticsearchTemplateTests {
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> chunk = new ArrayList<>();
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> chunk = new ArrayList<SampleEntity>();
for (SearchHit searchHit : response.getHits()) {
if (response.getHits().getHits().length <= 0) {
return null;
@@ -1284,7 +1256,7 @@ public class ElasticsearchTemplateTests {
chunk.add(user);
}
if (chunk.size() > 0) {
return new AggregatedPageImpl<>((List<T>) chunk);
return new PageImpl<T>((List<T>) chunk);
}
return null;
}
@@ -1338,15 +1310,15 @@ public class ElasticsearchTemplateTests {
// then
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> values = new ArrayList<>();
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> values = new ArrayList<SampleEntity>();
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 AggregatedPageImpl<>((List<T>) values);
return new PageImpl<T>((List<T>) values);
}
});
assertThat(page, is(notNullValue()));
@@ -1388,7 +1360,7 @@ public class ElasticsearchTemplateTests {
@Test
public void shouldReturnDocumentAboveMinimalScoreGivenQuery() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
indexQueries.add(buildIndex(SampleEntity.builder().id("1").message("ab").build()));
indexQueries.add(buildIndex(SampleEntity.builder().id("2").message("bc").build()));
@@ -1436,7 +1408,7 @@ public class ElasticsearchTemplateTests {
@Test
public void shouldDoBulkIndexWithoutId() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setMessage("some message");
@@ -1469,14 +1441,14 @@ public class ElasticsearchTemplateTests {
@Test
public void shouldIndexMapWithIndexNameAndTypeAtRuntime() {
//given
Map<String, Object> person1 = new HashMap<>();
Map<String, Object> person1 = new HashMap<String, Object>();
person1.put("userId", "1");
person1.put("email", "smhdiu@gmail.com");
person1.put("title", "Mr");
person1.put("firstName", "Mohsin");
person1.put("lastName", "Husen");
Map<String, Object> person2 = new HashMap<>();
Map<String, Object> person2 = new HashMap<String, Object>();
person2.put("userId", "2");
person2.put("email", "akonczak@gmail.com");
person2.put("title", "Mr");
@@ -1495,7 +1467,7 @@ public class ElasticsearchTemplateTests {
indexQuery2.setIndexName(INDEX_NAME);
indexQuery2.setType(TYPE_NAME);
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
indexQueries.add(indexQuery1);
indexQueries.add(indexQuery2);
@@ -1508,13 +1480,13 @@ public class ElasticsearchTemplateTests {
.withTypes(TYPE_NAME).withQuery(matchAllQuery()).build();
Page<Map> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, Map.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<Map> chunk = new ArrayList<>();
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<Map> chunk = new ArrayList<Map>();
for (SearchHit searchHit : response.getHits()) {
if (response.getHits().getHits().length <= 0) {
return null;
}
Map<String, Object> person = new HashMap<>();
Map<String, Object> person = new HashMap<String, Object>();
person.put("userId", searchHit.getSource().get("userId"));
person.put("email", searchHit.getSource().get("email"));
person.put("title", searchHit.getSource().get("title"));
@@ -1523,7 +1495,7 @@ public class ElasticsearchTemplateTests {
chunk.add(person);
}
if (chunk.size() > 0) {
return new AggregatedPageImpl<>((List<T>) chunk);
return new PageImpl<T>((List<T>) chunk);
}
return null;
}
@@ -2022,15 +1994,15 @@ public class ElasticsearchTemplateTests {
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withTypes("hetro").withIndices(INDEX_1_NAME, INDEX_2_NAME).build();
Page<ResultAggregator> page = elasticsearchTemplate.queryForPage(searchQuery, ResultAggregator.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<ResultAggregator> values = new ArrayList<>();
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<ResultAggregator> values = new ArrayList<ResultAggregator>();
for (SearchHit searchHit : response.getHits()) {
String id = String.valueOf(searchHit.getSource().get("id"));
String firstName = StringUtils.isNotEmpty((String) searchHit.getSource().get("firstName")) ? (String) searchHit.getSource().get("firstName") : "";
String lastName = StringUtils.isNotEmpty((String) searchHit.getSource().get("lastName")) ? (String) searchHit.getSource().get("lastName") : "";
values.add(new ResultAggregator(id, firstName, lastName));
}
return new AggregatedPageImpl<>((List<T>) values);
return new PageImpl<T>((List<T>) values);
}
});
@@ -2074,7 +2046,7 @@ public class ElasticsearchTemplateTests {
}
private List<IndexQuery> getIndexQueries(List<SampleEntity> sampleEntities) {
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
for (SampleEntity sampleEntity : sampleEntities) {
indexQueries.add(new IndexQueryBuilder().withId(sampleEntity.getId()).withObject(sampleEntity).build());
}
@@ -33,14 +33,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.builder.SampleInheritedEntityBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.entities.*;
import org.springframework.data.elasticsearch.entities.GeoEntity;
import org.springframework.data.elasticsearch.entities.Group;
import org.springframework.data.elasticsearch.entities.MinimalEntity;
import org.springframework.data.elasticsearch.entities.SampleInheritedEntity;
import org.springframework.data.elasticsearch.entities.SampleTransientEntity;
import org.springframework.data.elasticsearch.entities.SimpleRecursiveEntity;
import org.springframework.data.elasticsearch.entities.StockPrice;
import org.springframework.data.elasticsearch.entities.User;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -170,20 +164,4 @@ public class MappingBuilderTests {
assertThat(result, containsString("\"pointC\":{\"type\":\"geo_point\""));
assertThat(result, containsString("\"pointD\":{\"type\":\"geo_point\""));
}
/**
* DATAES-260 - StacOverflow when two reverse relationship.
*/
@Test
public void shouldHandleReverseRelationship() {
//given
elasticsearchTemplate.createIndex(User.class);
elasticsearchTemplate.putMapping(User.class);
elasticsearchTemplate.createIndex(Group.class);
elasticsearchTemplate.putMapping(Group.class);
//when
//then
}
}
@@ -15,12 +15,6 @@
*/
package org.springframework.data.elasticsearch.core.aggregation;
import static org.elasticsearch.action.search.SearchType.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.search.aggregations.AggregationBuilders.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.aggregations.Aggregations;
import org.junit.Before;
@@ -36,6 +30,12 @@ import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilde
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.action.search.SearchType.COUNT;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.search.aggregations.AggregationBuilders.terms;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Rizwan Idrees
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,6 +34,13 @@ import org.springframework.data.elasticsearch.entities.NonDocumentEntity;
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
@@ -54,7 +61,7 @@ public class ElasticsearchTemplateCompletionTests {
elasticsearchTemplate.refresh(CompletionEntity.class);
elasticsearchTemplate.putMapping(CompletionEntity.class);
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
indexQueries.add(new CompletionEntityBuilder("1").name("Rizwan Idrees").suggest(new String[]{"Rizwan Idrees"}).buildIndex());
indexQueries.add(new CompletionEntityBuilder("2").name("Franck Marchand").suggest(new String[]{"Franck", "Marchand"}).buildIndex());
indexQueries.add(new CompletionEntityBuilder("3").name("Mohsin Husen").suggest(new String[]{"Mohsin", "Husen"}, "Mohsin Husen").buildIndex());
@@ -74,7 +81,7 @@ public class ElasticsearchTemplateCompletionTests {
nonDocumentEntity.setSomeField1("foo");
nonDocumentEntity.setSomeField2("bar");
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Franck Marchand").suggest(new String[]{"Franck", "Marchand"}).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mohsin Husen").suggest(new String[]{"Mohsin", "Husen"}, "Mohsin Husen").buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Rizwan Idrees").suggest(new String[]{"Rizwan", "Idrees"}, "Rizwan Idrees").buildIndex());
@@ -94,7 +101,7 @@ public class ElasticsearchTemplateCompletionTests {
nonDocumentEntity.setSomeField1("Payload");
nonDocumentEntity.setSomeField2("test");
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Mewes Kochheim1").suggest(new String[]{"Mewes Kochheim1"}, null, Double.MAX_VALUE).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mewes Kochheim2").suggest(new String[]{"Mewes Kochheim2"}, null, Long.MAX_VALUE).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Mewes Kochheim3").suggest(new String[]{"Mewes Kochheim3"}, null, "Payload test").buildIndex());
@@ -110,7 +117,7 @@ public class ElasticsearchTemplateCompletionTests {
elasticsearchTemplate.refresh(AnnotatedCompletionEntity.class);
elasticsearchTemplate.putMapping(AnnotatedCompletionEntity.class);
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Mewes Kochheim1").suggest(new String[]{"Mewes Kochheim1"}).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mewes Kochheim2").suggest(new String[]{"Mewes Kochheim2"}, null, null, 0).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Mewes Kochheim3").suggest(new String[]{"Mewes Kochheim3"}, null, null, 1).buildIndex());
@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,8 @@
package org.springframework.data.elasticsearch.core.facet;
import static org.springframework.data.elasticsearch.annotations.FieldIndex.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
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;
@@ -24,8 +25,8 @@ 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.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.annotations.InnerField;
/**
* Simple type to test facets
@@ -48,10 +49,10 @@ public class ArticleEntity {
@InnerField(suffix = "sort", type = String, store = true, indexAnalyzer = "keyword")
}
)
private List<String> authors = new ArrayList<>();
private List<String> authors = new ArrayList<String>();
@Field(type = Integer, store = true)
private List<Integer> publishedYears = new ArrayList<>();
private List<Integer> publishedYears = new ArrayList<Integer>();
private int score;
@@ -12,7 +12,7 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
*//*
package org.springframework.data.elasticsearch.core.facet;
@@ -20,36 +20,29 @@ 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;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.FacetedPage;
import org.springframework.data.elasticsearch.core.facet.request.HistogramFacetRequestBuilder;
import org.springframework.data.elasticsearch.core.facet.request.NativeFacetRequest;
import org.springframework.data.elasticsearch.core.facet.request.RangeFacetRequestBuilder;
import org.springframework.data.elasticsearch.core.facet.request.StatisticalFacetRequestBuilder;
import org.springframework.data.elasticsearch.core.facet.request.TermFacetRequestBuilder;
import org.springframework.data.elasticsearch.core.facet.result.HistogramResult;
import org.springframework.data.elasticsearch.core.facet.result.IntervalUnit;
import org.springframework.data.elasticsearch.core.facet.result.Range;
import org.springframework.data.elasticsearch.core.facet.result.RangeResult;
import org.springframework.data.elasticsearch.core.facet.result.StatisticalResult;
import org.springframework.data.elasticsearch.core.facet.result.Term;
import org.springframework.data.elasticsearch.core.facet.result.TermResult;
import org.springframework.data.elasticsearch.core.facet.request.*;
import org.springframework.data.elasticsearch.core.facet.result.*;
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;
*/
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Jonathan Yan
* @author Artur Konczak
*/
*//*
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
@@ -71,7 +64,7 @@ public class ElasticsearchTemplateFacetTests {
elasticsearchTemplate.deleteIndex(ArticleEntity.class);
elasticsearchTemplate.createIndex(ArticleEntity.class);
elasticsearchTemplate.putMapping(ArticleEntity.class);
elasticsearchTemplate.refresh(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();
@@ -82,7 +75,7 @@ public class ElasticsearchTemplateFacetTests {
elasticsearchTemplate.index(article2);
elasticsearchTemplate.index(article3);
elasticsearchTemplate.index(article4);
elasticsearchTemplate.refresh(ArticleEntity.class);
elasticsearchTemplate.refresh(ArticleEntity.class, true);
}
@Test
@@ -99,21 +92,21 @@ public class ElasticsearchTemplateFacetTests {
TermResult facet = (TermResult) result.getFacet(facetName);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4l));
assertThat(term.getCount(), is(4));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getCount(), is(3));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getCount(), is(2));
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1l));
assertThat(term.getCount(), is(1));
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getTotal(), is(10l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -124,26 +117,27 @@ public class ElasticsearchTemplateFacetTests {
// 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<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
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(4l));
assertThat(term.getCount(), is(3));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getCount(), is(2));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getCount(), is(1));
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -153,26 +147,23 @@ public class ElasticsearchTemplateFacetTests {
// 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<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements(), is(equalTo(3)));
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(2));
assertThat(facet.getTerms().size(), is(1));
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
Term term1 = facet.getTerms().get(1);
assertThat(term1.getTerm(), is(JONATHAN_YAN));
assertThat(term1.getCount(), is(1l));
assertThat(term.getCount(), is(1));
assertThat(facet.getTotal(), is(2l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(5l));
assertThat(facet.getMissing(), is(0l));
}
@@ -191,21 +182,21 @@ public class ElasticsearchTemplateFacetTests {
TermResult facet = (TermResult) result.getFacet(facetName);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getCount(), is(3));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1l));
assertThat(term.getCount(), is(1));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getCount(), is(2));
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4l));
assertThat(term.getCount(), is(4));
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getTotal(), is(10l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -225,21 +216,21 @@ public class ElasticsearchTemplateFacetTests {
TermResult facet = (TermResult) result.getFacet(facetName);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1l));
assertThat(term.getCount(), is(1));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getCount(), is(2));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getCount(), is(3));
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4l));
assertThat(term.getCount(), is(4));
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getTotal(), is(10l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -261,19 +252,19 @@ public class ElasticsearchTemplateFacetTests {
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2000)));
assertThat(term.getCount(), is(3l));
assertThat(term.getCount(), is(3));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2001)));
assertThat(term.getCount(), is(2l));
assertThat(term.getCount(), is(2));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2002)));
assertThat(term.getCount(), is(1l));
assertThat(term.getCount(), is(1));
assertThat(facet.getTotal(), is(3l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
assertThat(facet.getMissing(), is(1l));
}
@Test
@@ -282,35 +273,36 @@ public class ElasticsearchTemplateFacetTests {
// given
String facetName = "fyears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFilter(FilterBuilders.notFilter(FilterBuilders.missingFilter("publishedYears")))
.withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("publishedYears").descCount().build()).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements(), is(equalTo(3)));
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(3l));
assertThat(term.getCount(), is(3));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2001)));
assertThat(term.getCount(), is(2l));
assertThat(term.getCount(), is(2));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2002)));
assertThat(term.getCount(), is(1l));
assertThat(term.getCount(), is(1));
assertThat(facet.getTotal(), is(3l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExeptionsForMultiFieldFacet() {
@Test
public void shouldReturnSingleFacetOverYearsAndAuthorsForGivenQuery() {
// given
String facetName = "fyears";
@@ -326,31 +318,31 @@ public class ElasticsearchTemplateFacetTests {
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2000)));
assertThat(term.getCount(), is(3l));
assertThat(term.getCount(), is(3));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2001)));
assertThat(term.getCount(), is(2l));
assertThat(term.getCount(), is(2));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2002)));
assertThat(term.getCount(), is(1l));
assertThat(term.getCount(), is(1));
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getCount(), is(3));
term = facet.getTerms().get(4);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1l));
assertThat(term.getCount(), is(1));
term = facet.getTerms().get(5);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getCount(), is(2));
term = facet.getTerms().get(6);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4l));
assertThat(term.getCount(), is(4));
assertThat(facet.getTotal(), is(16l));
assertThat(facet.getOther(), is(0l));
@@ -377,46 +369,46 @@ public class ElasticsearchTemplateFacetTests {
Term numberTerm = numberFacet.getTerms().get(0);
assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2000)));
assertThat(numberTerm.getCount(), is(3l));
assertThat(numberTerm.getCount(), is(3));
numberTerm = numberFacet.getTerms().get(1);
assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2001)));
assertThat(numberTerm.getCount(), is(2l));
assertThat(numberTerm.getCount(), is(2));
numberTerm = numberFacet.getTerms().get(2);
assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2002)));
assertThat(numberTerm.getCount(), is(1l));
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(3l));
assertThat(stringTerm.getCount(), is(3));
stringTerm = stringFacet.getTerms().get(1);
assertThat(stringTerm.getTerm(), is(JONATHAN_YAN));
assertThat(stringTerm.getCount(), is(1l));
assertThat(stringTerm.getCount(), is(1));
stringTerm = stringFacet.getTerms().get(2);
assertThat(stringTerm.getTerm(), is(MOHSIN_HUSEN));
assertThat(stringTerm.getCount(), is(2l));
assertThat(stringTerm.getCount(), is(2));
stringTerm = stringFacet.getTerms().get(3);
assertThat(stringTerm.getTerm(), is(RIZWAN_IDREES));
assertThat(stringTerm.getCount(), is(4l));
assertThat(stringTerm.getCount(), is(4));
assertThat(stringFacet.getTotal(), is(4l));
assertThat(stringFacet.getTotal(), is(10l));
assertThat(stringFacet.getOther(), is(0l));
assertThat(stringFacet.getMissing(), is(0l));
}
@Test(expected = UnsupportedOperationException.class)
public void shouldThrowExceptionForNativeFacets() {
@Test
public void shouldReturnFacetedYearsForNativeFacet() {
// given
String facetName = "fyears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new NativeFacetRequest()).build();
.withFacet(new NativeFacetRequest(FacetBuilders.termsFacet(facetName).field("publishedYears"))).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
@@ -427,15 +419,15 @@ public class ElasticsearchTemplateFacetTests {
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2000)));
assertThat(term.getCount(), is(3l));
assertThat(term.getCount(), is(3));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2001)));
assertThat(term.getCount(), is(2l));
assertThat(term.getCount(), is(2));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2002)));
assertThat(term.getCount(), is(1l));
assertThat(term.getCount(), is(1));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(0l));
@@ -447,11 +439,12 @@ public class ElasticsearchTemplateFacetTests {
// 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<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements(), is(equalTo(3)));
TermResult facet = (TermResult) result.getFacet(facetName);
@@ -459,10 +452,10 @@ public class ElasticsearchTemplateFacetTests {
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getCount(), is(2));
assertThat(facet.getTotal(), is(1l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(4l));
assertThat(facet.getMissing(), is(0l));
}
@@ -471,17 +464,18 @@ public class ElasticsearchTemplateFacetTests {
// 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<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements(), is(equalTo(3)));
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(4));
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -505,7 +499,7 @@ public class ElasticsearchTemplateFacetTests {
assertThat(facet.getRanges().size(), is(equalTo(3)));
Range range = facet.getRanges().get(0);
assertThat(range.getFrom(), is(Double.NEGATIVE_INFINITY));
assertThat(range.getFrom(), nullValue());
assertThat(range.getTo(), is((double) YEAR_2000));
assertThat(range.getCount(), is(0L));
assertThat(range.getTotal(), is(0.0));
@@ -514,17 +508,17 @@ public class ElasticsearchTemplateFacetTests {
assertThat(range.getFrom(), is((double) YEAR_2000));
assertThat(range.getTo(), is((double) YEAR_2002));
assertThat(range.getCount(), is(3L));
assertThat(range.getTotal(), is(12004.0));
assertThat(range.getTotal(), is(6000.0));
range = facet.getRanges().get(2);
assertThat(range.getFrom(), is((double) YEAR_2002));
assertThat(range.getTo(), is(Double.POSITIVE_INFINITY));
assertThat(range.getTo(), nullValue());
assertThat(range.getCount(), is(1L));
assertThat(range.getTotal(), is(6003.0));
assertThat(range.getTotal(), is(2002.0));
}
@Test
public void shouldReturnKeyValueRangeFacetForStringValuesInGivenQuery() {
public void shouldReturnKeyValueRangeFacetForGivenQuery() {
// given
String facetName = "rangeScoreOverYears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
@@ -541,7 +535,7 @@ public class ElasticsearchTemplateFacetTests {
assertThat(facet.getRanges().size(), is(equalTo(3)));
Range range = facet.getRanges().get(0);
assertThat(range.getFrom(), is(Double.NEGATIVE_INFINITY));
assertThat(range.getFrom(), nullValue());
assertThat(range.getTo(), is((double) YEAR_2000));
assertThat(range.getCount(), is(0L));
assertThat(range.getTotal(), is(0.0));
@@ -554,7 +548,43 @@ public class ElasticsearchTemplateFacetTests {
range = facet.getRanges().get(2);
assertThat(range.getFrom(), is((double) YEAR_2002));
assertThat(range.getTo(), is(Double.POSITIVE_INFINITY));
assertThat(range.getTo(), nullValue());
assertThat(range.getCount(), is(1L));
assertThat(range.getTotal(), is(40.0));
}
@Test
public void shouldReturnKeyValueRangeFacetForStringValuesInGivenQuery() {
// given
String facetName = "rangeScoreOverYears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(
new RangeFacetRequestBuilder(facetName).fields(PUBLISHED_YEARS, "score")
.to("2000").range("2000", "2002").from("2002").build()
).build();
// when
FacetedPage<ArticleEntity> 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));
}
@@ -605,4 +635,4 @@ public class ElasticsearchTemplateFacetTests {
assertThat(unit.getCount(), is(1L));
}
}
*/
@@ -21,6 +21,7 @@ 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;
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@ import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import com.spatial4j.core.io.GeohashUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -35,8 +36,6 @@ import org.springframework.data.geo.Point;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.spatial4j.core.io.GeohashUtils;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
@@ -56,7 +55,7 @@ public class ElasticsearchTemplateGeoTests {
elasticsearchTemplate.refresh(AuthorMarkerEntity.class);
elasticsearchTemplate.putMapping(AuthorMarkerEntity.class);
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
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());
@@ -70,7 +69,7 @@ public class ElasticsearchTemplateGeoTests {
elasticsearchTemplate.refresh(LocationMarkerEntity.class);
elasticsearchTemplate.putMapping(LocationMarkerEntity.class);
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
double[] latLonArray = {0.100000, 51.000000};
String lonLatString = "51.000000, 0.100000";
String geohash = "u1044k2bd6u";
@@ -15,12 +15,7 @@
*/
package org.springframework.data.elasticsearch.core.geo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,20 +16,18 @@
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;
import org.springframework.data.mapping.model.Property;
import org.springframework.data.mapping.model.SimpleTypeHolder;
import org.springframework.data.util.ClassTypeInformation;
import org.springframework.data.util.TypeInformation;
import org.springframework.util.ReflectionUtils;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public class SimpleElasticsearchPersistentEntityTests {
@@ -37,43 +35,46 @@ public class SimpleElasticsearchPersistentEntityTests {
public void shouldThrowExceptionGivenVersionPropertyIsNotLong() throws NoSuchFieldException, IntrospectionException {
// given
TypeInformation typeInformation = ClassTypeInformation.from(EntityWithWrongVersionType.class);
SimpleElasticsearchPersistentEntity<EntityWithWrongVersionType> entity = new SimpleElasticsearchPersistentEntity<>(
typeInformation);
SimpleElasticsearchPersistentProperty persistentProperty = createProperty(entity, "version");
SimpleElasticsearchPersistentProperty persistentProperty = new SimpleElasticsearchPersistentProperty(
EntityWithWrongVersionType.class.getDeclaredField("version"), new PropertyDescriptor("version",
EntityWithWrongVersionType.class), new SimpleElasticsearchPersistentEntity<EntityWithWrongVersionType>(
typeInformation), new SimpleTypeHolder()
);
// when
entity.addPersistentProperty(persistentProperty);
new SimpleElasticsearchPersistentEntity(typeInformation).addPersistentProperty(persistentProperty);
}
@Test(expected = MappingException.class)
public void shouldThrowExceptionGivenMultipleVersionPropertiesArePresent()
throws NoSuchFieldException, IntrospectionException {
public void shouldThrowExceptionGivenMultipleVersionPropertiesArePresent() throws NoSuchFieldException,
IntrospectionException {
// given
TypeInformation typeInformation = ClassTypeInformation.from(EntityWithMultipleVersionField.class);
SimpleElasticsearchPersistentEntity<EntityWithMultipleVersionField> entity = new SimpleElasticsearchPersistentEntity<>(
SimpleElasticsearchPersistentProperty persistentProperty1 = new SimpleElasticsearchPersistentProperty(
EntityWithMultipleVersionField.class.getDeclaredField("version1"), new PropertyDescriptor("version1",
EntityWithMultipleVersionField.class),
new SimpleElasticsearchPersistentEntity<EntityWithMultipleVersionField>(typeInformation),
new SimpleTypeHolder()
);
SimpleElasticsearchPersistentProperty persistentProperty2 = new SimpleElasticsearchPersistentProperty(
EntityWithMultipleVersionField.class.getDeclaredField("version2"), new PropertyDescriptor("version2",
EntityWithMultipleVersionField.class),
new SimpleElasticsearchPersistentEntity<EntityWithMultipleVersionField>(typeInformation),
new SimpleTypeHolder()
);
SimpleElasticsearchPersistentEntity simpleElasticsearchPersistentEntity = new SimpleElasticsearchPersistentEntity(
typeInformation);
SimpleElasticsearchPersistentProperty persistentProperty1 = createProperty(entity, "version1");
SimpleElasticsearchPersistentProperty persistentProperty2 = createProperty(entity, "version2");
entity.addPersistentProperty(persistentProperty1);
simpleElasticsearchPersistentEntity.addPersistentProperty(persistentProperty1);
// when
entity.addPersistentProperty(persistentProperty2);
}
private static SimpleElasticsearchPersistentProperty createProperty(SimpleElasticsearchPersistentEntity<?> entity,
String field) {
Property property = Property.of(ReflectionUtils.findField(entity.getTypeInformation().getType(), field));
return new SimpleElasticsearchPersistentProperty(property, entity, SimpleTypeHolder.DEFAULT);
simpleElasticsearchPersistentEntity.addPersistentProperty(persistentProperty2);
}
private class EntityWithWrongVersionType {
@Version private String version;
@Version
private String version;
public String getVersion() {
return version;
@@ -86,8 +87,10 @@ public class SimpleElasticsearchPersistentEntityTests {
private class EntityWithMultipleVersionField {
@Version private Long version1;
@Version private Long version2;
@Version
private Long version1;
@Version
private Long version2;
public Long getVersion1() {
return version1;
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -78,7 +78,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformOrOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -117,7 +117,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformAndOperationWithinCriteria() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
@@ -144,7 +144,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformOrOperationWithinCriteria() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
@@ -170,7 +170,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformIsOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
@@ -196,7 +196,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformMultipleIsOperations() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -234,7 +234,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformEndsWithOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -273,7 +273,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformStartsWithOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -312,7 +312,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformContainsOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -350,7 +350,7 @@ public class CriteriaQueryTests {
@Test
public void shouldExecuteExpression() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -388,7 +388,7 @@ public class CriteriaQueryTests {
@Test
public void shouldExecuteCriteriaChain() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -427,7 +427,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformIsNotOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -466,7 +466,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformBetweenOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -505,7 +505,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformBetweenOperationWithoutUpperBound() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -545,7 +545,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformBetweenOperationWithoutLowerBound() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -585,7 +585,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformLessThanEqualOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -625,7 +625,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformGreaterThanEquals() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -665,7 +665,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformBoostOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@@ -704,7 +704,7 @@ public class CriteriaQueryTests {
@Test
public void shouldReturnDocumentAboveMinimalScoreGivenCriteria() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
indexQueries.add(buildIndex(SampleEntity.builder().id("1").message("ab").build()));
indexQueries.add(buildIndex(SampleEntity.builder().id("2").message("bc").build()));
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,16 +15,11 @@
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
@@ -48,5 +43,5 @@ public class Book {
@Field(type = FieldType.Object)
private Author author;
@Field(type = FieldType.Nested)
private Map<Integer, Collection<String>> buckets = new HashMap<>();
private Map<Integer, Collection<String>> buckets = new HashMap<Integer, Collection<String>>();
}
@@ -15,11 +15,7 @@
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.*;
/**
* @author Rizwan Idrees
@@ -1,14 +1,10 @@
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.geo.GeoBox;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
@@ -1,37 +0,0 @@
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import java.util.HashSet;
import java.util.Set;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* Created by akonczak on 21/08/2016.
*/
@Document(indexName = "groups", type = "group")
public class Group {
@Id
String id;
@Field(type = FieldType.Nested, ignoreFields ={"groups"})
private Set<User> users = new HashSet<>();
}
@@ -17,11 +17,7 @@ package org.springframework.data.elasticsearch.entities;
import org.springframework.core.style.ToStringCreator;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldIndex;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.Parent;
import org.springframework.data.elasticsearch.annotations.*;
/**
* ParentEntity
@@ -15,15 +15,10 @@
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Date;
import java.util.List;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;

Some files were not shown because too many files have changed in this diff Show More