1
0
mirror of synced 2026-07-07 10:40:02 +00:00

Compare commits

...

65 Commits

Author SHA1 Message Date
Oliver Gierke 072fb3465a DATAES-346 - Release version 2.1.3 (Ingalls SR3). 2017-04-19 19:32:39 +02:00
Oliver Gierke a6dc02aa51 DATAES-346 - Prepare 2.1.3 (Ingalls SR3). 2017-04-19 19:32:02 +02:00
Oliver Gierke 5a3a49cc3e DATAES-346 - Updated changelog. 2017-04-19 19:31:58 +02:00
Oliver Gierke f1559d3b55 DATAES-336 - Updated changelog. 2017-04-19 13:04:14 +02:00
Oliver Gierke 9a9d95ba15 DATAES-335 - After release cleanups. 2017-04-19 11:48:46 +02:00
Oliver Gierke b873c5409c DATAES-335 - Prepare next development iteration. 2017-04-19 11:48:44 +02:00
Oliver Gierke 6aa4adc977 DATAES-335 - Release version 2.1.2 (Ingalls SR2). 2017-04-19 10:11:29 +02:00
Oliver Gierke 2c7d8c6f61 DATAES-335 - Prepare 2.1.2 (Ingalls SR2). 2017-04-19 10:10:48 +02:00
Oliver Gierke 05c9804d16 DATAES-335 - Updated changelog. 2017-04-19 10:10:44 +02:00
Oliver Gierke c72eaa79e9 DATAES-311 - Updated changelog. 2017-04-10 14:33:12 +02:00
Oliver Gierke 399611d68a DATAES-326 - Updated changelog. 2017-03-02 16:57:55 +01:00
Oliver Gierke f79caa9626 DATAES-327 - After release cleanups. 2017-03-02 10:21:57 +01:00
Oliver Gierke b8ff15e69c DATAES-327 - Prepare next development iteration. 2017-03-02 10:21:40 +01:00
Oliver Gierke c28f41a2c4 DATAES-327 - Release version 2.1.1 (Ingalls SR1). 2017-03-02 09:41:29 +01:00
Oliver Gierke 686921c46e DATAES-327 - Prepare 2.1.1 (Ingalls SR1). 2017-03-02 09:33:29 +01:00
Oliver Gierke d1e11ef5f9 DATAES-327 - Updated changelog. 2017-03-02 09:33:11 +01:00
Mark Paluch c0ef590038 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:42:56 +01:00
Oliver Gierke 692142ea65 DATAES-319 - Updated changelog. 2017-01-26 12:08:53 +01:00
Oliver Gierke 6e2331b040 DATAES-320 - After release cleanups. 2017-01-26 10:57:48 +01:00
Oliver Gierke 29910fc9ef DATAES-320 - Prepare next development iteration. 2017-01-26 10:57:45 +01:00
Oliver Gierke 38604eb64d DATAES-320 - Release version 2.1 GA (Ingalls). 2017-01-26 10:27:11 +01:00
Oliver Gierke 344f439778 DATAES-320 - Prepare 2.1 GA (Ingalls). 2017-01-26 10:26:36 +01:00
Oliver Gierke ea07d697ad DATAES-320 - Updated changelog. 2017-01-26 10:26:34 +01:00
Mark Paluch 6b549339c8 DATAES-322 - Update project documentation with the CLA tool integration. 2017-01-13 11:32:01 +01:00
Oliver Gierke 3c2894e45d DATAES-304 - Updated changelog. 2016-12-21 19:35:39 +01:00
Oliver Gierke d921f9d9a3 DATAES-275 - After release cleanups. 2016-12-21 16:33:14 +01:00
Oliver Gierke af1f658712 DATAES-275 - Prepare next development iteration. 2016-12-21 16:33:11 +01:00
Oliver Gierke 18c30078ba DATAES-275 - Release version 2.1 RC1 (Ingalls). 2016-12-21 16:16:52 +01:00
Oliver Gierke 812e202f15 DATAES-275 - Prepare 2.1 RC1 (Ingalls). 2016-12-21 16:15:48 +01:00
Oliver Gierke bf4cadbdd8 DATAES-275 - Updated changelog. 2016-12-21 16:15:44 +01:00
Oliver Gierke 200f1771d5 DATAES-315 - Adapt API in ElasticsearchRepositoryFactoryBean.
Related ticket: DATACMNS-891.
2016-12-15 15:25:17 +01:00
Mark Paluch b83a097892 DATAES-313 - Register ElasticsearchRepositoryFactory in spring.factories.
This is required for the switch in support for multi-store detection.

Related ticket: DATACMNS-952.
2016-12-06 09:12:53 +01:00
Oliver Gierke 6d08e92117 DATAES-306 - Updated changelog. 2016-11-23 13:52:48 +01:00
Oliver Gierke fce9c1fd60 DATAES-300 - Updated changelog. 2016-11-03 18:56:50 +01:00
Florian Hopf ceffbeebd1 DATAES-303 - Updated version and ES dependency version in README.
Original pull request: #157.
2016-11-03 11:23:27 +01:00
Oliver Gierke 42ba51546e DATAES-297 - Updated changelog. 2016-09-29 14:42:13 +02:00
Oliver Gierke 8df87b3268 DATAES-299 - Updated changelog. 2016-09-29 11:42:11 +02:00
Oliver Gierke bc3c2dc12c DATAES-296 - Updated changelog. 2016-09-21 08:10:37 +02:00
Oliver Gierke 5483564f08 DATAES-268 - Updated changelog. 2016-09-21 08:10:35 +02:00
Artur Konczak db3174dbbe DATAES-289 - added groovy plugin for ES2.4 2016-09-01 12:42:01 +01:00
Oliver Gierke 896fbbebc8 DATAES-289 - Upgraded to Elasticsearch 2.4.
Upgraded to Elasticsearch 2.4 as version before that are not compatiblewith Jackson 2.8 [0].

Removed the now unsupported Groovy plugin registration way and added groovy-lang as test scope dependency but had to disable the only Groovy related test as it seems to be unclear how to activate the Groovy plugin in an embedded Elasticsearch server [1].

[0] https://github.com/elastic/elasticsearch/issues/20089
[1] https://discuss.elastic.co/t/after-upgrade-from-es-2-1-1-to-es-2-2-0-groovy-scripting-is-broken/40977
2016-09-01 13:26:03 +02:00
Artur Konczak 7a95cb64a8 DATAES-260 added missing test 2016-08-22 00:31:40 +01:00
Pavel Luhin 2718be7c07 DATAES-260 - StacOverflow when two reverse relationship.
Ignore fields based on parent ignore list
2016-08-21 22:37:37 +01:00
Artur Konczak c7dfd2131e DATAES-228 - clean up 2016-08-21 00:33:39 +01:00
Mark Janssen 2b60128390 DATAES-228 Fix id handling for indexing
When an id is set in the IndexQuery object, use it without requiring an
@Document annotation. When it is not, try to resolve it from the object
when it has @Document and @Id annotations.
2016-08-21 00:23:14 +01:00
Artur Konczak 53b587101d DATAES-163 - Modified tests to work with new version of spring-data-elasticsearch base on ES2.x 2016-08-20 23:50:16 +01:00
Gad Akuka 063d8ed983 DATAES-163 - Add support for UUID as primary key
Add support for UUID as primary key

Add tests for support of UUID as primary key
2016-08-20 23:50:16 +01:00
Oliver Gierke e5b080a9b0 DATAES-284 - Downgrade to Jackson 2.7.5 until Elasticsearch is compatible with 2.8.
https://github.com/FasterXML/jackson-core/issues/313
https://github.com/elastic/elasticsearch/issues/20089
2016-08-20 10:08:25 +02:00
Oliver Gierke 7113c7ac66 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:08:21 +02:00
Young Gu 7e736a6271 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 09:59:08 +02:00
Oliver Gierke 20c5d19963 DATAES-250 - After release cleanups. 2016-07-27 14:32:38 +02:00
Oliver Gierke b1e9f77a2b DATAES-250 - Prepare next development iteration. 2016-07-27 14:32:36 +02:00
Oliver Gierke 7b6979166a DATAES-250 - Release version 2.1 M1 (Ingalls). 2016-07-27 13:52:13 +02:00
Oliver Gierke a3a6f9cc67 DATAES-250 - Prepare 2.1 M1 (Ingalls). 2016-07-27 13:51:38 +02:00
Oliver Gierke ecc62cc1b4 DATAES-250 - Updated changelog. 2016-07-27 13:51:36 +02:00
Zsombor Gegesy edfca24527 DATAES-264 - Make available the entity class of the repository so generic code can be written more easily. 2016-06-24 14:49:05 +01:00
Artur Konczak 392a87ab0a DATAES-180 - added faceted page back powered by aggregation 2016-06-24 11:56:38 +01:00
Artur Konczak 6ffac62b3e DATAES-180 - clean up 2016-06-24 11:56:38 +01:00
Petar Tahchiev fd06f8efd7 Created AggregatedPage to hold the Aggregations
Create AggregatedPage and populate it in the DefaultResultMapper.
2016-06-24 11:56:37 +01:00
Oliver Gierke 8c77d314aa DATAES-251 - Updated changelog. 2016-06-15 14:31:50 +02:00
Artur Konczak f569b0348a DATAES-262 - Upgrade elasticsearch to 2.3.3 2016-06-14 15:51:07 +01:00
Mohsin Husen 99a401fdff DATAES-245 - After release cleanups. 2016-04-07 09:48:43 +01:00
Oliver Gierke 6c0272880a DATAES-249 - Updated changelog. 2016-04-06 23:14:28 +02:00
Oliver Gierke 22d81083b4 DATAES-245 - After release cleanups. 2016-04-06 16:37:03 +02:00
Oliver Gierke c65a573b23 DATAES-245 - Prepare next development iteration. 2016-04-06 16:37:00 +02:00
69 changed files with 3293 additions and 487 deletions
+4 -1
View File
@@ -1,9 +1,12 @@
<!--
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).
+5 -10
View File
@@ -31,7 +31,7 @@ Add the Maven dependency:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>1.3.4.RELEASE</version>
<version>2.0.4.RELEASE</version>
</dependency>
```
@@ -42,7 +42,7 @@ the appropriate dependency version.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<version>2.1.0.BUILD-SNAPSHOT</version>
</dependency>
<repository>
@@ -52,15 +52,10 @@ 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.0.RC1 | 2.2.0 |
| 2.0.4.RELEASE | 2.4.0 |
| 2.0.0.RELEASE | 2.2.0 |
| 1.4.0.M1 | 1.7.3 |
| 1.3.0.RELEASE | 1.5.2 |
| 1.2.0.RELEASE | 1.4.4 |
@@ -250,7 +245,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'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.
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.
Code formatting for [Eclipse and Intellij](https://github.com/spring-projects/spring-data-build/tree/master/etc/ide)
+6 -7
View File
@@ -4,12 +4,12 @@
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>2.0.0.RELEASE</version>
<version>2.1.3.RELEASE</version>
<parent>
<groupId>org.springframework.data.build</groupId>
<artifactId>spring-data-parent</artifactId>
<version>1.8.0.RELEASE</version>
<version>1.9.3.RELEASE</version>
<relativePath>../spring-data-build/parent/pom.xml</relativePath>
</parent>
@@ -23,8 +23,8 @@
<commonscollections>3.2.1</commonscollections>
<commonslang>2.6</commonslang>
<elasticsearch>2.2.0</elasticsearch>
<springdata.commons>1.12.0.RELEASE</springdata.commons>
<elasticsearch>2.4.0</elasticsearch>
<springdata.commons>1.13.3.RELEASE</springdata.commons>
</properties>
@@ -86,7 +86,7 @@
<artifactId>jackson-databind</artifactId>
<version>${jackson}</version>
</dependency>
<!-- CDI -->
<dependency>
<groupId>javax.enterprise</groupId>
@@ -100,7 +100,6 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -129,7 +128,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.4</version>
<version>${lombok}</version>
<scope>test</scope>
</dependency>
@@ -1,5 +1,5 @@
/*
* Copyright 2014 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.
@@ -18,29 +18,28 @@ package org.springframework.data.elasticsearch.core;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
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;
@@ -48,6 +47,9 @@ import org.springframework.data.mapping.context.MappingContext;
/**
* @author Artur Konczak
* @author Petar Tahchiev
* @author Young Gu
* @author Oliver Gierke
*/
public class DefaultResultMapper extends AbstractResultMapper {
@@ -74,7 +76,7 @@ public class DefaultResultMapper extends AbstractResultMapper {
}
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
long totalHits = response.getHits().totalHits();
List<T> results = new ArrayList<T>();
for (SearchHit hit : response.getHits()) {
@@ -86,38 +88,39 @@ 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 PageImpl<T>(results, pageable, totalHits);
return new AggregatedPageImpl<T>(results, pageable, totalHits, response.getAggregations());
}
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);
}
@@ -169,18 +172,15 @@ public class DefaultResultMapper extends AbstractResultMapper {
}
private <T> void setPersistentEntityId(T result, String id, Class<T> clazz) {
if (mappingContext != null && clazz.isAnnotationPresent(Document.class)) {
PersistentProperty<ElasticsearchPersistentProperty> idProperty = mappingContext.getPersistentEntity(clazz).getIdProperty();
ElasticsearchPersistentEntity<?> persistentEntity = mappingContext.getPersistentEntity(clazz);
PersistentProperty<?> idProperty = persistentEntity.getIdProperty();
// Only deal with String because ES generated Ids are strings !
if (idProperty != null && idProperty.getType().isAssignableFrom(String.class)) {
Method setter = idProperty.getSetter();
if (setter != null) {
try {
setter.invoke(result, id);
} catch (Throwable t) {
t.printStackTrace();
}
}
persistentEntity.getPropertyAccessor(result).setProperty(idProperty, id);
}
}
}
@@ -81,8 +81,11 @@ 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.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.core.query.*;
@@ -98,6 +101,9 @@ import org.springframework.util.Assert;
* @author Artur Konczak
* @author Kevin Leturc
* @author Mason Chan
* @author Young Gu
* @author Oliver Gierke
* @author Mark Janssen
*/
public class ElasticsearchTemplate implements ElasticsearchOperations, ApplicationContextAware {
@@ -261,12 +267,12 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
}
@Override
public <T> Page<T> queryForPage(SearchQuery query, Class<T> clazz) {
public <T> AggregatedPage<T> queryForPage(SearchQuery query, Class<T> clazz) {
return queryForPage(query, clazz, resultsMapper);
}
@Override
public <T> Page<T> queryForPage(SearchQuery query, Class<T> clazz, SearchResultMapper mapper) {
public <T> AggregatedPage<T> queryForPage(SearchQuery query, Class<T> clazz, SearchResultMapper mapper) {
SearchResponse response = doSearch(prepareSearch(query, clazz), query);
return mapper.mapResults(response, clazz, query.getPageable());
}
@@ -410,6 +416,11 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
@@ -664,14 +675,14 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
while (hasRecords) {
Page<String> page = scroll(scrollId, scrollTimeInMillis, new SearchResultMapper() {
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<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 PageImpl<T>((List<T>) result);
return new AggregatedPageImpl<T>((List<T>) result);
}
return null;
}
@@ -880,6 +891,12 @@ 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());
}
@@ -998,13 +1015,10 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
IndexRequestBuilder indexRequestBuilder = null;
if (query.getObject() != null) {
String entityId = null;
if (isDocument(query.getObject().getClass())) {
entityId = getPersistentEntityId(query.getObject());
}
String id = isBlank(query.getId()) ? getPersistentEntityId(query.getObject()) : query.getId();
// If we have a query id and a document id, do not ask ES to generate one.
if (query.getId() != null && entityId != null) {
indexRequestBuilder = client.prepareIndex(indexName, type, query.getId());
if (id != null) {
indexRequestBuilder = client.prepareIndex(indexName, type, id);
} else {
indexRequestBuilder = client.prepareIndex(indexName, type);
}
@@ -1081,35 +1095,21 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, Applicati
}
private String getPersistentEntityId(Object entity) {
PersistentProperty idProperty = getPersistentEntityFor(entity.getClass()).getIdProperty();
if (idProperty != null) {
Method getter = idProperty.getGetter();
if (getter != null) {
try {
Object id = getter.invoke(entity);
if (id != null) {
return String.valueOf(id);
}
} catch (Throwable t) {
t.printStackTrace();
}
}
}
return null;
ElasticsearchPersistentEntity<?> persistentEntity = getPersistentEntityFor(entity.getClass());
Object identifier = persistentEntity.getIdentifierAccessor(entity).getIdentifier();
return identifier == null ? null : String.valueOf(identifier);
}
private void setPersistentEntityId(Object entity, String id) {
PersistentProperty idProperty = getPersistentEntityFor(entity.getClass()).getIdProperty();
ElasticsearchPersistentEntity<?> persistentEntity = getPersistentEntityFor(entity.getClass());
PersistentProperty<?> idProperty = persistentEntity.getIdProperty();
// Only deal with String because ES generated Ids are strings !
if (idProperty != null && idProperty.getType().isAssignableFrom(String.class)) {
Method setter = idProperty.getSetter();
if (setter != null) {
try {
setter.invoke(entity, id);
} catch (Throwable t) {
t.printStackTrace();
}
}
persistentEntity.getPropertyAccessor(entity).setProperty(idProperty,id);
}
}
@@ -1162,10 +1162,6 @@ 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();
@@ -0,0 +1,37 @@
/*
* 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);
}
@@ -0,0 +1,130 @@
/*
* 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.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<String, FacetResult>();
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<FacetResult>();
for (Aggregation agg : getAggregations()) {
if (agg instanceof Terms) {
List<Term> terms = new ArrayList<Term>();
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<org.springframework.data.elasticsearch.core.facet.result.Range>();
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<IntervalUnit>();
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,6 +32,7 @@ import org.springframework.core.GenericCollectionTypeResolver;
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;
@@ -45,6 +46,7 @@ import org.springframework.data.util.TypeInformation;
* @author Kevin Leturc
* @author Alexander Volz
* @author Dennis Maaß
* @author Pavel Luhin
*/
class MappingBuilder {
@@ -108,7 +110,7 @@ class MappingBuilder {
for (java.lang.reflect.Field field : fields) {
if (field.isAnnotationPresent(Transient.class) || isInIgnoreFields(field)) {
if (field.isAnnotationPresent(Transient.class) || isInIgnoreFields(field, fieldAnnotation)) {
continue;
}
@@ -336,10 +338,9 @@ class MappingBuilder {
return idFieldName.equals(field.getName());
}
private static boolean isInIgnoreFields(java.lang.reflect.Field field) {
Field fieldAnnotation = field.getAnnotation(Field.class);
if (null != fieldAnnotation) {
String[] ignoreFields = fieldAnnotation.ignoreFields();
private static boolean isInIgnoreFields(java.lang.reflect.Field field, Field parentFieldAnnotation) {
if (null != parentFieldAnnotation) {
String[] ignoreFields = parentFieldAnnotation.ignoreFields();
return Arrays.asList(ignoreFields).contains(field.getName());
}
return false;
@@ -16,13 +16,14 @@
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> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable);
<T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable);
}
@@ -0,0 +1,17 @@
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);
}
@@ -0,0 +1,55 @@
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<String, Aggregation>();
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,5 +1,5 @@
/*
* Copyright 2013 the original author or authors.
* Copyright 2013-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.
@@ -31,8 +31,8 @@ import org.springframework.util.Assert;
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public class MappingElasticsearchConverter implements ElasticsearchConverter, ApplicationContextAware {
private final MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext;
@@ -43,7 +43,9 @@ public class MappingElasticsearchConverter implements ElasticsearchConverter, Ap
public MappingElasticsearchConverter(
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
Assert.notNull(mappingContext);
Assert.notNull(mappingContext, "MappingContext must not be null!");
this.mappingContext = mappingContext;
this.conversionService = new DefaultConversionService();
}
@@ -0,0 +1,50 @@
/*
* 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;
}
}
@@ -0,0 +1,47 @@
/*
* 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;
}
}
@@ -0,0 +1,33 @@
/*
* 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();
}
@@ -0,0 +1,32 @@
/*
* 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();
}
@@ -0,0 +1,27 @@
/*
* 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
}
@@ -0,0 +1,73 @@
/*
* 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;
}
}
@@ -0,0 +1,58 @@
/*
* 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;
}
}
@@ -0,0 +1,43 @@
/*
* 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;
}
}
@@ -0,0 +1,132 @@
/*
* 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 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<Entry>();
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;
}
}
}
@@ -0,0 +1,85 @@
/*
* 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;
}
}
@@ -0,0 +1,53 @@
/*
* 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);
}
}
@@ -0,0 +1,52 @@
/*
* 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;
}
}
@@ -0,0 +1,27 @@
/*
* 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;
}
@@ -0,0 +1,107 @@
/*
* 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;
}
}
@@ -0,0 +1,88 @@
/*
* 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;
}
}
@@ -0,0 +1,39 @@
/*
* 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;
}
}
@@ -0,0 +1,92 @@
/*
* 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 +
'}';
}
}
@@ -0,0 +1,79 @@
/*
* 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;
}
}
@@ -0,0 +1,44 @@
/*
* 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;
}
}
@@ -0,0 +1,86 @@
/*
* 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;
}
}
@@ -0,0 +1,44 @@
/*
* 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;
}
}
@@ -0,0 +1,63 @@
/*
* 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-2016 the original author or authors.
* Copyright 2013-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.
@@ -29,6 +29,7 @@ import org.springframework.util.Assert;
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
abstract class AbstractQuery implements Query {
@@ -55,7 +56,9 @@ abstract class AbstractQuery implements Query {
@Override
public final <T extends Query> T setPageable(Pageable pageable) {
Assert.notNull(pageable);
Assert.notNull(pageable, "Pageable must not be null!");
this.pageable = pageable;
return (T) this.addSort(pageable.getSort());
}
@@ -22,6 +22,7 @@ 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,7 +39,7 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
private QueryBuilder filter;
private List<SortBuilder> sorts;
private final List<ScriptField> scriptFields = new ArrayList<ScriptField>();
/*private List<FacetRequest> facets;*/
private List<FacetRequest> facets;
private List<AbstractAggregationBuilder> aggregations;
private HighlightBuilder.Field[] highlightFields;
private List<IndexBoost> indicesBoost;
@@ -94,7 +95,7 @@ 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<FacetRequest>();
}
@@ -108,7 +109,7 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
@Override
public List<FacetRequest> getFacets() {
return facets;
}*/
}
@Override
public List<AbstractAggregationBuilder> getAggregations() {
@@ -25,6 +25,7 @@ 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
@@ -40,6 +41,7 @@ public class NativeSearchQueryBuilder {
private QueryBuilder filterBuilder;
private List<ScriptField> scriptFields = new ArrayList<ScriptField>();
private List<SortBuilder> sortBuilders = new ArrayList<SortBuilder>();
private List<FacetRequest> facetRequests = new ArrayList<FacetRequest>();
private List<AbstractAggregationBuilder> aggregationBuilders = new ArrayList<AbstractAggregationBuilder>();
private HighlightBuilder.Field[] highlightFields;
private Pageable pageable;
@@ -78,10 +80,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;
@@ -168,6 +170,10 @@ public class NativeSearchQueryBuilder {
nativeSearchQuery.setScriptFields(scriptFields);
}
if (!isEmpty(facetRequests)) {
nativeSearchQuery.setFacets(facetRequests);
}
if (!isEmpty(aggregationBuilders)) {
nativeSearchQuery.setAggregations(aggregationBuilders);
}
@@ -21,6 +21,7 @@ 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
@@ -37,7 +38,8 @@ public interface SearchQuery extends Query {
List<SortBuilder> getElasticsearchSorts();
/*List<FacetRequest> getFacets();*/
@Deprecated
List<FacetRequest> getFacets();
List<AbstractAggregationBuilder> getAggregations();
@@ -43,4 +43,6 @@ 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-2016 the original author or authors.
* Copyright 2013-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.
@@ -43,6 +43,7 @@ import org.springframework.util.Assert;
* @author Mohsin Husen
* @author Ryan Henszey
* @author Kevin Leturc
* @author Mark Paluch
*/
public abstract class AbstractElasticsearchRepository<T, ID extends Serializable> implements
ElasticsearchRepository<T, ID> {
@@ -56,14 +57,18 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
}
public AbstractElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations);
Assert.notNull(elasticsearchOperations, "ElasticsearchOperations must not be null!");
this.setElasticsearchOperations(elasticsearchOperations);
}
public AbstractElasticsearchRepository(ElasticsearchEntityInformation<T, ID> metadata,
ElasticsearchOperations elasticsearchOperations) {
this(elasticsearchOperations);
Assert.notNull(metadata);
Assert.notNull(metadata, "ElasticsearchEntityInformation must not be null!");
this.entityInformation = metadata;
setEntityClass(this.entityInformation.getJavaType());
try {
@@ -276,6 +281,7 @@ public abstract class AbstractElasticsearchRepository<T, ID extends Serializable
return resolveReturnedClassFromGenericType(clazz.getSuperclass());
}
@Override
public Class<T> getEntityClass() {
if (!isEntityClassSet()) {
try {
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-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.
@@ -28,6 +28,7 @@ import org.springframework.util.Assert;
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Oliver Gierke
* @author Mark Paluch
*/
public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchEntityInformationCreator {
@@ -35,7 +36,9 @@ public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchE
public ElasticsearchEntityInformationCreatorImpl(
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
Assert.notNull(mappingContext);
Assert.notNull(mappingContext, "MappingContext must not be null!");
this.mappingContext = mappingContext;
}
@@ -1,115 +1,122 @@
/*
* 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 static org.springframework.data.querydsl.QueryDslUtils.*;
import java.io.Serializable;
import java.lang.reflect.Method;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.query.ElasticsearchPartQuery;
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.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.QueryLookupStrategy;
import org.springframework.data.repository.query.RepositoryQuery;
import org.springframework.util.Assert;
/**
* Factory to create {@link ElasticsearchRepository}
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Ryan Henszey
*/
public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport {
private final ElasticsearchOperations elasticsearchOperations;
private final ElasticsearchEntityInformationCreator entityInformationCreator;
public ElasticsearchRepositoryFactory(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations);
this.elasticsearchOperations = elasticsearchOperations;
this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(elasticsearchOperations
.getElasticsearchConverter().getMappingContext());
}
@Override
public <T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
return entityInformationCreator.getEntityInformation(domainClass);
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
protected Object getTargetRepository(RepositoryInformation metadata) {
return getTargetRepositoryViaReflection(metadata,getEntityInformation(metadata.getDomainType()), elasticsearchOperations);
}
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
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())
|| Double.class.isAssignableFrom(metadata.getIdType())) {
return NumberKeyedRepository.class;
} else if (metadata.getIdType() == String.class) {
return SimpleElasticsearchRepository.class;
} else {
throw new IllegalArgumentException("Unsuppored ID type " + metadata.getIdType());
}
}
private static boolean isQueryDslRepository(Class<?> repositoryInterface) {
return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface);
}
@Override
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)
*/
@Override
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory,
NamedQueries namedQueries) {
ElasticsearchQueryMethod queryMethod = new ElasticsearchQueryMethod(method, metadata, factory);
String namedQueryName = queryMethod.getNamedQueryName();
if (namedQueries.hasQuery(namedQueryName)) {
String namedQuery = namedQueries.getQuery(namedQueryName);
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, namedQuery);
} else if (queryMethod.hasAnnotatedQuery()) {
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, queryMethod.getAnnotatedQuery());
}
return new ElasticsearchPartQuery(queryMethod, elasticsearchOperations);
}
}
}
/*
* Copyright 2013-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.repository.support;
import static org.springframework.data.querydsl.QueryDslUtils.*;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.UUID;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.query.ElasticsearchPartQuery;
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.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.QueryLookupStrategy;
import org.springframework.data.repository.query.RepositoryQuery;
import org.springframework.util.Assert;
/**
* Factory to create {@link ElasticsearchRepository}
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Ryan Henszey
* @author Gad Akuka
* @author Mark Paluch
*/
public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport {
private final ElasticsearchOperations elasticsearchOperations;
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());
}
@Override
public <T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
return entityInformationCreator.getEntityInformation(domainClass);
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
protected Object getTargetRepository(RepositoryInformation metadata) {
return getTargetRepositoryViaReflection(metadata,getEntityInformation(metadata.getDomainType()), elasticsearchOperations);
}
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
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())
|| 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());
}
}
private static boolean isQueryDslRepository(Class<?> repositoryInterface) {
return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface);
}
@Override
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)
*/
@Override
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory factory,
NamedQueries namedQueries) {
ElasticsearchQueryMethod queryMethod = new ElasticsearchQueryMethod(method, metadata, factory);
String namedQueryName = queryMethod.getNamedQueryName();
if (namedQueries.hasQuery(namedQueryName)) {
String namedQuery = namedQueries.getQuery(namedQueryName);
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, namedQuery);
} else if (queryMethod.hasAnnotatedQuery()) {
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, queryMethod.getAnnotatedQuery());
}
return new ElasticsearchPartQuery(queryMethod, elasticsearchOperations);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013 the original author or authors.
* Copyright 2013-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.
@@ -29,19 +29,31 @@ import org.springframework.util.Assert;
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Mark Paluch
*/
public class ElasticsearchRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends
RepositoryFactoryBeanSupport<T, S, ID> {
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.
*
* @param operations the operations to set
*/
public void setElasticsearchOperations(ElasticsearchOperations operations) {
Assert.notNull(operations);
Assert.notNull(operations, "ElasticsearchOperations must not be null!");
setMappingContext(operations.getElasticsearchConverter().getMappingContext());
this.operations = operations;
}
@@ -0,0 +1,47 @@
/*
* 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;
}
}
@@ -0,0 +1 @@
org.springframework.data.repository.core.support.RepositoryFactorySupport=org.springframework.data.elasticsearch.repository.support.ElasticsearchRepositoryFactory
+114
View File
@@ -1,6 +1,120 @@
Spring Data Elasticsearch Changelog
===================================
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).
Changes in version 2.1.2.RELEASE (2017-04-19)
---------------------------------------------
* DATAES-335 - Release 2.1.2 (Ingalls SR2).
Changes in version 3.0.0.M2 (2017-04-04)
----------------------------------------
* DATAES-342 - Adapt to API changes in RepositoryConfigurationExtensionSupport.
* DATAES-329 - Remove references to single-argument assertion methods of Spring.
* DATAES-328 - Integrate Data Commons Java 8 upgrade branch.
* DATAES-325 - Remove references to GenericCollectionTypeResolver in favor of ResolvableType.
* DATAES-322 - Update project documentation with the CLA tool integration.
* DATAES-315 - Adapt API in RepositoryFactoryBeanSupport implementation.
* DATAES-313 - Register repository factory in spring.factories for multi-store support.
* DATAES-311 - Release 3.0 M2 (Kay).
Changes in version 2.0.8.RELEASE (2017-03-02)
---------------------------------------------
* DATAES-329 - Remove references to single-argument assertion methods of Spring.
* DATAES-326 - Release 2.0.8 (Hopper SR8).
Changes in version 2.1.1.RELEASE (2017-03-02)
---------------------------------------------
* DATAES-329 - Remove references to single-argument assertion methods of Spring.
* DATAES-327 - Release 2.1.1 (Ingalls SR1).
* DATAES-325 - Remove references to GenericCollectionTypeResolver in favor of ResolvableType.
Changes in version 2.0.7.RELEASE (2017-01-26)
---------------------------------------------
* DATAES-319 - Release 2.0.7 (Hopper SR7).
Changes in version 2.1.0.RELEASE (2017-01-26)
---------------------------------------------
* DATAES-322 - Update project documentation with the CLA tool integration.
* DATAES-320 - Release 2.1 GA (Ingalls).
Changes in version 2.0.6.RELEASE (2016-12-21)
---------------------------------------------
* DATAES-304 - Release 2.0.6 (Hopper SR6).
Changes in version 2.1.0.RC1 (2016-12-21)
-----------------------------------------
* DATAES-315 - Adapt API in RepositoryFactoryBeanSupport implementation.
* DATAES-313 - Register repository factory in spring.factories for multi-store support.
* DATAES-289 - Upgrade to Elasticsearch 2.4.
* DATAES-284 - Downgrade to Jackson 2.7.5 until Elasticsearch is compatible with 2.8.
* DATAES-281 - Can't save entity without id setter.
* DATAES-275 - Release 2.1 RC1 (Ingalls).
Changes in version 3.0.0.M1 (2016-11-23)
----------------------------------------
* DATAES-307 - Set up 3.0 development.
* DATAES-306 - Release 3.0 M1 (Kay).
Changes in version 2.0.5.RELEASE (2016-11-03)
---------------------------------------------
* DATAES-300 - Release 2.0.5 (Hopper SR5).
Changes in version 2.0.4.RELEASE (2016-09-29)
---------------------------------------------
* DATAES-297 - Release 2.0.4 (Hopper SR4).
Changes in version 1.3.6.RELEASE (2016-09-29)
---------------------------------------------
* DATAES-299 - Release 1.3.6 (Gosling SR6).
Changes in version 1.3.5.RELEASE (2016-09-20)
---------------------------------------------
* DATAES-296 - Release 1.3.5 (Gosling SR5).
Changes in version 2.0.3.RELEASE (2016-09-20)
---------------------------------------------
* DATAES-281 - Can't save entity without id setter.
* DATAES-268 - Release 2.0.3 (Hopper SR3).
Changes in version 2.1.0.M1 (2016-07-27)
----------------------------------------
* DATAES-262 - Upgrade Elasticsearch to 2.3.3.
* DATAES-250 - Release 2.1 M1 (Ingalls).
Changes in version 2.0.2.RELEASE (2016-06-15)
---------------------------------------------
* DATAES-251 - Release 2.0.2 (Hopper SR2).
Changes in version 2.0.1.RELEASE (2016-04-06)
---------------------------------------------
* DATAES-249 - Release 2.0.1 (Hopper SR1).
Changes in version 2.0.0.RELEASE (2016-04-06)
---------------------------------------------
* DATAES-245 - Release 2.0 GA (Hopper).
+1 -1
View File
@@ -1,4 +1,4 @@
Spring Data Elasticsearch 2.0 GA
Spring Data Elasticsearch 2.1.3
Copyright (c) [2013-2016] Pivotal Software, Inc.
This product is licensed to you under the Apache License, Version 2.0 (the "License").
@@ -0,0 +1,140 @@
/*
* 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 +
'}';
}
}
@@ -1,96 +1,100 @@
/*
* 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);
}
}
/*
* 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);
}
}
@@ -22,6 +22,7 @@ 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 +48,7 @@ public class CustomResultMapper implements ResultsMapper {
}
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@@ -19,22 +19,35 @@ import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Value;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.util.ArrayIterator;
import org.elasticsearch.action.get.GetResponse;
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.annotation.AccessType;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.DefaultResultMapperTests.ImmutableEntity;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.entities.Car;
/**
@@ -51,7 +64,33 @@ public class DefaultResultMapperTests {
@Before
public void init() {
MockitoAnnotations.initMocks(this);
resultMapper = new DefaultResultMapper();
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, null);
//Then
page.hasFacets();
assertThat(page.hasAggregations(), is(true));
assertThat(page.getAggregation("engine").getName(), is("Diesel"));
}
@Test
@@ -104,6 +143,28 @@ 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);
@@ -132,4 +193,12 @@ public class DefaultResultMapperTests {
result.put("model", new InternalSearchHitField("model", Arrays.<Object>asList(model)));
return result;
}
@Document(indexName = "someIndex")
@NoArgsConstructor(force = true)
@Getter
static class ImmutableEntity {
private final String id, name;
}
}
@@ -41,9 +41,14 @@ 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.*;
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.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.*;
import org.springframework.data.elasticsearch.entities.*;
import org.springframework.data.util.CloseableIterator;
@@ -632,12 +637,12 @@ public class ElasticsearchTemplateTests {
// when
Page<String> page = elasticsearchTemplate.queryForPage(searchQuery, String.class, new SearchResultMapper() {
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<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 PageImpl<T>((List<T>) values);
return new AggregatedPageImpl<T>((List<T>) values);
}
});
// then
@@ -791,7 +796,7 @@ public class ElasticsearchTemplateTests {
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, new SearchResultMapper() {
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<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();
@@ -802,7 +807,7 @@ public class ElasticsearchTemplateTests {
}
if (result.size() > 0) {
return new PageImpl<T>((List<T>) result);
return new AggregatedPageImpl<T>((List<T>) result);
}
return null;
}
@@ -843,7 +848,7 @@ public class ElasticsearchTemplateTests {
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 10000L, new SearchResultMapper() {
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<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();
@@ -854,7 +859,7 @@ public class ElasticsearchTemplateTests {
}
if (result.size() > 0) {
return new PageImpl<T>((List<T>) result);
return new AggregatedPageImpl<T>((List<T>) result);
}
return null;
}
@@ -892,7 +897,7 @@ public class ElasticsearchTemplateTests {
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, new SearchResultMapper() {
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<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) {
@@ -904,7 +909,7 @@ public class ElasticsearchTemplateTests {
chunk.add(user);
}
if (chunk.size() > 0) {
return new PageImpl<T>((List<T>) chunk);
return new AggregatedPageImpl<T>((List<T>) chunk);
}
return null;
}
@@ -937,7 +942,7 @@ public class ElasticsearchTemplateTests {
while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, new SearchResultMapper() {
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<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) {
@@ -949,7 +954,7 @@ public class ElasticsearchTemplateTests {
chunk.add(user);
}
if (chunk.size() > 0) {
return new PageImpl<T>((List<T>) chunk);
return new AggregatedPageImpl<T>((List<T>) chunk);
}
return null;
}
@@ -1243,7 +1248,7 @@ public class ElasticsearchTemplateTests {
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() {
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<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) {
@@ -1256,7 +1261,7 @@ public class ElasticsearchTemplateTests {
chunk.add(user);
}
if (chunk.size() > 0) {
return new PageImpl<T>((List<T>) chunk);
return new AggregatedPageImpl<T>((List<T>) chunk);
}
return null;
}
@@ -1310,7 +1315,7 @@ public class ElasticsearchTemplateTests {
// then
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() {
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> values = new ArrayList<SampleEntity>();
for (SearchHit searchHit : response.getHits()) {
SampleEntity sampleEntity = new SampleEntity();
@@ -1318,7 +1323,7 @@ public class ElasticsearchTemplateTests {
sampleEntity.setMessage((String) searchHit.getSource().get("message"));
values.add(sampleEntity);
}
return new PageImpl<T>((List<T>) values);
return new AggregatedPageImpl<T>((List<T>) values);
}
});
assertThat(page, is(notNullValue()));
@@ -1480,7 +1485,7 @@ public class ElasticsearchTemplateTests {
.withTypes(TYPE_NAME).withQuery(matchAllQuery()).build();
Page<Map> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, Map.class, new SearchResultMapper() {
@Override
public <T> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<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) {
@@ -1495,7 +1500,7 @@ public class ElasticsearchTemplateTests {
chunk.add(person);
}
if (chunk.size() > 0) {
return new PageImpl<T>((List<T>) chunk);
return new AggregatedPageImpl<T>((List<T>) chunk);
}
return null;
}
@@ -1994,7 +1999,7 @@ 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> Page<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
public <T> AggregatedPage<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"));
@@ -2002,7 +2007,7 @@ public class ElasticsearchTemplateTests {
String lastName = StringUtils.isNotEmpty((String) searchHit.getSource().get("lastName")) ? (String) searchHit.getSource().get("lastName") : "";
values.add(new ResultAggregator(id, firstName, lastName));
}
return new PageImpl<T>((List<T>) values);
return new AggregatedPageImpl<T>((List<T>) values);
}
});
@@ -164,4 +164,20 @@ 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
}
}
@@ -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,8 +20,6 @@ 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;
@@ -36,13 +34,12 @@ 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")
@@ -64,7 +61,7 @@ public class ElasticsearchTemplateFacetTests {
elasticsearchTemplate.deleteIndex(ArticleEntity.class);
elasticsearchTemplate.createIndex(ArticleEntity.class);
elasticsearchTemplate.putMapping(ArticleEntity.class);
elasticsearchTemplate.refresh(ArticleEntity.class, true);
elasticsearchTemplate.refresh(ArticleEntity.class);
IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex();
IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex();
@@ -75,7 +72,7 @@ public class ElasticsearchTemplateFacetTests {
elasticsearchTemplate.index(article2);
elasticsearchTemplate.index(article3);
elasticsearchTemplate.index(article4);
elasticsearchTemplate.refresh(ArticleEntity.class, true);
elasticsearchTemplate.refresh(ArticleEntity.class);
}
@Test
@@ -92,21 +89,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(4));
assertThat(term.getCount(), is(4l));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3));
assertThat(term.getCount(), is(3l));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2));
assertThat(term.getCount(), is(2l));
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1));
assertThat(term.getCount(), is(1l));
assertThat(facet.getTotal(), is(10l));
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -117,27 +114,26 @@ 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(3)));
assertThat(result.getNumberOfElements(), is(equalTo(4)));
TermResult facet = (TermResult) result.getFacet(facetName);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(3));
assertThat(term.getCount(), is(4l));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(2));
assertThat(term.getCount(), is(3l));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(1));
assertThat(term.getCount(), is(2l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -147,23 +143,26 @@ 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(3)));
assertThat(result.getNumberOfElements(), is(equalTo(4)));
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(1));
assertThat(facet.getTerms().size(), is(2));
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(1));
assertThat(term.getCount(), is(2l));
Term term1 = facet.getTerms().get(1);
assertThat(term1.getTerm(), is(JONATHAN_YAN));
assertThat(term1.getCount(), is(1l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(5l));
assertThat(facet.getTotal(), is(2l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -182,21 +181,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(3));
assertThat(term.getCount(), is(3l));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1));
assertThat(term.getCount(), is(1l));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2));
assertThat(term.getCount(), is(2l));
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4));
assertThat(term.getCount(), is(4l));
assertThat(facet.getTotal(), is(10l));
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -216,21 +215,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(1));
assertThat(term.getCount(), is(1l));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2));
assertThat(term.getCount(), is(2l));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3));
assertThat(term.getCount(), is(3l));
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4));
assertThat(term.getCount(), is(4l));
assertThat(facet.getTotal(), is(10l));
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -252,19 +251,19 @@ public class ElasticsearchTemplateFacetTests {
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2000)));
assertThat(term.getCount(), is(3));
assertThat(term.getCount(), is(3l));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2001)));
assertThat(term.getCount(), is(2));
assertThat(term.getCount(), is(2l));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2002)));
assertThat(term.getCount(), is(1));
assertThat(term.getCount(), is(1l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getTotal(), is(3l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(1l));
assertThat(facet.getMissing(), is(0l));
}
@Test
@@ -273,36 +272,35 @@ 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(3)));
assertThat(result.getNumberOfElements(), is(equalTo(4)));
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(equalTo(3)));
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2000)));
assertThat(term.getCount(), is(3));
assertThat(term.getCount(), is(3l));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2001)));
assertThat(term.getCount(), is(2));
assertThat(term.getCount(), is(2l));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2002)));
assertThat(term.getCount(), is(1));
assertThat(term.getCount(), is(1l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getTotal(), is(3l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@Test
public void shouldReturnSingleFacetOverYearsAndAuthorsForGivenQuery() {
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExeptionsForMultiFieldFacet() {
// given
String facetName = "fyears";
@@ -318,31 +316,31 @@ public class ElasticsearchTemplateFacetTests {
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2000)));
assertThat(term.getCount(), is(3));
assertThat(term.getCount(), is(3l));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2001)));
assertThat(term.getCount(), is(2));
assertThat(term.getCount(), is(2l));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2002)));
assertThat(term.getCount(), is(1));
assertThat(term.getCount(), is(1l));
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3));
assertThat(term.getCount(), is(3l));
term = facet.getTerms().get(4);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1));
assertThat(term.getCount(), is(1l));
term = facet.getTerms().get(5);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2));
assertThat(term.getCount(), is(2l));
term = facet.getTerms().get(6);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4));
assertThat(term.getCount(), is(4l));
assertThat(facet.getTotal(), is(16l));
assertThat(facet.getOther(), is(0l));
@@ -369,46 +367,46 @@ public class ElasticsearchTemplateFacetTests {
Term numberTerm = numberFacet.getTerms().get(0);
assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2000)));
assertThat(numberTerm.getCount(), is(3));
assertThat(numberTerm.getCount(), is(3l));
numberTerm = numberFacet.getTerms().get(1);
assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2001)));
assertThat(numberTerm.getCount(), is(2));
assertThat(numberTerm.getCount(), is(2l));
numberTerm = numberFacet.getTerms().get(2);
assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2002)));
assertThat(numberTerm.getCount(), is(1));
assertThat(numberTerm.getCount(), is(1l));
TermResult stringFacet = (TermResult) result.getFacet(stringFacetName);
Term stringTerm = stringFacet.getTerms().get(0);
assertThat(stringTerm.getTerm(), is(ARTUR_KONCZAK));
assertThat(stringTerm.getCount(), is(3));
assertThat(stringTerm.getCount(), is(3l));
stringTerm = stringFacet.getTerms().get(1);
assertThat(stringTerm.getTerm(), is(JONATHAN_YAN));
assertThat(stringTerm.getCount(), is(1));
assertThat(stringTerm.getCount(), is(1l));
stringTerm = stringFacet.getTerms().get(2);
assertThat(stringTerm.getTerm(), is(MOHSIN_HUSEN));
assertThat(stringTerm.getCount(), is(2));
assertThat(stringTerm.getCount(), is(2l));
stringTerm = stringFacet.getTerms().get(3);
assertThat(stringTerm.getTerm(), is(RIZWAN_IDREES));
assertThat(stringTerm.getCount(), is(4));
assertThat(stringTerm.getCount(), is(4l));
assertThat(stringFacet.getTotal(), is(10l));
assertThat(stringFacet.getTotal(), is(4l));
assertThat(stringFacet.getOther(), is(0l));
assertThat(stringFacet.getMissing(), is(0l));
}
@Test
public void shouldReturnFacetedYearsForNativeFacet() {
@Test(expected = UnsupportedOperationException.class)
public void shouldThrowExceptionForNativeFacets() {
// given
String facetName = "fyears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new NativeFacetRequest(FacetBuilders.termsFacet(facetName).field("publishedYears"))).build();
.withFacet(new NativeFacetRequest()).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
@@ -419,15 +417,15 @@ public class ElasticsearchTemplateFacetTests {
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2000)));
assertThat(term.getCount(), is(3));
assertThat(term.getCount(), is(3l));
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2001)));
assertThat(term.getCount(), is(2));
assertThat(term.getCount(), is(2l));
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Integer.toString(YEAR_2002)));
assertThat(term.getCount(), is(1));
assertThat(term.getCount(), is(1l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(0l));
@@ -439,12 +437,11 @@ 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(3)));
assertThat(result.getNumberOfElements(), is(equalTo(4)));
TermResult facet = (TermResult) result.getFacet(facetName);
@@ -452,10 +449,10 @@ public class ElasticsearchTemplateFacetTests {
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(2));
assertThat(term.getCount(), is(3l));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(4l));
assertThat(facet.getTotal(), is(1l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -464,18 +461,17 @@ 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(3)));
assertThat(result.getNumberOfElements(), is(equalTo(4)));
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(4));
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
}
@@ -499,7 +495,7 @@ public class ElasticsearchTemplateFacetTests {
assertThat(facet.getRanges().size(), is(equalTo(3)));
Range range = facet.getRanges().get(0);
assertThat(range.getFrom(), nullValue());
assertThat(range.getFrom(), is(Double.NEGATIVE_INFINITY));
assertThat(range.getTo(), is((double) YEAR_2000));
assertThat(range.getCount(), is(0L));
assertThat(range.getTotal(), is(0.0));
@@ -508,17 +504,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(6000.0));
assertThat(range.getTotal(), is(12004.0));
range = facet.getRanges().get(2);
assertThat(range.getFrom(), is((double) YEAR_2002));
assertThat(range.getTo(), nullValue());
assertThat(range.getTo(), is(Double.POSITIVE_INFINITY));
assertThat(range.getCount(), is(1L));
assertThat(range.getTotal(), is(2002.0));
assertThat(range.getTotal(), is(6003.0));
}
@Test
public void shouldReturnKeyValueRangeFacetForGivenQuery() {
public void shouldReturnKeyValueRangeFacetForStringValuesInGivenQuery() {
// given
String facetName = "rangeScoreOverYears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
@@ -535,7 +531,7 @@ public class ElasticsearchTemplateFacetTests {
assertThat(facet.getRanges().size(), is(equalTo(3)));
Range range = facet.getRanges().get(0);
assertThat(range.getFrom(), nullValue());
assertThat(range.getFrom(), is(Double.NEGATIVE_INFINITY));
assertThat(range.getTo(), is((double) YEAR_2000));
assertThat(range.getCount(), is(0L));
assertThat(range.getTotal(), is(0.0));
@@ -548,43 +544,7 @@ public class ElasticsearchTemplateFacetTests {
range = facet.getRanges().get(2);
assertThat(range.getFrom(), is((double) YEAR_2002));
assertThat(range.getTo(), nullValue());
assertThat(range.getCount(), is(1L));
assertThat(range.getTotal(), is(40.0));
}
@Test
public void 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.getTo(), is(Double.POSITIVE_INFINITY));
assertThat(range.getCount(), is(1L));
assertThat(range.getTotal(), is(40.0));
}
@@ -635,4 +595,4 @@ public class ElasticsearchTemplateFacetTests {
assertThat(unit.getCount(), is(1L));
}
}
*/
@@ -0,0 +1,23 @@
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<User>();
}
@@ -0,0 +1,88 @@
/*
* 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.entities;
import java.util.UUID;
import lombok.*;
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;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
/**
* @author Gad Akuka
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-uuid-keyed", type = "test-type-uuid-keyed", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleEntityUUIDKeyed {
@Id
private UUID id;
private String type;
private String message;
private int rate;
@ScriptedField
private Long scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version
private Long version;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SampleEntityUUIDKeyed that = (SampleEntityUUIDKeyed) o;
if (available != that.available) return false;
if (rate != that.rate) return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) : that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (location != null ? !location.equals(that.location) : that.location != null) return false;
if (message != null ? !message.equals(that.message) : that.message != null) return false;
if (type != null ? !type.equals(that.type) : that.type != null) return false;
if (version != null ? !version.equals(that.version) : that.version != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
@@ -0,0 +1,22 @@
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 = "users", type = "user")
public class User {
@Id
private String id;
@Field(type= FieldType.Nested,ignoreFields={"users"})
private Set<Group> groups = new HashSet<Group>();
}
@@ -0,0 +1,24 @@
/*
* Copyright 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.
* 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.immutable;
import org.springframework.data.repository.CrudRepository;
/**
* @author Young Gu
* @author Oliver Gierke
*/
public interface ImmutableElasticsearchRepository extends CrudRepository<ImmutableEntity, String> {}
@@ -0,0 +1,65 @@
/*
* Copyright 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.
* 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.immutable;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Young Gu
* @author Oliver Gierke
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:immutable-repository-test.xml")
public class ImmutableElasticsearchRepositoryTests {
@Autowired ImmutableElasticsearchRepository repository;
@Autowired ElasticsearchOperations operations;
@Before
public void before() {
operations.deleteIndex(ImmutableEntity.class);
operations.createIndex(ImmutableEntity.class);
operations.refresh(ImmutableEntity.class);
}
/**
* @see DATAES-281
*/
@Test
public void shouldSaveAndFindImmutableDocument() {
// when
ImmutableEntity entity = repository.save(new ImmutableEntity("test name"));
assertThat(entity.getId(), is(notNullValue()));
// then
ImmutableEntity entityFromElasticSearch = repository.findOne(entity.getId());
assertThat(entityFromElasticSearch.getName(), is("test name"));
assertThat(entityFromElasticSearch.getId(), is(entity.getId()));
}
}
@@ -0,0 +1,38 @@
/*
* 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.immutable;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author Young Gu
* @author Oliver Gierke
*/
@Document(indexName = "test-index")
@NoArgsConstructor(force = true)
@Getter
public class ImmutableEntity {
private final String id, name;
public ImmutableEntity(String name) {
this.id = null;
this.name = name;
}
}
@@ -0,0 +1,34 @@
/*
* 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.repositories.sample;
import java.util.List;
import java.util.UUID;
import org.springframework.data.elasticsearch.entities.SampleEntityUUIDKeyed;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* @author Gad Akuka
*/
public interface SampleUUIDKeyedElasticsearchRepository extends ElasticsearchRepository<SampleEntityUUIDKeyed, UUID> {
long deleteById(UUID id);
List<SampleEntityUUIDKeyed> deleteByAvailable(boolean available);
List<SampleEntityUUIDKeyed> deleteByMessage(String message);
void deleteByType(String type);
}
@@ -0,0 +1,505 @@
/*
* 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.
* 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 static org.elasticsearch.index.query.QueryBuilders.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.util.*;
import org.junit.Before;
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.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.entities.SampleEntityUUIDKeyed;
import org.springframework.data.elasticsearch.repositories.sample.SampleUUIDKeyedElasticsearchRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Gad Akuka
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/simple-repository-test.xml")
public class UUIDElasticsearchRepositoryTests {
@Autowired
private SampleUUIDKeyedElasticsearchRepository repository;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
elasticsearchTemplate.deleteIndex(SampleEntityUUIDKeyed.class);
elasticsearchTemplate.createIndex(SampleEntityUUIDKeyed.class);
elasticsearchTemplate.putMapping(SampleEntityUUIDKeyed.class);
elasticsearchTemplate.refresh(SampleEntityUUIDKeyed.class);
}
@Test
public void shouldDoBulkIndexDocument() {
// given
UUID documentId1 = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed1.setId(documentId1);
sampleEntityUUIDKeyed1.setMessage("some message");
sampleEntityUUIDKeyed1.setVersion(System.currentTimeMillis());
UUID documentId2 = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed2 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed2.setId(documentId2);
sampleEntityUUIDKeyed2.setMessage("some message");
sampleEntityUUIDKeyed2.setVersion(System.currentTimeMillis());
// when
repository.save(Arrays.asList(sampleEntityUUIDKeyed1, sampleEntityUUIDKeyed2));
// then
SampleEntityUUIDKeyed entity1FromElasticSearch = repository.findOne(documentId1);
assertThat(entity1FromElasticSearch, is(notNullValue()));
SampleEntityUUIDKeyed entity2FromElasticSearch = repository.findOne(documentId2);
assertThat(entity2FromElasticSearch, is(notNullValue()));
}
@Test
public void shouldSaveDocument() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("some message");
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
// when
repository.save(sampleEntityUUIDKeyed);
// then
SampleEntityUUIDKeyed entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(notNullValue()));
}
@Test
public void shouldFindDocumentById() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("some message");
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed);
// when
SampleEntityUUIDKeyed entityFromElasticSearch = repository.findOne(documentId);
// then
assertThat(entityFromElasticSearch, is(notNullValue()));
assertThat(sampleEntityUUIDKeyed, is((equalTo(sampleEntityUUIDKeyed))));
}
@Test
public void shouldReturnCountOfDocuments() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("some message");
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed);
// when
Long count = repository.count();
// then
assertThat(count, is(greaterThanOrEqualTo(1L)));
}
@Test
public void shouldFindAllDocuments() {
// when
Iterable<SampleEntityUUIDKeyed> results = repository.findAll();
// then
assertThat(results, is(notNullValue()));
}
@Test
public void shouldDeleteDocument() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("some message");
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed);
// when
repository.delete(documentId);
// then
SampleEntityUUIDKeyed entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(nullValue()));
}
@Test
public void shouldSearchDocumentsGivenSearchQuery() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("some test message");
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed);
SearchQuery query = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test")).build();
// when
Page<SampleEntityUUIDKeyed> page = repository.search(query);
// then
assertThat(page, is(notNullValue()));
assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1)));
}
@Test
public void shouldSearchDocumentsGivenElasticsearchQuery() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("hello world.");
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed);
// when
Page<SampleEntityUUIDKeyed> page = repository.search(termQuery("message", "world"), new PageRequest(0, 50));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1)));
}
/*
DATAES-82
*/
@Test
public void shouldFindAllByIdQuery() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("hello world.");
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed);
UUID documentId2 = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed2 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed2.setId(documentId2);
sampleEntityUUIDKeyed2.setMessage("hello world.");
sampleEntityUUIDKeyed2.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed2);
// when
LinkedList<SampleEntityUUIDKeyed> sampleEntities = (LinkedList<SampleEntityUUIDKeyed>) repository.findAll(Arrays.asList(documentId, documentId2));
// then
assertNotNull("sample entities cant be null..", sampleEntities);
assertThat(sampleEntities.size(), is(2));
assertThat(sampleEntities.get(0).getId(), isIn(Arrays.asList(documentId, documentId2)));
assertThat(sampleEntities.get(1).getId(), isIn(Arrays.asList(documentId, documentId2)));
}
@Test
public void shouldSaveIterableEntities() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed1.setId(documentId);
sampleEntityUUIDKeyed1.setMessage("hello world.");
sampleEntityUUIDKeyed1.setVersion(System.currentTimeMillis());
UUID documentId2 = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed2 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed2.setId(documentId2);
sampleEntityUUIDKeyed2.setMessage("hello world.");
sampleEntityUUIDKeyed2.setVersion(System.currentTimeMillis());
Iterable<SampleEntityUUIDKeyed> sampleEntities = Arrays.asList(sampleEntityUUIDKeyed1, sampleEntityUUIDKeyed2);
// when
repository.save(sampleEntities);
// then
Page<SampleEntityUUIDKeyed> entities = repository.search(termQuery("id", documentId), new PageRequest(0, 50));
assertNotNull(entities);
}
@Test
public void shouldReturnTrueGivenDocumentWithIdExists() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("hello world.");
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed);
// when
boolean exist = repository.exists(documentId);
// then
assertEquals(exist, true);
}
@Test
public void shouldDeleteAll() {
// when
repository.deleteAll();
// then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
Page<SampleEntityUUIDKeyed> sampleEntities = repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(), equalTo(0L));
}
@Test
public void shouldDeleteById() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("hello world.");
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed);
// when
long result = repository.deleteById(documentId);
// then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build();
Page<SampleEntityUUIDKeyed> sampleEntities = repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(), equalTo(0L));
assertThat(result, equalTo(1L));
}
@Test
public void shouldDeleteByMessageAndReturnList() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed1.setId(documentId);
sampleEntityUUIDKeyed1.setMessage("hello world 1");
sampleEntityUUIDKeyed1.setAvailable(true);
sampleEntityUUIDKeyed1.setVersion(System.currentTimeMillis());
documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed2 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed2.setId(documentId);
sampleEntityUUIDKeyed2.setMessage("hello world 2");
sampleEntityUUIDKeyed2.setAvailable(true);
sampleEntityUUIDKeyed2.setVersion(System.currentTimeMillis());
documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed3 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed3.setId(documentId);
sampleEntityUUIDKeyed3.setMessage("hello world 3");
sampleEntityUUIDKeyed3.setAvailable(false);
sampleEntityUUIDKeyed3.setVersion(System.currentTimeMillis());
repository.save(Arrays.asList(sampleEntityUUIDKeyed1, sampleEntityUUIDKeyed2, sampleEntityUUIDKeyed3));
// when
List<SampleEntityUUIDKeyed> result = repository.deleteByAvailable(true);
repository.refresh();
// then
assertThat(result.size(), equalTo(2));
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
Page<SampleEntityUUIDKeyed> sampleEntities = repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(), equalTo(1L));
}
@Test
public void shouldDeleteByListForMessage() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed1.setId(documentId);
sampleEntityUUIDKeyed1.setMessage("hello world 1");
sampleEntityUUIDKeyed1.setVersion(System.currentTimeMillis());
documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed2 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed2.setId(documentId);
sampleEntityUUIDKeyed2.setMessage("hello world 2");
sampleEntityUUIDKeyed2.setVersion(System.currentTimeMillis());
documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed3 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed3.setId(documentId);
sampleEntityUUIDKeyed3.setMessage("hello world 3");
sampleEntityUUIDKeyed3.setVersion(System.currentTimeMillis());
repository.save(Arrays.asList(sampleEntityUUIDKeyed1, sampleEntityUUIDKeyed2, sampleEntityUUIDKeyed3));
// when
List<SampleEntityUUIDKeyed> result = repository.deleteByMessage("hello world 3");
repository.refresh();
// then
assertThat(result.size(), equalTo(1));
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
Page<SampleEntityUUIDKeyed> sampleEntities = repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(), equalTo(2L));
}
@Test
public void shouldDeleteByType() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed1.setId(documentId);
sampleEntityUUIDKeyed1.setType("book");
sampleEntityUUIDKeyed1.setVersion(System.currentTimeMillis());
documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed2 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed2.setId(documentId);
sampleEntityUUIDKeyed2.setType("article");
sampleEntityUUIDKeyed2.setVersion(System.currentTimeMillis());
documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed3 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed3.setId(documentId);
sampleEntityUUIDKeyed3.setType("image");
sampleEntityUUIDKeyed3.setVersion(System.currentTimeMillis());
repository.save(Arrays.asList(sampleEntityUUIDKeyed1, sampleEntityUUIDKeyed2, sampleEntityUUIDKeyed3));
// when
repository.deleteByType("article");
repository.refresh();
// then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
Page<SampleEntityUUIDKeyed> sampleEntities = repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(), equalTo(2L));
}
@Test
public void shouldDeleteEntity() {
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("hello world.");
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed);
// when
repository.delete(sampleEntityUUIDKeyed);
repository.refresh();
// then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("id", documentId)).build();
Page<SampleEntityUUIDKeyed> sampleEntities = repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(), equalTo(0L));
}
@Test
public void shouldReturnIterableEntities() {
// given
UUID documentId1 = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed1.setId(documentId1);
sampleEntityUUIDKeyed1.setMessage("hello world.");
sampleEntityUUIDKeyed1.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed1);
UUID documentId2 = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed2 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed2.setId(documentId2);
sampleEntityUUIDKeyed2.setMessage("hello world.");
sampleEntityUUIDKeyed2.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed2);
// when
Iterable<SampleEntityUUIDKeyed> sampleEntities = repository.search(termQuery("id", documentId1));
// then
assertNotNull("sample entities cant be null..", sampleEntities);
}
@Test
public void shouldDeleteIterableEntities() {
// given
UUID documentId1 = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed1 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed1.setId(documentId1);
sampleEntityUUIDKeyed1.setMessage("hello world.");
sampleEntityUUIDKeyed1.setVersion(System.currentTimeMillis());
UUID documentId2 = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed2 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed2.setId(documentId2);
sampleEntityUUIDKeyed2.setMessage("hello world.");
sampleEntityUUIDKeyed2.setVersion(System.currentTimeMillis());
repository.save(sampleEntityUUIDKeyed2);
Iterable<SampleEntityUUIDKeyed> sampleEntities = Arrays.asList(sampleEntityUUIDKeyed2, sampleEntityUUIDKeyed2);
// when
repository.delete(sampleEntities);
// then
assertThat(repository.findOne(documentId1), is(nullValue()));
assertThat(repository.findOne(documentId2), is(nullValue()));
}
@Test
public void shouldSortByGivenField() {
// todo
// given
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage("world");
repository.save(sampleEntityUUIDKeyed);
UUID documentId2 = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed2 = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed2.setId(documentId2);
sampleEntityUUIDKeyed2.setMessage("hello");
repository.save(sampleEntityUUIDKeyed2);
// when
Iterable<SampleEntityUUIDKeyed> sampleEntities = repository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC, "message")));
// then
assertThat(sampleEntities, is(notNullValue()));
}
@Test
public void shouldReturnSimilarEntities() {
// given
String sampleMessage = "So we build a web site or an application and want to add search to it, "
+ "and then it hits us: getting search working is hard. We want our search solution to be fast,"
+ " we want a painless setup and a completely free search schema, we want to be able to index data simply using JSON over HTTP, "
+ "we want our search server to be always available, we want to be able to start with one machine and scale to hundreds, "
+ "we want real-time search, we want simple multi-tenancy, and we want a solution that is built for the cloud.";
List<SampleEntityUUIDKeyed> sampleEntities = createSampleEntitiesWithMessage(sampleMessage, 30);
repository.save(sampleEntities);
// when
Page<SampleEntityUUIDKeyed> results = repository.searchSimilar(sampleEntities.get(0), new String[]{"message"}, new PageRequest(0, 5));
// then
assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L)));
}
private static List<SampleEntityUUIDKeyed> createSampleEntitiesWithMessage(String message, int numberOfEntities) {
List<SampleEntityUUIDKeyed> sampleEntities = new ArrayList<SampleEntityUUIDKeyed>();
for (int i = 0; i < numberOfEntities; i++) {
UUID documentId = UUID.randomUUID();
SampleEntityUUIDKeyed sampleEntityUUIDKeyed = new SampleEntityUUIDKeyed();
sampleEntityUUIDKeyed.setId(documentId);
sampleEntityUUIDKeyed.setMessage(message);
sampleEntityUUIDKeyed.setRate(2);
sampleEntityUUIDKeyed.setVersion(System.currentTimeMillis());
sampleEntities.add(sampleEntityUUIDKeyed);
}
return sampleEntities;
}
}
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<import resource="infrastructure.xml"/>
<bean name="elasticsearchTemplate"
class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client"/>
</bean>
<elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.immutable"/>
</beans>
@@ -34,7 +34,7 @@
description=Groovy scripting integration for Elasticsearch
#
# 'version': plugin's version
version=2.2.0
version=2.4.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.2.0
elasticsearch.version=2.4.0
#
### deprecated elements for jvm plugins :
#
@@ -24,15 +24,12 @@ grant {
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
// groovy runtime (TODO: clean these up if possible)
permission org.elasticsearch.script.ClassPermission "groovy.grape.GrabAnnotationTransformation";
permission org.elasticsearch.script.ClassPermission "groovy.json.JsonOutput";
permission org.elasticsearch.script.ClassPermission "groovy.lang.Binding";
@@ -49,9 +46,11 @@ grant {
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 "sun.reflect.MethodAccessorImpl";
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";
permission org.elasticsearch.script.ClassPermission "groovy.lang.Reference";
};
+2 -2
View File
@@ -10,8 +10,8 @@ Import-Template:
javax.enterprise.*;version="${cdi:[=.=.=,+1.0.0)}";resolution:=optional,
org.apache.commons.lang.*;version="${commonslang:[=.=.=,+1.0.0)}",
com.fasterxml.jackson.*;version="${jackson:[=.=.=,+1.0.0)}";resolution:=optional,
org.elasticsearch.*;version="${elasticsearch:[=.=.=,2.2.0)}",
org.apache.lucene.*;version="5.4.1",
org.elasticsearch.*;version="${elasticsearch:[=.=.=,+1.0.0)}",
org.apache.lucene.*;version="5.5.0",
org.joda.time.*;version="${jodatime:[=.=.=,+1.0.0)}",
org.slf4j.*;version="${slf4j:[=.=.=,+1.0.0)}",
org.springframework.*;version="${spring:[=.=.=.=,+1.0.0)}",