DATAES-579 - Test code cleanup.

Original pull request: #283.
This commit is contained in:
P.J.Meisch 2019-05-09 23:30:30 +02:00 committed by Mark Paluch
parent 287aa45b98
commit 4c206f7de5
164 changed files with 7454 additions and 6143 deletions

View File

@ -37,6 +37,7 @@ import java.util.stream.Collectors;
* @author Kevin Leturc
* @author Zetang Zeng
* @author Dmitriy Yakovlev
* @author Peter-Josef Meisch
*/
public interface ElasticsearchOperations {
@ -108,7 +109,7 @@ public interface ElasticsearchOperations {
* @param clazz
* @param <T>
*/
<T> Map getMapping(Class<T> clazz);
<T> Map<String, Object> getMapping(Class<T> clazz);
/**
* Get mapping for a given indexName and type
@ -116,21 +117,21 @@ public interface ElasticsearchOperations {
* @param indexName
* @param type
*/
Map getMapping(String indexName, String type);
Map<String, Object> getMapping(String indexName, String type);
/**
* Get settings for a given indexName
*
* @param indexName
*/
Map getSetting(String indexName);
Map<String, Object> getSetting(String indexName);
/**
* Get settings for a given class
*
* @param clazz
*/
<T> Map getSetting(Class<T> clazz);
<T> Map<String, Object> getSetting(Class<T> clazz);
/**

View File

@ -124,6 +124,7 @@ import org.springframework.util.StringUtils;
* @author Ivan Greene
* @author Christoph Strobl
* @author Dmitriy Yakovlev
* @author Peter-Josef Meisch
*/
public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<Client>, ApplicationContextAware {
@ -234,10 +235,10 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
}
@Override
public Map getMapping(String indexName, String type) {
public Map<String, Object> getMapping(String indexName, String type) {
Assert.notNull(indexName, "No index defined for putMapping()");
Assert.notNull(type, "No type defined for putMapping()");
Map mappings = null;
Map<String, Object> mappings = null;
try {
mappings = client.admin().indices().getMappings(new GetMappingsRequest().indices(indexName).types(type))
.actionGet().getMappings().get(indexName).get(type).getSourceAsMap();
@ -249,7 +250,7 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
}
@Override
public <T> Map getMapping(Class<T> clazz) {
public <T> Map<String, Object> getMapping(Class<T> clazz) {
return getMapping(getPersistentEntityFor(clazz).getIndexName(), getPersistentEntityFor(clazz).getIndexType());
}
@ -1034,10 +1035,10 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
return createIndex(getPersistentEntityFor(clazz).getIndexName(), settings);
}
private <T> Map getDefaultSettings(ElasticsearchPersistentEntity<T> persistentEntity) {
private <T> Map<String, String> getDefaultSettings(ElasticsearchPersistentEntity<T> persistentEntity) {
if (persistentEntity.isUseServerConfiguration())
return new HashMap();
return new HashMap<>();
return new MapBuilder<String, String>().put("index.number_of_shards", String.valueOf(persistentEntity.getShards()))
.put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas()))
@ -1046,12 +1047,12 @@ public class ElasticsearchTemplate implements ElasticsearchOperations, EsClient<
}
@Override
public <T> Map getSetting(Class<T> clazz) {
public <T> Map<String, Object> getSetting(Class<T> clazz) {
return getSetting(getPersistentEntityFor(clazz).getIndexName());
}
@Override
public Map getSetting(String indexName) {
public Map<String, Object> getSetting(String indexName) {
Assert.notNull(indexName, "No index defined for getSettings");
Settings settings = client.admin().indices().getSettings(new GetSettingsRequest()).actionGet().getIndexToSettings()
.get(indexName);

View File

@ -1,73 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch;
import static org.apache.commons.lang.RandomStringUtils.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.entities.Author;
import org.springframework.data.elasticsearch.entities.Book;
import org.springframework.data.elasticsearch.repositories.book.SampleElasticSearchBookRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Mohsin Husen
* @author Christoph Strobl
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/repository-test-nested-object-books.xml")
public class InnerObjectTests {
@Autowired private SampleElasticSearchBookRepository bookRepository;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
elasticsearchTemplate.deleteIndex(Book.class);
elasticsearchTemplate.createIndex(Book.class);
elasticsearchTemplate.putMapping(Book.class);
elasticsearchTemplate.refresh(Book.class);
}
@Test
public void shouldIndexInnerObject() {
// given
String id = randomAlphanumeric(5);
Book book = new Book();
book.setId(id);
book.setName("xyz");
Author author = new Author();
author.setId("1");
author.setName("ABC");
book.setAuthor(author);
// when
bookRepository.save(book);
// then
assertThat(bookRepository.findById(id), is(notNullValue()));
}
}

View File

@ -16,14 +16,16 @@
package org.springframework.data.elasticsearch;
import static org.apache.commons.lang.RandomStringUtils.*;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.*;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -35,18 +37,19 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.entities.Author;
import org.springframework.data.elasticsearch.entities.Book;
import org.springframework.data.elasticsearch.entities.Car;
import org.springframework.data.elasticsearch.entities.GirlFriend;
import org.springframework.data.elasticsearch.entities.Person;
import org.springframework.data.elasticsearch.entities.PersonMultipleLevelNested;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -54,29 +57,20 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/repository-test-nested-object.xml")
@ContextConfiguration("classpath:/elasticsearch-template-test.xml")
public class NestedObjectTests {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
elasticsearchTemplate.deleteIndex(Book.class);
elasticsearchTemplate.createIndex(Book.class);
elasticsearchTemplate.putMapping(Book.class);
elasticsearchTemplate.refresh(Book.class);
elasticsearchTemplate.deleteIndex(Person.class);
elasticsearchTemplate.createIndex(Person.class);
elasticsearchTemplate.putMapping(Person.class);
elasticsearchTemplate.refresh(Person.class);
elasticsearchTemplate.deleteIndex(PersonMultipleLevelNested.class);
elasticsearchTemplate.createIndex(PersonMultipleLevelNested.class);
elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class);
elasticsearchTemplate.refresh(PersonMultipleLevelNested.class);
IndexInitializer.init(elasticsearchTemplate, Book.class);
IndexInitializer.init(elasticsearchTemplate, Person.class);
IndexInitializer.init(elasticsearchTemplate, PersonMultipleLevelNested.class);
}
@Test
@ -126,81 +120,79 @@ public class NestedObjectTests {
indexQueries.add(indexQuery1);
indexQueries.add(indexQuery2);
elasticsearchTemplate.putMapping(Person.class);
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(Person.class);
final QueryBuilder builder = nestedQuery("car", boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None);
final QueryBuilder builder = nestedQuery("car",
boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza")), ScoreMode.None);
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
final List<Person> persons = elasticsearchTemplate.queryForList(searchQuery, Person.class);
assertThat(persons.size(), is(1));
assertThat(persons).hasSize(1);
}
@Test
public void shouldIndexMultipleLevelNestedObject() {
//given
// given
final List<IndexQuery> indexQueries = createPerson();
//when
elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class);
// when
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(PersonMultipleLevelNested.class);
//then
// then
final GetQuery getQuery = new GetQuery();
getQuery.setId("1");
final PersonMultipleLevelNested personIndexed = elasticsearchTemplate.queryForObject(getQuery, PersonMultipleLevelNested.class);
assertThat(personIndexed, is(notNullValue()));
final PersonMultipleLevelNested personIndexed = elasticsearchTemplate.queryForObject(getQuery,
PersonMultipleLevelNested.class);
assertThat(personIndexed).isNotNull();
}
@Test
public void shouldIndexMultipleLevelNestedObjectWithIncludeInParent() {
//given
// given
final List<IndexQuery> indexQueries = createPerson();
//when
elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class);
// when
elasticsearchTemplate.bulkIndex(indexQueries);
// then
final Map<String, Object> mapping = elasticsearchTemplate.getMapping(PersonMultipleLevelNested.class);
final Map mapping = elasticsearchTemplate.getMapping(PersonMultipleLevelNested.class);
assertThat(mapping, is(notNullValue()));
final Map propertyMap = (Map) mapping.get("properties");
assertThat(propertyMap, is(notNullValue()));
assertThat(mapping).isNotNull();
final Map<String, Object> propertyMap = (Map<String, Object>) mapping.get("properties");
assertThat(propertyMap).isNotNull();
final Map bestCarsAttributes = (Map) propertyMap.get("bestCars");
assertThat(bestCarsAttributes.get("include_in_parent"), is(notNullValue()));
assertThat(bestCarsAttributes.get("include_in_parent")).isNotNull();
}
@Test
public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject() {
//given
// given
final List<IndexQuery> indexQueries = createPerson();
//when
elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class);
// when
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(PersonMultipleLevelNested.class);
//then
// then
final BoolQueryBuilder builder = boolQuery();
builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"),ScoreMode.None))
.must(nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()),ScoreMode.None));
builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"), ScoreMode.None)).must(
nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()), ScoreMode.None));
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(builder)
.build();
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
final Page<PersonMultipleLevelNested> personIndexed = elasticsearchTemplate.queryForPage(searchQuery, PersonMultipleLevelNested.class);
assertThat(personIndexed, is(notNullValue()));
assertThat(personIndexed.getTotalElements(), is(1L));
assertThat(personIndexed.getContent().get(0).getId(), is("1"));
final Page<PersonMultipleLevelNested> personIndexed = elasticsearchTemplate.queryForPage(searchQuery,
PersonMultipleLevelNested.class);
assertThat(personIndexed).isNotNull();
assertThat(personIndexed.getTotalElements()).isEqualTo(1);
assertThat(personIndexed.getContent().get(0).getId()).isEqualTo("1");
}
private List<IndexQuery> createPerson() {
final PersonMultipleLevelNested person1 = new PersonMultipleLevelNested();
@ -245,7 +237,7 @@ public class NestedObjectTests {
person2.setId("2");
person2.setName("name");
person2.setGirlFriends(Arrays.asList(permanent));
person2.setGirlFriends(Collections.singletonList(permanent));
final IndexQuery indexQuery2 = new IndexQuery();
indexQuery2.setId(person2.getId());
@ -261,6 +253,7 @@ public class NestedObjectTests {
@Test
public void shouldSearchBooksForPersonInitialLevelNestedType() {
// given
final List<Car> cars = new ArrayList<>();
final Car saturn = new Car();
@ -322,24 +315,24 @@ public class NestedObjectTests {
indexQueries.add(indexQuery1);
indexQueries.add(indexQuery2);
elasticsearchTemplate.putMapping(Person.class);
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(Person.class);
final QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")), ScoreMode.None);
// when
final QueryBuilder builder = nestedQuery("books", boolQuery().must(termQuery("books.name", "java")),
ScoreMode.None);
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
final List<Person> persons = elasticsearchTemplate.queryForList(searchQuery, Person.class);
assertThat(persons.size(), is(1));
// then
assertThat(persons).hasSize(1);
}
/*
DATAES-73
*/
@Test
@Test // DATAES-73
public void shouldIndexAndSearchMapAsNestedType() {
//given
// given
final Book book1 = new Book();
final Book book2 = new Book();
@ -369,17 +362,221 @@ public class NestedObjectTests {
indexQueries.add(indexQuery1);
indexQueries.add(indexQuery2);
//when
// when
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(Book.class);
//then
// then
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"),ScoreMode.None))
.build();
.withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"), ScoreMode.None)).build();
final Page<Book> books = elasticsearchTemplate.queryForPage(searchQuery, Book.class);
assertThat(books.getContent().size(), is(1));
assertThat(books.getContent().get(0).getId(), is(book2.getId()));
assertThat(books.getContent()).hasSize(1);
assertThat(books.getContent().get(0).getId()).isEqualTo(book2.getId());
}
}
@Setter
@Getter
@Document(indexName = "test-index-book-nested-objects", type = "book", shards = 1, replicas = 0, refreshInterval = "-1")
static class Book {
@Id private String id;
private String name;
@Field(type = FieldType.Object) private Author author;
@Field(type = FieldType.Nested) private Map<Integer, Collection<String>> buckets = new HashMap<>();
@MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"),
otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop",
searchAnalyzer = "standard") }) private String description;
}
@Document(indexName = "test-index-person", type = "user", shards = 1, replicas = 0, refreshInterval = "-1")
static class Person {
@Id private String id;
private String name;
@Field(type = FieldType.Nested) private List<Car> car;
@Field(type = FieldType.Nested, includeInParent = true) private List<Book> books;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Car> getCar() {
return car;
}
public void setCar(List<Car> car) {
this.car = car;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
static class Car {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Document(indexName = "test-index-person-multiple-level-nested", type = "user", shards = 1, replicas = 0,
refreshInterval = "-1")
static class PersonMultipleLevelNested {
@Id private String id;
private String name;
@Field(type = FieldType.Nested) private List<GirlFriend> girlFriends;
@Field(type = FieldType.Nested) private List<Car> cars;
@Field(type = FieldType.Nested, includeInParent = true) private List<Car> bestCars;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<GirlFriend> getGirlFriends() {
return girlFriends;
}
public void setGirlFriends(List<GirlFriend> girlFriends) {
this.girlFriends = girlFriends;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public List<Car> getBestCars() {
return bestCars;
}
public void setBestCars(List<Car> bestCars) {
this.bestCars = bestCars;
}
}
/**
* @author Mohsin Husen
*/
static class GirlFriend {
private String name;
private String type;
@Field(type = FieldType.Nested) private List<Car> cars;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
static class Author {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@ -1,55 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.builder;
import java.util.Date;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.entities.SampleInheritedEntity;
/**
* @author Kevin Leturc
*/
public class SampleInheritedEntityBuilder {
private SampleInheritedEntity result;
public SampleInheritedEntityBuilder(String id) {
result = new SampleInheritedEntity();
result.setId(id);
}
public SampleInheritedEntityBuilder createdDate(Date createdDate) {
result.setCreatedDate(createdDate);
return this;
}
public SampleInheritedEntityBuilder message(String message) {
result.setMessage(message);
return this;
}
public SampleInheritedEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}

View File

@ -17,9 +17,6 @@ package org.springframework.data.elasticsearch.client;
import static org.assertj.core.api.Assertions.*;
import java.util.List;
import org.elasticsearch.common.transport.TransportAddress;
import org.junit.Test;
/**
@ -85,6 +82,6 @@ public class ClusterNodesUnitTests {
public void rejectsUnresolvableHost() {
assertThatExceptionOfType(IllegalArgumentException.class) //
.isThrownBy(() -> ClusterNodes.of("mylocalhost:80"));
.isThrownBy(() -> ClusterNodes.of("mylocalhost.invalid.:80"));
}
}

View File

@ -18,7 +18,6 @@ package org.springframework.data.elasticsearch.client.reactive;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.springframework.data.elasticsearch.client.reactive.HostProvider.Verification;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
@ -26,6 +25,7 @@ import org.junit.Before;
import org.junit.Test;
import org.springframework.data.elasticsearch.client.ElasticsearchHost;
import org.springframework.data.elasticsearch.client.ElasticsearchHost.State;
import org.springframework.data.elasticsearch.client.reactive.HostProvider.Verification;
import org.springframework.data.elasticsearch.client.reactive.ReactiveMockClientTestsUtils.MockDelegatingElasticsearchHostProvider;
import org.springframework.data.elasticsearch.client.reactive.ReactiveMockClientTestsUtils.MockWebClientProvider.Receive;
import org.springframework.web.reactive.function.client.ClientResponse;
@ -106,8 +106,7 @@ public class MultiNodeHostProviderUnitTests {
provider.clusterInfo().as(StepVerifier::create).expectNextCount(1).verifyComplete();
provider.getActive(Verification.ACTIVE).as(StepVerifier::create).expectNext(mock.client(HOST_2))
.verifyComplete();
provider.getActive(Verification.ACTIVE).as(StepVerifier::create).expectNext(mock.client(HOST_2)).verifyComplete();
verify(mock.client(HOST_2), times(2)).head();
}

View File

@ -53,7 +53,6 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.elasticsearch.ElasticsearchVersion;
import org.springframework.data.elasticsearch.ElasticsearchVersionRule;
import org.springframework.data.elasticsearch.TestUtils;

View File

@ -16,7 +16,7 @@
package org.springframework.data.elasticsearch.client.reactive;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.data.elasticsearch.client.reactive.ReactiveMockClientTestsUtils.MockWebClientProvider.Receive.*;

View File

@ -24,7 +24,6 @@ import java.util.Collections;
import org.apache.commons.lang.ClassUtils;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

View File

@ -1,101 +0,0 @@
/*
* Copyright 2013-15 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.config;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.elasticsearch.node.NodeValidationException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.Utils;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.data.elasticsearch.repositories.sample.SampleElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.repository.Repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Kevin Leturc
* @author Gad Akuka
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class EnableElasticsearchRepositoriesTests implements ApplicationContextAware {
ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Configuration
@EnableElasticsearchRepositories(basePackages = {"org.springframework.data.elasticsearch.repositories.sample",
"org.springframework.data.elasticsearch.config"})
static class Config {
@Bean
public ElasticsearchOperations elasticsearchTemplate() throws NodeValidationException {
return new ElasticsearchTemplate(Utils.getNodeClient());
}
}
@Autowired
private SampleElasticsearchRepository repository;
@Autowired(required = false)
private SampleRepository nestedRepository;
interface SampleRepository extends Repository<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);
}
}

View File

@ -13,19 +13,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.config;
package org.springframework.data.elasticsearch.config.abstractelasticsearchconfiguration;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.repositories.existing.index.CreateIndexFalseRepository;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -47,8 +48,8 @@ public class ElasticsearchConfigurationTests {
@Configuration
@EnableElasticsearchRepositories(
basePackages = { "org.springframework.data.elasticsearch.repositories.existing.index",
"org.springframework.data.elasticsearch.config" })
basePackages = { "org.springframework.data.elasticsearch.config.abstractelasticsearchconfiguration" },
considerNestedRepositories = true)
static class Config extends AbstractElasticsearchConfiguration {
@Override
@ -60,6 +61,15 @@ public class ElasticsearchConfigurationTests {
@Test // DATAES-563
public void bootstrapsRepository() {
assertThat(repository, is(notNullValue()));
assertThat(repository).isNotNull();
}
@Document(indexName = "test-index-config-abstractelasticsearchconfiguraiton", type = "test-type", createIndex = false)
static class CreateIndexFalseEntity {
@Id private String id;
}
interface CreateIndexFalseRepository extends ElasticsearchRepository<CreateIndexFalseEntity, String> {}
}

View File

@ -13,19 +13,19 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.config;
package org.springframework.data.elasticsearch.config.namespace;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.client.RestClientFactoryBean;
import org.springframework.data.elasticsearch.client.TransportClientFactoryBean;
import org.springframework.data.elasticsearch.repositories.sample.SampleElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -33,31 +33,41 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Don Wellington
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("namespace.xml")
public class ElasticsearchNamespaceHandlerTests {
@Autowired
private ApplicationContext context;
@Autowired private ApplicationContext context;
@Test
public void shouldCreateTransportClient() {
assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue()));
assertThat(context.getBean(TransportClientFactoryBean.class), is(instanceOf(TransportClientFactoryBean.class)));
assertThat(context.getBean(TransportClientFactoryBean.class)).isNotNull();
assertThat(context.getBean(TransportClientFactoryBean.class)).isInstanceOf(TransportClientFactoryBean.class);
}
@Test
public void shouldCreateRepository() {
assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue()));
assertThat(context.getBean(SampleElasticsearchRepository.class),
is(instanceOf(SampleElasticsearchRepository.class)));
assertThat(context.getBean(TransportClientFactoryBean.class)).isNotNull();
assertThat(context.getBean(CreateIndexFalseRepository.class)).isInstanceOf(CreateIndexFalseRepository.class);
}
@Test
public void shouldCreateRestClient() {
assertThat(context.getBean(RestClientFactoryBean.class), is(notNullValue()));
assertThat(context.getBean(RestClientFactoryBean.class), is(instanceOf(RestClientFactoryBean.class)));
assertThat(context.getBean(RestClientFactoryBean.class)).isNotNull();
assertThat(context.getBean(RestClientFactoryBean.class)).isInstanceOf(RestClientFactoryBean.class);
}
@Document(indexName = "test-index-config-namespace", type = "test-type", createIndex = false)
static class CreateIndexFalseEntity {
@Id private String id;
}
interface CreateIndexFalseRepository extends ElasticsearchRepository<CreateIndexFalseEntity, String> {}
}

View File

@ -13,9 +13,20 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.config;
package org.springframework.data.elasticsearch.config.nested;
import static org.junit.Assert.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import org.elasticsearch.node.NodeValidationException;
import org.junit.Test;
@ -23,10 +34,16 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.Utils;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.repository.Repository;
import org.springframework.test.context.ContextConfiguration;
@ -34,29 +51,59 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Kevin Leturc
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class EnableNestedElasticsearchRepositoriesTests {
@Configuration
@EnableElasticsearchRepositories(basePackages = {"org.springframework.data.elasticsearch.repositories.sample",
"org.springframework.data.elasticsearch.config"}, considerNestedRepositories = true)
@EnableElasticsearchRepositories(basePackages = { "org.springframework.data.elasticsearch.config.nested" },
considerNestedRepositories = true)
static class Config {
@Bean
public ElasticsearchOperations elasticsearchTemplate() throws NodeValidationException {
return new ElasticsearchTemplate(Utils.getNodeClient());
}
}
@Autowired(required = false)
private SampleRepository nestedRepository;
interface SampleRepository extends Repository<SampleEntity, Long> {};
@Autowired(required = false) private SampleRepository nestedRepository;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Test
public void hasNestedRepository() {
assertNotNull(nestedRepository);
}
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-config-nested", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
interface SampleRepository extends Repository<SampleEntity, Long> {}
}

View File

@ -0,0 +1,186 @@
/*
* Copyright 2013-15 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.config.notnested;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import java.util.UUID;
import org.elasticsearch.node.NodeValidationException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.Utils;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.data.repository.Repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Kevin Leturc
* @author Gad Akuka
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class EnableElasticsearchRepositoriesTests implements ApplicationContextAware {
ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
@Configuration
@EnableElasticsearchRepositories(basePackages = { "org.springframework.data.elasticsearch.config.notnested" })
static class Config {
@Bean
public ElasticsearchOperations elasticsearchTemplate() throws NodeValidationException {
return new ElasticsearchTemplate(Utils.getNodeClient());
}
}
@Autowired ElasticsearchTemplate elasticsearchTemplate;
@Autowired private SampleElasticsearchRepository repository;
@Autowired(required = false) private SampleRepository nestedRepository;
interface SampleRepository extends Repository<EnableElasticsearchRepositoriesTests.SampleEntity, Long> {}
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
}
@Test
public void bootstrapsRepository() {
assertThat(repository).isNotNull();
}
@Test
public void shouldScanSelectedPackage() {
// given
// when
String[] beanNamesForType = context.getBeanNamesForType(ElasticsearchRepository.class);
// then
assertThat(beanNamesForType).containsExactlyInAnyOrder("sampleElasticsearchRepository",
"sampleUUIDKeyedElasticsearchRepository");
}
@Test
public void hasNotNestedRepository() {
assertThat(nestedRepository).isNull();
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-config-not-nested", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
/**
* @author Gad Akuka
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-uuid-keyed-config-not-nested", type = "test-type-uuid-keyed", shards = 1,
replicas = 0, refreshInterval = "-1")
static class SampleEntityUUIDKeyed {
@Id private UUID id;
private String type;
@Field(type = FieldType.Text, fielddata = true) private String message;
private int rate;
@ScriptedField private Long scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
}
}

View File

@ -13,11 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.repositories.sample;
package org.springframework.data.elasticsearch.config.notnested;
import java.util.List;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
@ -25,13 +24,14 @@ import org.springframework.data.elasticsearch.repository.ElasticsearchRepository
* @author Mohsin Husen
* @author Christoph Strobl
*/
public interface SampleElasticsearchRepository extends ElasticsearchRepository<SampleEntity, String> {
public interface SampleElasticsearchRepository
extends ElasticsearchRepository<EnableElasticsearchRepositoriesTests.SampleEntity, String> {
long deleteSampleEntityById(String id);
List<SampleEntity> deleteByAvailable(boolean available);
List<EnableElasticsearchRepositoriesTests.SampleEntity> deleteByAvailable(boolean available);
List<SampleEntity> deleteByMessage(String message);
List<EnableElasticsearchRepositoriesTests.SampleEntity> deleteByMessage(String message);
void deleteByType(String type);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2013-2019 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -13,25 +13,25 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.repositories.sample;
package org.springframework.data.elasticsearch.config.notnested;
import java.util.List;
import java.util.UUID;
import org.springframework.data.elasticsearch.entities.SampleEntityUUIDKeyed;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* @author Gad Akuka
* @author Christoph Strobl
*/
public interface SampleUUIDKeyedElasticsearchRepository extends ElasticsearchRepository<SampleEntityUUIDKeyed, UUID> {
interface SampleUUIDKeyedElasticsearchRepository
extends ElasticsearchRepository<EnableElasticsearchRepositoriesTests.SampleEntityUUIDKeyed, UUID> {
long deleteSampleEntityUUIDKeyedById(UUID id);
List<SampleEntityUUIDKeyed> deleteByAvailable(boolean available);
List<EnableElasticsearchRepositoriesTests.SampleEntityUUIDKeyed> deleteByAvailable(boolean available);
List<SampleEntityUUIDKeyed> deleteByMessage(String message);
List<EnableElasticsearchRepositoriesTests.SampleEntityUUIDKeyed> deleteByMessage(String message);
void deleteByType(String type);

View File

@ -16,10 +16,19 @@
package org.springframework.data.elasticsearch.core;
import static org.apache.commons.lang.RandomStringUtils.*;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -29,19 +38,27 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.AliasBuilder;
import org.springframework.data.elasticsearch.core.query.AliasQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Mohsin Husen
* @author Ilkang Na
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
@ -51,16 +68,18 @@ public class AliasTests {
private static final String INDEX_NAME_2 = "test-alias-index-2";
private static final String TYPE_NAME = "test-alias-type";
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
Map<String, Object> settings = new HashMap<>();
private static Map<String, Object> settings = new HashMap<>();
static {
settings.put("index.refresh_interval", "-1");
settings.put("index.number_of_replicas", "0");
settings.put("index.number_of_shards", "2");
settings.put("index.store.type", "fs");
}
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
elasticsearchTemplate.deleteIndex(INDEX_NAME_1);
elasticsearchTemplate.createIndex(INDEX_NAME_1, settings);
@ -69,143 +88,146 @@ public class AliasTests {
elasticsearchTemplate.deleteIndex(INDEX_NAME_2);
elasticsearchTemplate.createIndex(INDEX_NAME_2, settings);
elasticsearchTemplate.refresh(INDEX_NAME_2);
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
}
@Test
public void shouldAddAlias() {
// given
String aliasName = "test-alias";
AliasQuery aliasQuery = new AliasBuilder()
.withIndexName(INDEX_NAME_1)
.withAliasName(aliasName).build();
AliasQuery aliasQuery = new AliasBuilder().withIndexName(INDEX_NAME_1).withAliasName(aliasName).build();
// when
elasticsearchTemplate.addAlias(aliasQuery);
// then
List<AliasMetaData> aliases = elasticsearchTemplate.queryForAlias(INDEX_NAME_1);
assertThat(aliases, is(notNullValue()));
assertThat(aliases.get(0).alias(), is(aliasName));
assertThat(aliases).isNotNull();
assertThat(aliases.get(0).alias()).isEqualTo(aliasName);
}
@Test
public void shouldRemoveAlias() {
// given
String indexName = INDEX_NAME_1;
String aliasName = "test-alias";
AliasQuery aliasQuery = new AliasBuilder()
.withIndexName(indexName)
.withAliasName(aliasName).build();
AliasQuery aliasQuery = new AliasBuilder().withIndexName(indexName).withAliasName(aliasName).build();
// when
elasticsearchTemplate.addAlias(aliasQuery);
List<AliasMetaData> aliases = elasticsearchTemplate.queryForAlias(indexName);
assertThat(aliases, is(notNullValue()));
assertThat(aliases.get(0).alias(), is(aliasName));
assertThat(aliases).isNotNull();
assertThat(aliases.get(0).alias()).isEqualTo(aliasName);
// then
elasticsearchTemplate.removeAlias(aliasQuery);
aliases = elasticsearchTemplate.queryForAlias(indexName);
assertThat(aliases, anyOf(is(nullValue()), hasSize(0)));
assertThat(aliases).isEmpty();
}
/*
DATAES-70
*/
@Test
@Test // DATAES-70
public void shouldAddAliasWithGivenRoutingValue() {
//given
String indexName = INDEX_NAME_1;
// given
String alias = "test-alias";
AliasQuery aliasQuery = new AliasBuilder()
.withIndexName(indexName)
.withAliasName(alias)
.withRouting("0").build();
AliasQuery aliasQuery = new AliasBuilder().withIndexName(INDEX_NAME_1).withAliasName(alias).withRouting("0")
.build();
//when
// when
elasticsearchTemplate.addAlias(aliasQuery);
String documentId = randomNumeric(5);
SampleEntity sampleEntity = SampleEntity.builder().id(documentId)
.message("some message")
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message")
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = new IndexQueryBuilder()
.withIndexName(alias)
.withId(sampleEntity.getId())
.withType(TYPE_NAME)
.withObject(sampleEntity)
.build();
IndexQuery indexQuery = new IndexQueryBuilder().withIndexName(alias).withId(sampleEntity.getId())
.withType(TYPE_NAME).withObject(sampleEntity).build();
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(INDEX_NAME_1);
SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withIndices(alias).withTypes(TYPE_NAME).build();
SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices(alias)
.withTypes(TYPE_NAME).build();
long count = elasticsearchTemplate.count(query);
//then
List<AliasMetaData> aliases = elasticsearchTemplate.queryForAlias(INDEX_NAME_1);
assertThat(aliases, is(notNullValue()));
assertThat(aliases.get(0).alias(), is(alias));
assertThat(aliases.get(0).searchRouting(), is("0"));
assertThat(aliases.get(0).indexRouting(), is("0"));
assertThat(count, is(1L));
//cleanup
// then
List<AliasMetaData> aliases = elasticsearchTemplate.queryForAlias(INDEX_NAME_1);
assertThat(aliases).isNotNull();
final AliasMetaData aliasMetaData = aliases.get(0);
assertThat(aliasMetaData.alias()).isEqualTo(alias);
assertThat(aliasMetaData.searchRouting()).isEqualTo("0");
assertThat(aliasMetaData.indexRouting()).isEqualTo("0");
assertThat(count).isEqualTo(1);
// cleanup
elasticsearchTemplate.removeAlias(aliasQuery);
elasticsearchTemplate.deleteIndex(SampleEntity.class);
elasticsearchTemplate.createIndex(SampleEntity.class);
elasticsearchTemplate.putMapping(SampleEntity.class);
elasticsearchTemplate.refresh(SampleEntity.class);
}
/*
DATAES-70
*/
@Test
@Test // DATAES-70
public void shouldAddAliasForVariousRoutingValues() {
//given
// given
String alias1 = "test-alias-1";
String alias2 = "test-alias-2";
AliasQuery aliasQuery1 = new AliasBuilder()
.withIndexName(INDEX_NAME_1)
.withAliasName(alias1)
.withIndexRouting("0").build();
AliasQuery aliasQuery1 = new AliasBuilder().withIndexName(INDEX_NAME_1).withAliasName(alias1).withIndexRouting("0")
.build();
AliasQuery aliasQuery2 = new AliasBuilder()
.withIndexName(INDEX_NAME_2)
.withAliasName(alias2)
.withSearchRouting("1").build();
AliasQuery aliasQuery2 = new AliasBuilder().withIndexName(INDEX_NAME_2).withAliasName(alias2).withSearchRouting("1")
.build();
//when
// when
elasticsearchTemplate.addAlias(aliasQuery1);
elasticsearchTemplate.addAlias(aliasQuery2);
String documentId = randomNumeric(5);
SampleEntity sampleEntity = SampleEntity.builder().id(documentId)
.message("some message")
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message("some message")
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = new IndexQueryBuilder()
.withIndexName(alias1)
.withType(TYPE_NAME)
.withId(sampleEntity.getId())
.withObject(sampleEntity).build();
IndexQuery indexQuery = new IndexQueryBuilder().withIndexName(alias1).withType(TYPE_NAME)
.withId(sampleEntity.getId()).withObject(sampleEntity).build();
elasticsearchTemplate.index(indexQuery);
// then
List<AliasMetaData> responseAlias1 = elasticsearchTemplate.queryForAlias(INDEX_NAME_1);
assertThat(responseAlias1, is(notNullValue()));
assertThat(responseAlias1.get(0).alias(), is(alias1));
assertThat(responseAlias1.get(0).indexRouting(), is("0"));
assertThat(responseAlias1).isNotNull();
final AliasMetaData aliasMetaData1 = responseAlias1.get(0);
assertThat(aliasMetaData1.alias()).isEqualTo(alias1);
assertThat(aliasMetaData1.indexRouting()).isEqualTo("0");
List<AliasMetaData> responseAlias2 = elasticsearchTemplate.queryForAlias(INDEX_NAME_2);
assertThat(responseAlias2, is(notNullValue()));
assertThat(responseAlias2.get(0).alias(), is(alias2));
assertThat(responseAlias2.get(0).searchRouting(), is("1"));
assertThat(responseAlias2).isNotNull();
final AliasMetaData aliasMetaData2 = responseAlias2.get(0);
assertThat(aliasMetaData2.alias()).isEqualTo(alias2);
assertThat(aliasMetaData2.searchRouting()).isEqualTo("1");
//cleanup
// cleanup
elasticsearchTemplate.removeAlias(aliasQuery1);
elasticsearchTemplate.removeAlias(aliasQuery2);
}
@Builder
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "test-index-sample-core-alias", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
}

View File

@ -17,23 +17,34 @@ package org.springframework.data.elasticsearch.core;
import static org.assertj.core.api.Assertions.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.IOException;
import java.util.Locale;
import org.junit.Before;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.ReadOnlyProperty;
import org.springframework.data.annotation.Transient;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.entities.Car;
import org.springframework.data.elasticsearch.entities.GeoEntity;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Polygon;
/**
* @author Artur Konczak
* @author Mohsin Husen
* @author Oliver Gierke
* @author Peter-Josef Meisch
*/
public class DefaultEntityMapperTests {
@ -49,44 +60,46 @@ public class DefaultEntityMapperTests {
@Test
public void shouldMapObjectToJsonString() throws IOException {
//Given
//When
// given
// when
String jsonResult = entityMapper.mapToString(Car.builder().model(CAR_MODEL).name(CAR_NAME).build());
//Then
// then
assertThat(jsonResult).isEqualTo(JSON_STRING);
}
@Test
public void shouldMapJsonStringToObject() throws IOException {
//Given
//When
// given
// when
Car result = entityMapper.mapToObject(JSON_STRING, Car.class);
//Then
// then
assertThat(result.getName()).isEqualTo(CAR_NAME);
assertThat(result.getModel()).isEqualTo(CAR_MODEL);
}
@Test
public void shouldMapGeoPointElasticsearchNames() throws IOException {
//given
// given
final Point point = new Point(10, 20);
final String pointAsString = point.getX() + "," + point.getY();
final double[] pointAsArray = {point.getX(), point.getY()};
final GeoEntity geoEntity = GeoEntity.builder()
.pointA(point).pointB(GeoPoint.fromPoint(point)).pointC(pointAsString).pointD(pointAsArray)
.build();
//when
final double[] pointAsArray = { point.getX(), point.getY() };
final GeoEntity geoEntity = GeoEntity.builder().pointA(point).pointB(GeoPoint.fromPoint(point))
.pointC(pointAsString).pointD(pointAsArray).build();
// when
String jsonResult = entityMapper.mapToString(geoEntity);
//then
// then
assertThat(jsonResult).contains(pointTemplate("pointA", point));
assertThat(jsonResult).contains(pointTemplate("pointB", point));
assertThat(jsonResult).contains(String.format(Locale.ENGLISH, "\"%s\":\"%s\"", "pointC", pointAsString));
assertThat(jsonResult).contains(String.format(Locale.ENGLISH, "\"%s\":[%.1f,%.1f]", "pointD", pointAsArray[0], pointAsArray[1]));
assertThat(jsonResult)
.contains(String.format(Locale.ENGLISH, "\"%s\":[%.1f,%.1f]", "pointD", pointAsArray[0], pointAsArray[1]));
}
@Test // DATAES-464
@ -116,10 +129,71 @@ public class DefaultEntityMapperTests {
public static class Sample {
public @ReadOnlyProperty String readOnly;
public @Transient String annotatedTransientProperty;
public transient String transientProperty;
public String property;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
static class Car {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
/**
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-geo-core-default-entity-mapper", type = "geo-test-index", shards = 1, replicas = 0,
refreshInterval = "-1")
static class GeoEntity {
@Id private String id;
// geo shape - Spring Data
private Box box;
private Circle circle;
private Polygon polygon;
// geo point - Custom implementation + Spring Data
@GeoPointField private Point pointA;
private GeoPoint pointB;
@GeoPointField private String pointC;
@GeoPointField private double[] pointD;
}
}

View File

@ -16,13 +16,20 @@
package org.springframework.data.elasticsearch.core;
import static java.util.Arrays.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
@ -48,13 +55,17 @@ import org.junit.runners.Parameterized.Parameters;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.entities.Car;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import com.fasterxml.jackson.databind.util.ArrayIterator;
@ -65,6 +76,7 @@ import com.fasterxml.jackson.databind.util.ArrayIterator;
* @author Mark Paluch
* @author Ilkang Na
* @author Christoph Strobl
* @author Peter-Josef Meisch
*/
@RunWith(Parameterized.class)
public class DefaultResultMapperTests {
@ -99,7 +111,8 @@ public class DefaultResultMapperTests {
@Test
public void shouldMapAggregationsToPage() {
// Given
// given
SearchHit[] hits = { createCarHit("Ford", "Grat"), createCarHit("BMW", "Arrow") };
SearchHits searchHits = mock(SearchHits.class);
when(searchHits.getTotalHits()).thenReturn(2L);
@ -109,70 +122,70 @@ public class DefaultResultMapperTests {
Aggregations aggregations = new Aggregations(asList(createCarAggregation()));
when(response.getAggregations()).thenReturn(aggregations);
// When
AggregatedPage<Car> page = (AggregatedPage<Car>) resultMapper.mapResults(response, Car.class, Pageable.unpaged());
// when
AggregatedPage<Car> page = resultMapper.mapResults(response, Car.class, Pageable.unpaged());
// Then
// then
page.hasFacets();
assertThat(page.hasAggregations(), is(true));
assertThat(page.getAggregation("Diesel").getName(), is("Diesel"));
assertThat(page.hasAggregations()).isTrue();
assertThat(page.getAggregation("Diesel").getName()).isEqualTo("Diesel");
}
@Test
public void shouldMapSearchRequestToPage() {
// Given
// given
SearchHit[] hits = { createCarHit("Ford", "Grat"), createCarHit("BMW", "Arrow") };
SearchHits searchHits = mock(SearchHits.class);
when(searchHits.getTotalHits()).thenReturn(2L);
when(searchHits.iterator()).thenReturn(new ArrayIterator(hits));
when(response.getHits()).thenReturn(searchHits);
// When
// when
Page<Car> page = resultMapper.mapResults(response, Car.class, Pageable.unpaged());
// Then
assertThat(page.hasContent(), is(true));
assertThat(page.getTotalElements(), is(2L));
assertThat(page.getContent().get(0).getName(), is("Ford"));
// then
assertThat(page.hasContent()).isTrue();
assertThat(page.getTotalElements()).isEqualTo(2);
assertThat(page.getContent().get(0).getName()).isEqualTo("Ford");
}
@Test
public void shouldMapPartialSearchRequestToObject() {
// Given
// given
SearchHit[] hits = { createCarPartialHit("Ford", "Grat"), createCarPartialHit("BMW", "Arrow") };
SearchHits searchHits = mock(SearchHits.class);
when(searchHits.getTotalHits()).thenReturn(2L);
when(searchHits.iterator()).thenReturn(new ArrayIterator(hits));
when(response.getHits()).thenReturn(searchHits);
// When
// when
Page<Car> page = resultMapper.mapResults(response, Car.class, Pageable.unpaged());
// Then
assertThat(page.hasContent(), is(true));
assertThat(page.getTotalElements(), is(2L));
assertThat(page.getContent().get(0).getName(), is("Ford"));
// then
assertThat(page.hasContent()).isTrue();
assertThat(page.getTotalElements()).isEqualTo(2);
assertThat(page.getContent().get(0).getName()).isEqualTo("Ford");
}
@Test
public void shouldMapGetRequestToObject() {
// Given
// given
GetResponse response = mock(GetResponse.class);
when(response.getSourceAsString()).thenReturn(createJsonCar("Ford", "Grat"));
// When
// when
Car result = resultMapper.mapResult(response, Car.class);
// Then
assertThat(result, notNullValue());
assertThat(result.getModel(), is("Grat"));
assertThat(result.getName(), is("Ford"));
// then
assertThat(result).isNotNull();
assertThat(result.getModel()).isEqualTo("Grat");
assertThat(result.getName()).isEqualTo("Ford");
}
/**
* @see DATAES-281.
*/
@Test
@Test // DATAES-281
@Ignore("fix me - UnsupportedOperation")
public void setsIdentifierOnImmutableType() {
@ -182,24 +195,26 @@ public class DefaultResultMapperTests {
ImmutableEntity result = resultMapper.mapResult(response, ImmutableEntity.class);
assertThat(result, is(notNullValue()));
assertThat(result.getId(), is("identifier"));
assertThat(result).isNotNull();
assertThat(result.getId()).isEqualTo("identifier");
}
@Test // DATAES-198
public void setsVersionFromGetResponse() {
GetResponse response = mock(GetResponse.class);
when(response.getSourceAsString()).thenReturn("{}");
when(response.getVersion()).thenReturn(1234L);
SampleEntity result = resultMapper.mapResult(response, SampleEntity.class);
assertThat(result, is(notNullValue()));
assertThat(result.getVersion(), is(1234L));
assertThat(result).isNotNull();
assertThat(result.getVersion()).isEqualTo(1234);
}
@Test // DATAES-198
public void setsVersionFromMultiGetResponse() {
GetResponse response1 = mock(GetResponse.class);
when(response1.getSourceAsString()).thenReturn("{}");
when(response1.isExists()).thenReturn(true);
@ -216,15 +231,15 @@ public class DefaultResultMapperTests {
LinkedList<SampleEntity> results = resultMapper.mapResults(multiResponse, SampleEntity.class);
assertThat(results, is(notNullValue()));
assertThat(results, hasSize(2));
assertThat(results).isNotNull().hasSize(2);
assertThat(results.get(0).getVersion(), is(1234L));
assertThat(results.get(1).getVersion(), is(5678L));
assertThat(results.get(0).getVersion()).isEqualTo(1234);
assertThat(results.get(1).getVersion()).isEqualTo(5678);
}
@Test // DATAES-198
public void setsVersionFromSearchResponse() {
SearchHit hit1 = mock(SearchHit.class);
when(hit1.getSourceAsString()).thenReturn("{}");
when(hit1.getVersion()).thenReturn(1234L);
@ -243,25 +258,28 @@ public class DefaultResultMapperTests {
AggregatedPage<SampleEntity> results = resultMapper.mapResults(searchResponse, SampleEntity.class,
mock(Pageable.class));
assertThat(results, is(notNullValue()));
assertThat(results).isNotNull();
assertThat(results.getContent().get(0).getVersion(), is(1234L));
assertThat(results.getContent().get(1).getVersion(), is(5678L));
assertThat(results.getContent().get(0).getVersion()).isEqualTo(1234);
assertThat(results.getContent().get(1).getVersion()).isEqualTo(5678);
}
private Aggregation createCarAggregation() {
Aggregation aggregation = mock(Terms.class);
when(aggregation.getName()).thenReturn("Diesel");
return aggregation;
}
private SearchHit createCarHit(String name, String model) {
SearchHit hit = mock(SearchHit.class);
when(hit.getSourceAsString()).thenReturn(createJsonCar(name, model));
return hit;
}
private SearchHit createCarPartialHit(String name, String model) {
SearchHit hit = mock(SearchHit.class);
when(hit.getSourceAsString()).thenReturn(null);
when(hit.getFields()).thenReturn(createCarFields(name, model));
@ -269,6 +287,7 @@ public class DefaultResultMapperTests {
}
private String createJsonCar(String name, String model) {
final String q = "\"";
StringBuffer sb = new StringBuffer();
sb.append("{").append(q).append("name").append(q).append(":").append(q).append(name).append(q).append(",");
@ -277,6 +296,7 @@ public class DefaultResultMapperTests {
}
private Map<String, DocumentField> createCarFields(String name, String model) {
Map<String, DocumentField> result = new HashMap<>();
result.put("name", new DocumentField("name", asList(name)));
result.put("model", new DocumentField("model", asList(model)));
@ -290,4 +310,107 @@ public class DefaultResultMapperTests {
private final String id, name;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
static class Car {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-default-result-mapper", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
}

View File

@ -17,10 +17,14 @@ package org.springframework.data.elasticsearch.core;
import static org.assertj.core.api.Assertions.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import java.io.IOException;
import java.util.ArrayList;
@ -43,19 +47,22 @@ import org.springframework.data.annotation.Transient;
import org.springframework.data.annotation.TypeAlias;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchCustomConversions;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.entities.Car;
import org.springframework.data.elasticsearch.entities.GeoEntity;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Polygon;
/**
* @author Christoph Strobl
*/
public class ElasticsearchEntityMapperUnitTests {
static final String JSON_STRING = "{\"_class\":\"org.springframework.data.elasticsearch.entities.Car\",\"name\":\"Grat\",\"model\":\"Ford\"}";
static final String JSON_STRING = "{\"_class\":\"org.springframework.data.elasticsearch.core.ElasticsearchEntityMapperUnitTests$Car\",\"name\":\"Grat\",\"model\":\"Ford\"}";
static final String CAR_MODEL = "Ford";
static final String CAR_NAME = "Grat";
ElasticsearchEntityMapper entityMapper;
@ -674,4 +681,66 @@ public class ElasticsearchEntityMapperUnitTests {
return new ShotGun(source.get("model").toString());
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
static class Car {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
/**
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-geo-core-entity-mapper", type = "geo-test-index", shards = 1, replicas = 0,
refreshInterval = "-1")
static class GeoEntity {
@Id private String id;
// geo shape - Spring Data
private Box box;
private Circle circle;
private Polygon polygon;
// geo point - Custom implementation + Spring Data
@GeoPointField private Point pointA;
private GeoPoint pointB;
@GeoPointField private String pointC;
@GeoPointField private double[] pointD;
}
}

View File

@ -16,15 +16,33 @@
package org.springframework.data.elasticsearch.core;
import static org.apache.commons.lang.RandomStringUtils.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -40,6 +58,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Alen Turkovic
* @author Sascha Woo
* @author Don Wellington
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-rest-template-test.xml")
@ -47,6 +66,7 @@ public class ElasticsearchRestTemplateTests extends ElasticsearchTemplateTests {
@Test(expected = ElasticsearchStatusException.class)
public void shouldThrowExceptionIfDocumentDoesNotExistWhileDoingPartialUpdate() {
// when
IndexRequest indexRequest = new IndexRequest();
indexRequest.source("{}", XContentType.JSON);
@ -54,4 +74,74 @@ public class ElasticsearchRestTemplateTests extends ElasticsearchTemplateTests {
.withIndexRequest(indexRequest).build();
elasticsearchTemplate.update(updateQuery);
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-core-rest-template", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
}

View File

@ -15,8 +15,7 @@
*/
package org.springframework.data.elasticsearch.core;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -26,26 +25,27 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Artur Konczak
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-custom-mapper.xml")
public class ElasticsearchTemplateCustomMapperTests {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Autowired
private EntityMapper entityMapper;
@Autowired private EntityMapper entityMapper;
@Autowired
private ResultsMapper resultsMapper;
@Autowired private ResultsMapper resultsMapper;
@Test
public void shouldUseCustomMapper() {
//given
//when
//them
assertThat(elasticsearchTemplate.getResultsMapper(), is(resultsMapper));
assertThat(elasticsearchTemplate.getResultsMapper().getEntityMapper(), is(entityMapper));
// given
// when
// then
assertThat(elasticsearchTemplate.getResultsMapper()).isSameAs(resultsMapper);
assertThat(elasticsearchTemplate.getResultsMapper().getEntityMapper()).isSameAs(entityMapper);
}
}

View File

@ -15,10 +15,9 @@
*/
package org.springframework.data.elasticsearch.core;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.common.xcontent.XContentFactory.*;
import static org.elasticsearch.join.query.JoinQueryBuilders.hasChildQuery;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.elasticsearch.join.query.JoinQueryBuilders.*;
import java.util.List;
@ -29,48 +28,46 @@ import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.style.ToStringCreator;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.Parent;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplateParentChildTests.ParentEntity.ChildEntity;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.entities.ParentEntity;
import org.springframework.data.elasticsearch.entities.ParentEntity.ChildEntity;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Philipp Jardas
* @author Peter-Josef Meisch
*/
@Ignore(value = "DATAES-421")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class ElasticsearchTemplateParentChildTests {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
clean();
elasticsearchTemplate.createIndex(ParentEntity.class);
elasticsearchTemplate.createIndex(ChildEntity.class);
elasticsearchTemplate.putMapping(ChildEntity.class);
}
@After
public void clean() {
elasticsearchTemplate.deleteIndex(ChildEntity.class);
elasticsearchTemplate.deleteIndex(ParentEntity.class);
IndexInitializer.init(elasticsearchTemplate, ParentEntity.class);
IndexInitializer.init(elasticsearchTemplate, ChildEntity.class);
}
@Ignore(value = "DATAES-421")
@Test
public void shouldIndexParentChildEntity() {
// index two parents
ParentEntity parent1 = index("parent1", "First Parent");
ParentEntity parent2 = index("parent2", "Second Parent");
@ -84,16 +81,19 @@ public class ElasticsearchTemplateParentChildTests {
elasticsearchTemplate.refresh(ChildEntity.class);
// find all parents that have the first child
QueryBuilder query = hasChildQuery(ParentEntity.CHILD_TYPE, QueryBuilders.termQuery("name", child1name.toLowerCase()), ScoreMode.None);
QueryBuilder query = hasChildQuery(ParentEntity.CHILD_TYPE,
QueryBuilders.termQuery("name", child1name.toLowerCase()), ScoreMode.None);
List<ParentEntity> parents = elasticsearchTemplate.queryForList(new NativeSearchQuery(query), ParentEntity.class);
// we're expecting only the first parent as result
assertThat("parents", parents, contains(hasProperty("id", is(parent1.getId()))));
assertThat(parents).hasSize(1);
assertThat(parents.get(0).getId()).isEqualTo(parent1.getId());
}
@Ignore(value = "DATAES-421")
@Test
public void shouldUpdateChild() throws Exception {
// index parent and child
ParentEntity parent = index("parent", "Parent");
ChildEntity child = index("child", parent.getId(), "Child");
@ -107,12 +107,13 @@ public class ElasticsearchTemplateParentChildTests {
updateRequest.doc(builder);
final UpdateResponse response = update(updateRequest);
assertThat(response.getShardInfo().getSuccessful(), is(1));
assertThat(response.getShardInfo().getSuccessful()).isEqualTo(1);
}
@Ignore(value = "DATAES-421")
@Test(expected = RoutingMissingException.class)
public void shouldFailWithRoutingMissingExceptionOnUpdateChildIfNotRoutingSetOnUpdateRequest() throws Exception {
// index parent and child
ParentEntity parent = index("parent", "Parent");
ChildEntity child = index("child", parent.getId(), "Child");
@ -129,6 +130,7 @@ public class ElasticsearchTemplateParentChildTests {
@Ignore(value = "DATAES-421")
@Test(expected = RoutingMissingException.class)
public void shouldFailWithRoutingMissingExceptionOnUpdateChildIfRoutingOnlySetOnRequestDoc() throws Exception {
// index parent and child
ParentEntity parent = index("parent", "Parent");
ChildEntity child = index("child", parent.getId(), "Child");
@ -144,6 +146,7 @@ public class ElasticsearchTemplateParentChildTests {
}
private ParentEntity index(String parentId, String name) {
ParentEntity parent = new ParentEntity(parentId, name);
IndexQuery index = new IndexQuery();
index.setId(parent.getId());
@ -154,6 +157,7 @@ public class ElasticsearchTemplateParentChildTests {
}
private ChildEntity index(String childId, String parentId, String name) {
ChildEntity child = new ChildEntity(childId, parentId, name);
IndexQuery index = new IndexQuery();
index.setId(child.getId());
@ -165,6 +169,7 @@ public class ElasticsearchTemplateParentChildTests {
}
private UpdateResponse update(UpdateRequest updateRequest) {
final UpdateQuery update = new UpdateQuery();
update.setId(updateRequest.id());
update.setType(updateRequest.type());
@ -172,4 +177,76 @@ public class ElasticsearchTemplateParentChildTests {
update.setUpdateRequest(updateRequest);
return elasticsearchTemplate.update(update);
}
/**
* @author Philipp Jardas
* @author Mohsin Husen
*/
@Document(
indexName = org.springframework.data.elasticsearch.core.ElasticsearchTemplateParentChildTests.ParentEntity.INDEX,
type = org.springframework.data.elasticsearch.core.ElasticsearchTemplateParentChildTests.ParentEntity.PARENT_TYPE,
shards = 1, replicas = 0, refreshInterval = "-1")
static class ParentEntity {
public static final String INDEX = "parent-child";
public static final String PARENT_TYPE = "parent-entity";
public static final String CHILD_TYPE = "child-entity";
@Id private String id;
@Field(type = FieldType.Text, store = true) private String name;
public ParentEntity() {}
public ParentEntity(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return new ToStringCreator(this).append("id", id).append("name", name).toString();
}
@Document(indexName = INDEX, type = CHILD_TYPE, shards = 1, replicas = 0, refreshInterval = "-1")
static class ChildEntity {
@Id private String id;
@Field(type = FieldType.Text, store = true) @Parent(type = PARENT_TYPE) private String parentId;
@Field(type = FieldType.Text, store = true) private String name;
public ChildEntity() {}
public ChildEntity(String id, String parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
public String getId() {
return id;
}
public String getParentId() {
return parentId;
}
public String getName() {
return name;
}
@Override
public String toString() {
return new ToStringCreator(this).append("id", id).append("parentId", parentId).append("name", name).toString();
}
}
}
}

View File

@ -1,18 +1,53 @@
/*
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core;
import static org.apache.commons.lang.RandomStringUtils.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.engine.DocumentMissingException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.UpdateQuery;
import org.springframework.data.elasticsearch.core.query.UpdateQueryBuilder;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTests {
@ -22,8 +57,35 @@ public class ElasticsearchTransportTemplateTests extends ElasticsearchTemplateTe
// when
IndexRequest indexRequest = new IndexRequest();
indexRequest.source("{}", XContentType.JSON);
UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5))
.withClass(SampleEntity.class).withIndexRequest(indexRequest).build();
UpdateQuery updateQuery = new UpdateQueryBuilder().withId(randomNumeric(5)).withClass(SampleEntity.class)
.withIndexRequest(indexRequest).build();
elasticsearchTemplate.update(updateQuery);
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-core-transport-template", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
}

View File

@ -15,14 +15,14 @@
*/
package org.springframework.data.elasticsearch.core;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.elasticsearch.action.search.SearchPhaseExecutionException;
@ -30,11 +30,13 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.facet.LogEntity;
import org.springframework.data.elasticsearch.core.facet.LogEntityBuilder;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -43,79 +45,188 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*
* @author Artur Konczak
* @author Mohsin Husen
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class LogEntityTests {
@Autowired
private ElasticsearchTemplate template;
@Autowired private ElasticsearchTemplate template;
@Before
public void before() throws ParseException {
template.deleteIndex(LogEntity.class);
template.createIndex(LogEntity.class);
template.putMapping(LogEntity.class);
IndexInitializer.init(template, LogEntity.class);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
IndexQuery indexQuery1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse("2013-10-18 18:01")).code(2)
.ip("10.10.10.1").buildIndex();
IndexQuery indexQuery1 = new LogEntityBuilder("1").action("update").date(dateFormatter.parse("2013-10-18 18:01"))
.code(2).ip("10.10.10.1").buildIndex();
IndexQuery indexQuery2 = new LogEntityBuilder("2").action("update").date(dateFormatter.parse("2013-10-19 18:02")).code(2)
.ip("10.10.10.2").buildIndex();
IndexQuery indexQuery2 = new LogEntityBuilder("2").action("update").date(dateFormatter.parse("2013-10-19 18:02"))
.code(2).ip("10.10.10.2").buildIndex();
IndexQuery indexQuery3 = new LogEntityBuilder("3").action("update").date(dateFormatter.parse("2013-10-19 18:03")).code(2)
.ip("10.10.10.3").buildIndex();
IndexQuery indexQuery3 = new LogEntityBuilder("3").action("update").date(dateFormatter.parse("2013-10-19 18:03"))
.code(2).ip("10.10.10.3").buildIndex();
IndexQuery indexQuery4 = new LogEntityBuilder("4").action("update").date(dateFormatter.parse("2013-10-19 18:04")).code(2)
.ip("10.10.10.4").buildIndex();
IndexQuery indexQuery4 = new LogEntityBuilder("4").action("update").date(dateFormatter.parse("2013-10-19 18:04"))
.code(2).ip("10.10.10.4").buildIndex();
template.bulkIndex(Arrays.asList(indexQuery1, indexQuery2, indexQuery3, indexQuery4));
template.refresh(LogEntity.class);
}
/*
DATAES-66
*/
@Test
public void shouldIndexGivenLogEntityWithIPFieldType() throws ParseException {
//when
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(termQuery("ip", "10.10.10.1")).build();
@Test // DATAES-66
public void shouldIndexGivenLogEntityWithIPFieldType() {
// when
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("ip", "10.10.10.1")).build();
List<LogEntity> entities = template.queryForList(searchQuery, LogEntity.class);
//then
assertThat(entities, is(notNullValue()));
assertThat(entities.size(), is(1));
// then
assertThat(entities).isNotNull().hasSize(1);
}
/*
DATAES-66
*/
@Test(expected = SearchPhaseExecutionException.class)
@Test(expected = SearchPhaseExecutionException.class) // DATAES-66
public void shouldThrowExceptionWhenInvalidIPGivenForSearchQuery() {
//when
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(termQuery("ip", "10.10.10")).build();
// when
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("ip", "10.10.10")).build();
List<LogEntity> entities = template.queryForList(searchQuery, LogEntity.class);
//then
assertThat(entities, is(notNullValue()));
assertThat(entities.size(), is(1));
// then
assertThat(entities).isNotNull().hasSize(1);
}
/*
DATAES-66
*/
@Test
@Test // DATAES-66
public void shouldReturnLogsForGivenIPRanges() {
//when
// when
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(rangeQuery("ip").from("10.10.10.1").to("10.10.10.3")).build();
List<LogEntity> entities = template.queryForList(searchQuery, LogEntity.class);
//then
assertThat(entities, is(notNullValue()));
assertThat(entities.size(), is(3));
// then
assertThat(entities).isNotNull().hasSize(3);
}
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
@Document(indexName = "test-index-log-core", type = "test-log-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class LogEntity {
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
@Id private String id;
private String action;
private long sequenceCode;
@Field(type = Ip) private String ip;
@Field(type = Date) private java.util.Date date;
private LogEntity() {}
public LogEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAction() {
return action;
}
public String toString() {
return new StringBuffer().append("{id:").append(id).append(",action:").append(action).append(",code:")
.append(sequenceCode).append(",date:").append(format.format(date)).append("}").toString();
}
public void setAction(String action) {
this.action = action;
}
public long getSequenceCode() {
return sequenceCode;
}
public void setSequenceCode(long sequenceCode) {
this.sequenceCode = sequenceCode;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
static class LogEntityBuilder {
private LogEntity result;
public LogEntityBuilder(String id) {
result = new LogEntity(id);
}
public LogEntityBuilder action(String action) {
result.setAction(action);
return this;
}
public LogEntityBuilder code(long sequenceCode) {
result.setSequenceCode(sequenceCode);
return this;
}
public LogEntityBuilder date(Date date) {
result.setDate(date);
return this;
}
public LogEntityBuilder ip(String ip) {
result.setIp(ip);
return this;
}
public LogEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}
}

View File

@ -16,48 +16,58 @@
package org.springframework.data.elasticsearch.core;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.skyscreamer.jsonassert.JSONAssert.assertEquals;
import static org.skyscreamer.jsonassert.JSONAssert.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import static org.springframework.data.elasticsearch.utils.IndexBuilder.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.io.IOException;
import java.lang.Boolean;
import java.lang.Integer;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.assertj.core.data.Percentage;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.elasticsearch.annotations.CompletionField;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.Mapping;
import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.annotations.Parent;
import org.springframework.data.elasticsearch.builder.SampleInheritedEntityBuilder;
import org.springframework.data.elasticsearch.annotations.Setting;
import org.springframework.data.elasticsearch.core.completion.Completion;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.entities.Book;
import org.springframework.data.elasticsearch.entities.CopyToEntity;
import org.springframework.data.elasticsearch.entities.GeoEntity;
import org.springframework.data.elasticsearch.entities.Group;
import org.springframework.data.elasticsearch.entities.NormalizerEntity;
import org.springframework.data.elasticsearch.entities.SampleInheritedEntity;
import org.springframework.data.elasticsearch.entities.SampleTransientEntity;
import org.springframework.data.elasticsearch.entities.SimpleRecursiveEntity;
import org.springframework.data.elasticsearch.entities.StockPrice;
import org.springframework.data.elasticsearch.entities.User;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Polygon;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -77,9 +87,23 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
elasticsearchTemplate.deleteIndex(StockPrice.class);
elasticsearchTemplate.deleteIndex(SimpleRecursiveEntity.class);
elasticsearchTemplate.deleteIndex(StockPrice.class);
elasticsearchTemplate.deleteIndex(SampleInheritedEntity.class);
elasticsearchTemplate.deleteIndex(User.class);
elasticsearchTemplate.deleteIndex(Group.class);
elasticsearchTemplate.deleteIndex(Book.class);
elasticsearchTemplate.deleteIndex(NormalizerEntity.class);
elasticsearchTemplate.deleteIndex(CopyToEntity.class);
}
@Test
public void shouldNotFailOnCircularReference() {
elasticsearchTemplate.deleteIndex(SimpleRecursiveEntity.class);
elasticsearchTemplate.createIndex(SimpleRecursiveEntity.class);
elasticsearchTemplate.putMapping(SimpleRecursiveEntity.class);
elasticsearchTemplate.refresh(SimpleRecursiveEntity.class);
@ -115,7 +139,6 @@ public class MappingBuilderTests extends MappingContextBaseTests {
// Given
// When
elasticsearchTemplate.deleteIndex(StockPrice.class);
elasticsearchTemplate.createIndex(StockPrice.class);
elasticsearchTemplate.putMapping(StockPrice.class);
String symbol = "AU";
@ -128,11 +151,12 @@ public class MappingBuilderTests extends MappingContextBaseTests {
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
List<StockPrice> result = elasticsearchTemplate.queryForList(searchQuery, StockPrice.class);
// Then
assertThat(result.size(), is(1));
assertThat(result).hasSize(1);
StockPrice entry = result.get(0);
assertThat(entry.getSymbol(), is(symbol));
assertThat(entry.getPrice(), is(BigDecimal.valueOf(price)));
assertThat(entry.getSymbol()).isEqualTo(symbol);
assertThat(entry.getPrice()).isCloseTo(BigDecimal.valueOf(price), Percentage.withPercentage(0.01));
}
@Test // DATAES-568
@ -160,10 +184,9 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@Test // DATAES-76
public void shouldAddSampleInheritedEntityDocumentToIndex() {
// Given
// given
// When
elasticsearchTemplate.deleteIndex(SampleInheritedEntity.class);
// when
elasticsearchTemplate.createIndex(SampleInheritedEntity.class);
elasticsearchTemplate.putMapping(SampleInheritedEntity.class);
Date createdDate = new Date();
@ -175,12 +198,13 @@ public class MappingBuilderTests extends MappingContextBaseTests {
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
List<SampleInheritedEntity> result = elasticsearchTemplate.queryForList(searchQuery, SampleInheritedEntity.class);
// Then
assertThat(result.size(), is(1));
// then
assertThat(result).hasSize(1);
SampleInheritedEntity entry = result.get(0);
assertThat(entry.getCreatedDate(), is(createdDate));
assertThat(entry.getMessage(), is(message));
assertThat(entry.getCreatedDate()).isEqualTo(createdDate);
assertThat(entry.getMessage()).isEqualTo(message);
}
@Test // DATAES-568
@ -207,6 +231,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
elasticsearchTemplate.putMapping(User.class);
elasticsearchTemplate.createIndex(Group.class);
elasticsearchTemplate.putMapping(Group.class);
// when
// then
@ -218,7 +243,9 @@ public class MappingBuilderTests extends MappingContextBaseTests {
// given
elasticsearchTemplate.createIndex(Book.class);
elasticsearchTemplate.putMapping(Book.class);
// when
// then
}
@ -226,7 +253,6 @@ public class MappingBuilderTests extends MappingContextBaseTests {
public void shouldUseBothAnalyzer() {
// given
elasticsearchTemplate.deleteIndex(Book.class);
elasticsearchTemplate.createIndex(Book.class);
elasticsearchTemplate.putMapping(Book.class);
@ -236,19 +262,18 @@ public class MappingBuilderTests extends MappingContextBaseTests {
Map prefixDescription = (Map) ((Map) descriptionMapping.get("fields")).get("prefix");
// then
assertThat(prefixDescription.size(), is(3));
assertThat(prefixDescription.get("type"), equalTo("text"));
assertThat(prefixDescription.get("analyzer"), equalTo("stop"));
assertThat(prefixDescription.get("search_analyzer"), equalTo("standard"));
assertThat(descriptionMapping.get("type"), equalTo("text"));
assertThat(descriptionMapping.get("analyzer"), equalTo("whitespace"));
assertThat(prefixDescription).hasSize(3);
assertThat(prefixDescription.get("type")).isEqualTo("text");
assertThat(prefixDescription.get("analyzer")).isEqualTo("stop");
assertThat(prefixDescription.get("search_analyzer")).isEqualTo("standard");
assertThat(descriptionMapping.get("type")).isEqualTo("text");
assertThat(descriptionMapping.get("analyzer")).isEqualTo("whitespace");
}
@Test // DATAES-492
public void shouldUseKeywordNormalizer() {
// given
elasticsearchTemplate.deleteIndex(NormalizerEntity.class);
elasticsearchTemplate.createIndex(NormalizerEntity.class);
elasticsearchTemplate.putMapping(NormalizerEntity.class);
@ -259,17 +284,16 @@ public class MappingBuilderTests extends MappingContextBaseTests {
Map fieldDescriptionLowerCase = (Map) ((Map) ((Map) properties.get("description")).get("fields")).get("lower_case");
// then
assertThat(fieldName.get("type"), equalTo("keyword"));
assertThat(fieldName.get("normalizer"), equalTo("lower_case_normalizer"));
assertThat(fieldDescriptionLowerCase.get("type"), equalTo("keyword"));
assertThat(fieldDescriptionLowerCase.get("normalizer"), equalTo("lower_case_normalizer"));
assertThat(fieldName.get("type")).isEqualTo("keyword");
assertThat(fieldName.get("normalizer")).isEqualTo("lower_case_normalizer");
assertThat(fieldDescriptionLowerCase.get("type")).isEqualTo("keyword");
assertThat(fieldDescriptionLowerCase.get("normalizer")).isEqualTo("lower_case_normalizer");
}
@Test // DATAES-503
public void shouldUseCopyTo() {
// given
elasticsearchTemplate.deleteIndex(CopyToEntity.class);
elasticsearchTemplate.createIndex(CopyToEntity.class);
elasticsearchTemplate.putMapping(CopyToEntity.class);
@ -281,8 +305,8 @@ public class MappingBuilderTests extends MappingContextBaseTests {
// then
List<String> copyToValue = Collections.singletonList("name");
assertThat(fieldFirstName.get("copy_to"), equalTo(copyToValue));
assertThat(fieldLastName.get("copy_to"), equalTo(copyToValue));
assertThat(fieldFirstName.get("copy_to")).isEqualTo(copyToValue);
assertThat(fieldLastName.get("copy_to")).isEqualTo(copyToValue);
}
@Test // DATAES-568
@ -455,7 +479,7 @@ public class MappingBuilderTests extends MappingContextBaseTests {
/**
* MinimalChildEntity
*
* @author Peter-josef Meisch
* @author Peter-Josef Meisch
*/
@Document(indexName = "test-index-minimal", type = "mapping")
static class MinimalChildEntity {
@ -464,4 +488,303 @@ public class MappingBuilderTests extends MappingContextBaseTests {
@Parent(type = "parentType") private String parentId;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Nordine Bittich
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-book-mapping-builder", type = "book", shards = 1, replicas = 0, refreshInterval = "-1")
static class Book {
@Id private String id;
private String name;
@Field(type = FieldType.Object) private Author author;
@Field(type = FieldType.Nested) private Map<Integer, Collection<String>> buckets = new HashMap<>();
@MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"),
otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop",
searchAnalyzer = "standard") }) private String description;
}
/**
* @author Stuart Stevenson
* @author Mohsin Husen
*/
@Document(indexName = "test-index-simple-recursive-mapping-builder", type = "circular-object", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SimpleRecursiveEntity {
@Id private String id;
@Field(type = FieldType.Object, ignoreFields = { "circularObject" }) private SimpleRecursiveEntity circularObject;
}
/**
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-copy-to-mapping-builder", type = "test", shards = 1, replicas = 0, refreshInterval = "-1")
static class CopyToEntity {
@Id private String id;
@Field(type = FieldType.Keyword, copyTo = "name") private String firstName;
@Field(type = FieldType.Keyword, copyTo = "name") private String lastName;
@Field(type = FieldType.Keyword) private String name;
}
/**
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-normalizer-mapping-builder", type = "test", shards = 1, replicas = 0, refreshInterval = "-1")
@Setting(settingPath = "/settings/test-normalizer.json")
static class NormalizerEntity {
@Id private String id;
@Field(type = FieldType.Keyword, normalizer = "lower_case_normalizer") private String name;
@MultiField(mainField = @Field(type = FieldType.Text), otherFields = { @InnerField(suffix = "lower_case",
type = FieldType.Keyword, normalizer = "lower_case_normalizer") }) private String description;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
static class Author {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
/**
* @author Kevin Leturc
*/
@Document(indexName = "test-index-sample-inherited-mapping-builder", type = "mapping", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleInheritedEntity extends AbstractInheritedEntity {
@Field(type = Text, index = false, store = true, analyzer = "standard") private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
/**
* @author Kevin Leturc
*/
static class SampleInheritedEntityBuilder {
private SampleInheritedEntity result;
public SampleInheritedEntityBuilder(String id) {
result = new SampleInheritedEntity();
result.setId(id);
}
public SampleInheritedEntityBuilder createdDate(Date createdDate) {
result.setCreatedDate(createdDate);
return this;
}
public SampleInheritedEntityBuilder message(String message) {
result.setMessage(message);
return this;
}
public SampleInheritedEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}
/**
* @author Artur Konczak
* @author Mohsin Husen
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-stock-mapping-builder", type = "price", shards = 1, replicas = 0, refreshInterval = "-1")
static class StockPrice {
@Id private String id;
private String symbol;
@Field(type = FieldType.Double) private BigDecimal price;
}
/**
* @author Kevin Letur
*/
static class AbstractInheritedEntity {
@Id private String id;
@Field(type = FieldType.Date, index = false) private Date createdDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
/**
* @author Jakub Vavrik
*/
@Document(indexName = "test-index-recursive-mapping-mapping-builder", type = "mapping", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleTransientEntity {
@Id private String id;
@Field(type = Text, index = false, store = true, analyzer = "standard") private String message;
@Transient private SampleTransientEntity.NestedEntity nested;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
static class NestedEntity {
@Field private static SampleTransientEntity.NestedEntity someField = new SampleTransientEntity.NestedEntity();
@Field private Boolean something;
public SampleTransientEntity.NestedEntity getSomeField() {
return someField;
}
public void setSomeField(SampleTransientEntity.NestedEntity someField) {
this.someField = someField;
}
public Boolean getSomething() {
return something;
}
public void setSomething(Boolean something) {
this.something = something;
}
}
}
/**
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-geo-mapping-builder", type = "geo-test-index", shards = 1, replicas = 0, refreshInterval = "-1")
static class GeoEntity {
@Id private String id;
// geo shape - Spring Data
private Box box;
private Circle circle;
private Polygon polygon;
// geo point - Custom implementation + Spring Data
@GeoPointField private Point pointA;
private GeoPoint pointB;
@GeoPointField private String pointC;
@GeoPointField private double[] pointD;
}
/**
* Created by akonczak on 21/08/2016.
*/
@Document(indexName = "test-index-user-mapping-builder", type = "user")
static class User {
@Id private String id;
@Field(type = FieldType.Nested, ignoreFields = { "users" }) private Set<Group> groups = new HashSet<>();
}
/**
* Created by akonczak on 21/08/2016.
*/
@Document(indexName = "test-index-group-mapping-builder", type = "group")
static class Group {
@Id String id;
@Field(type = FieldType.Nested, ignoreFields = { "groups" }) private Set<User> users = new HashSet<>();
}
}

View File

@ -15,9 +15,6 @@
package org.springframework.data.elasticsearch.core;
import java.util.Collection;
import java.util.Collections;
import org.springframework.data.elasticsearch.config.ElasticsearchConfigurationSupport;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
@ -37,13 +34,8 @@ abstract class MappingContextBaseTests {
private SimpleElasticsearchMappingContext setupMappingContext() {
SimpleElasticsearchMappingContext mappingContext = new ElasticsearchConfigurationSupport() {
@Override
protected Collection<String> getMappingBasePackages() {
return Collections.singletonList("org.springframework.data.elasticsearch.entities.mapping");
}
}.elasticsearchMappingContext();
SimpleElasticsearchMappingContext mappingContext = new ElasticsearchConfigurationSupport() {}
.elasticsearchMappingContext();
mappingContext.initialize();
return mappingContext;
}

View File

@ -17,13 +17,21 @@ package org.springframework.data.elasticsearch.core;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import java.net.ConnectException;
import java.util.Arrays;
import java.util.Collections;
@ -39,10 +47,10 @@ import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@ -50,6 +58,10 @@ import org.springframework.data.elasticsearch.ElasticsearchVersion;
import org.springframework.data.elasticsearch.ElasticsearchVersionRule;
import org.springframework.data.elasticsearch.TestUtils;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
@ -57,7 +69,6 @@ import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StringUtils;
@ -68,6 +79,7 @@ import org.springframework.util.StringUtils;
* @author Christoph Strobl
* @author Mark Paluch
* @currentRead Golden Fool - Robin Hobb
* @author Peter-Josef Meisch
*/
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:infrastructure.xml")
@ -75,7 +87,7 @@ public class ReactiveElasticsearchTemplateTests {
public @Rule ElasticsearchVersionRule elasticsearchVersion = ElasticsearchVersionRule.any();
static final String DEFAULT_INDEX = "test-index-sample";
static final String DEFAULT_INDEX = "reactive-template-test-index";
static final String ALTERNATE_INDEX = "reactive-template-tests-alternate-index";
private ElasticsearchRestTemplate restTemplate;
@ -676,4 +688,74 @@ public class ReactiveElasticsearchTemplateTests {
static class Message {
String message;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = DEFAULT_INDEX, type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
}

View File

@ -18,13 +18,21 @@ package org.springframework.data.elasticsearch.core;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.action.search.SearchRequest.*;
import static org.mockito.Mockito.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import java.util.Collections;
import org.elasticsearch.action.delete.DeleteRequest;
@ -41,15 +49,24 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.StringQuery;
import org.springframework.data.elasticsearch.entities.SampleEntity;
/**
* @author Christoph Strobl
* @currentRead Fool's Fate - Robin Hobb
* @author Peter-Josef Meisch
*/
public class ReactiveElasticsearchTemplateUnitTests {
@ -61,6 +78,7 @@ public class ReactiveElasticsearchTemplateUnitTests {
@Before
public void setUp() {
template = new ReactiveElasticsearchTemplate(client);
}
@ -126,7 +144,6 @@ public class ReactiveElasticsearchTemplateUnitTests {
ArgumentCaptor<SearchRequest> captor = ArgumentCaptor.forClass(SearchRequest.class);
when(client.search(captor.capture())).thenReturn(Flux.empty());
template.find(new CriteriaQuery(new Criteria("*")).setPageable(PageRequest.of(2, 50)), SampleEntity.class) //
.as(StepVerifier::create) //
.verifyComplete();
@ -141,7 +158,6 @@ public class ReactiveElasticsearchTemplateUnitTests {
ArgumentCaptor<SearchRequest> captor = ArgumentCaptor.forClass(SearchRequest.class);
when(client.scroll(captor.capture())).thenReturn(Flux.empty());
template.find(new CriteriaQuery(new Criteria("*")).setPageable(Pageable.unpaged()), SampleEntity.class) //
.as(StepVerifier::create) //
.verifyComplete();
@ -232,4 +248,74 @@ public class ReactiveElasticsearchTemplateUnitTests {
assertThat(captor.getValue().indicesOptions()).isEqualTo(IndicesOptions.LENIENT_EXPAND_OPEN);
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-core-reactive-template-Unit", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available)
return false;
if (rate != that.rate)
return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage)
: that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (type != null ? !type.equals(that.type) : that.type != null)
return false;
if (version != null ? !version.equals(that.version) : that.version != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}
}

View File

@ -3,12 +3,16 @@ package org.springframework.data.elasticsearch.core;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.elasticsearch.entities.SampleDynamicTemplatesEntity;
import org.springframework.data.elasticsearch.entities.SampleDynamicTemplatesEntityTwo;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.DynamicTemplates;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -48,4 +52,31 @@ public class SimpleDynamicTemplatesMappingTests extends MappingContextBaseTests
assertEquals(EXPECTED_MAPPING_TWO, mapping);
}
/**
* @author Petr Kukral
*/
@Document(indexName = "test-dynamictemplates", type = "test-dynamictemplatestype", indexStoreType = "memory",
shards = 1, replicas = 0, refreshInterval = "-1")
@DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings.json")
static class SampleDynamicTemplatesEntity {
@Id private String id;
@Field(type = FieldType.Object) private Map<String, String> names = new HashMap<String, String>();
}
/**
* @author Petr Kukral
*/
@Document(indexName = "test-dynamictemplates", type = "test-dynamictemplatestype", indexStoreType = "memory",
shards = 1, replicas = 0, refreshInterval = "-1")
@DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings_two.json")
static class SampleDynamicTemplatesEntityTwo {
@Id private String id;
@Field(type = FieldType.Object) private Map<String, String> names = new HashMap<String, String>();
}
}

View File

@ -16,12 +16,17 @@
package org.springframework.data.elasticsearch.core;
import static org.junit.Assert.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import java.io.IOException;
import java.util.Date;
import org.junit.Test;
import org.springframework.data.elasticsearch.entities.SampleDateMappingEntity;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Jakub Vavrik
@ -43,4 +48,63 @@ public class SimpleElasticsearchDateMappingTests extends MappingContextBaseTests
assertEquals(EXPECTED_MAPPING, mapping);
}
/**
* @author Jakub Vavrik
*/
@Document(indexName = "test-index-date-mapping-core", type = "mapping", shards = 1, replicas = 0,
refreshInterval = "-1")
static class SampleDateMappingEntity {
@Id private String id;
@Field(type = Text, index = false, store = true, analyzer = "standard") private String message;
@Field(type = Date, format = DateFormat.custom,
pattern = "dd.MM.yyyy hh:mm") private java.util.Date customFormatDate;
@Field(type = FieldType.Date) private Date defaultFormatDate;
@Field(type = FieldType.Date, format = DateFormat.basic_date) private Date basicFormatDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getCustomFormatDate() {
return customFormatDate;
}
public void setCustomFormatDate(Date customFormatDate) {
this.customFormatDate = customFormatDate;
}
public Date getDefaultFormatDate() {
return defaultFormatDate;
}
public void setDefaultFormatDate(Date defaultFormatDate) {
this.defaultFormatDate = defaultFormatDate;
}
public Date getBasicFormatDate() {
return basicFormatDate;
}
public void setBasicFormatDate(Date basicFormatDate) {
this.basicFormatDate = basicFormatDate;
}
}
}

View File

@ -15,39 +15,44 @@
*/
package org.springframework.data.elasticsearch.core.aggregation;
import static org.elasticsearch.action.search.SearchType.*;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.elasticsearch.search.aggregations.AggregationBuilders.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.Integer;
import java.lang.Integer;
import java.util.ArrayList;
import java.util.List;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.search.aggregations.Aggregations;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.ResultsExtractor;
import org.springframework.data.elasticsearch.core.facet.ArticleEntity;
import org.springframework.data.elasticsearch.core.facet.ArticleEntityBuilder;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.search.aggregations.AggregationBuilders.terms;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Jonathan Yan
* @author Artur Konczak
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
@ -60,20 +65,27 @@ public class ElasticsearchTemplateAggregationTests {
public static final int YEAR_2002 = 2002;
public static final int YEAR_2001 = 2001;
public static final int YEAR_2000 = 2000;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public static final String INDEX_NAME = "test-index-articles-core-aggregation";
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
elasticsearchTemplate.deleteIndex(ArticleEntity.class);
elasticsearchTemplate.createIndex(ArticleEntity.class);
elasticsearchTemplate.putMapping(ArticleEntity.class);
elasticsearchTemplate.refresh(ArticleEntity.class);
IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").subject("computing").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex();
IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").subject("computing").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex();
IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").subject("computing").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex();
IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").subject("accounting").addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex();
IndexInitializer.init(elasticsearchTemplate, ArticleEntity.class);
IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").subject("computing")
.addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10)
.buildIndex();
IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").subject("computing")
.addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20)
.buildIndex();
IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").subject("computing")
.addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000)
.score(30).buildIndex();
IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").subject("accounting")
.addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000)
.score(40).buildIndex();
elasticsearchTemplate.index(article1);
elasticsearchTemplate.index(article2);
@ -82,14 +94,21 @@ public class ElasticsearchTemplateAggregationTests {
elasticsearchTemplate.refresh(ArticleEntity.class);
}
@After
public void after() {
elasticsearchTemplate.deleteIndex(ArticleEntity.class);
}
@Test
public void shouldReturnAggregatedResponseForGivenSearchQuery() {
// given
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.withSearchType(SearchType.DEFAULT)
.withIndices("test-index-articles").withTypes("article")
.addAggregation(terms("subjects").field("subject"))
SearchQuery searchQuery = new NativeSearchQueryBuilder() //
.withQuery(matchAllQuery()) //
.withSearchType(SearchType.DEFAULT) //
.withIndices(INDEX_NAME).withTypes("article") //
.addAggregation(terms("subjects").field("subject")) //
.build();
// when
Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() {
@ -99,9 +118,139 @@ public class ElasticsearchTemplateAggregationTests {
}
});
// then
assertThat(aggregations, is(notNullValue()));
assertThat(aggregations.asMap().get("subjects"), is(notNullValue()));
assertThat(aggregations).isNotNull();
assertThat(aggregations.asMap().get("subjects")).isNotNull();
}
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
@Document(indexName = "test-index-articles-core-aggregation", type = "article", shards = 1, replicas = 0, refreshInterval = "-1")
static class ArticleEntity {
@Id private String id;
private String title;
@Field(type = Text, fielddata = true) private String subject;
@MultiField(mainField = @Field(type = Text),
otherFields = {
@InnerField(suffix = "untouched", type = Text, store = true, fielddata = true, analyzer = "keyword"),
@InnerField(suffix = "sort", type = Text, store = true,
analyzer = "keyword") }) private List<String> authors = new ArrayList<>();
@Field(type = Integer, store = true) private List<Integer> publishedYears = new ArrayList<>();
private int score;
private ArticleEntity() {
}
public ArticleEntity(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public List<Integer> getPublishedYears() {
return publishedYears;
}
public void setPublishedYears(List<Integer> publishedYears) {
this.publishedYears = publishedYears;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
static class ArticleEntityBuilder {
private ArticleEntity result;
public ArticleEntityBuilder(String id) {
result = new ArticleEntity(id);
}
public ArticleEntityBuilder title(String title) {
result.setTitle(title);
return this;
}
public ArticleEntityBuilder subject(String subject) {
result.setSubject(subject);
return this;
}
public ArticleEntityBuilder addAuthor(String author) {
result.getAuthors().add(author);
return this;
}
public ArticleEntityBuilder addPublishedYear(Integer year) {
result.getPublishedYears().add(year);
return this;
}
public ArticleEntityBuilder score(int score) {
result.setScore(score);
return this;
}
public ArticleEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}
}

View File

@ -1,50 +0,0 @@
package org.springframework.data.elasticsearch.core.completion;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.CompletionField;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author Mewes Kochheim
*/
@Document(indexName = "test-index-annotated-completion", type = "annotated-completion-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class AnnotatedCompletionEntity {
@Id
private String id;
private String name;
@CompletionField(maxInputLength = 100)
private Completion suggest;
private AnnotatedCompletionEntity() {
}
public AnnotatedCompletionEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Completion getSuggest() {
return suggest;
}
public void setSuggest(Completion suggest) {
this.suggest = suggest;
}
}

View File

@ -1,59 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.completion;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
/**
* @author Franck Marchand
* @author Mohsin Husen
* @author Mewes Kochheim
*/
public class AnnotatedCompletionEntityBuilder {
private AnnotatedCompletionEntity result;
public AnnotatedCompletionEntityBuilder(String id) {
result = new AnnotatedCompletionEntity(id);
}
public AnnotatedCompletionEntityBuilder name(String name) {
result.setName(name);
return this;
}
public AnnotatedCompletionEntityBuilder suggest(String[] input) {
return suggest(input, null);
}
public AnnotatedCompletionEntityBuilder suggest(String[] input, Integer weight) {
Completion suggest = new Completion(input);
suggest.setWeight(weight);
result.setSuggest(suggest);
return this;
}
public AnnotatedCompletionEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}

View File

@ -1,52 +0,0 @@
package org.springframework.data.elasticsearch.core.completion;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.CompletionField;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author Franck Marchand
* @author Mohsin Husen
* @author Mewes Kochheim
*/
@Document(indexName = "test-index-completion-annotated", type = "completion-annotation-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class CompletionAnnotatedEntity {
@Id
private String id;
private String name;
@CompletionField
private Completion suggest;
private CompletionAnnotatedEntity() {
}
public CompletionAnnotatedEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Completion getSuggest() {
return suggest;
}
public void setSuggest(Completion suggest) {
this.suggest = suggest;
}
}

View File

@ -1,50 +0,0 @@
package org.springframework.data.elasticsearch.core.completion;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.CompletionField;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author Mewes Kochheim
*/
@Document(indexName = "test-index-completion", type = "completion-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class CompletionEntity {
@Id
private String id;
private String name;
@CompletionField(maxInputLength = 100)
private Completion suggest;
private CompletionEntity() {
}
public CompletionEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Completion getSuggest() {
return suggest;
}
public void setSuggest(Completion suggest) {
this.suggest = suggest;
}
}

View File

@ -1,61 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.completion;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
/**
* @author Franck Marchand
* @author Mohsin Husen
* @author Mewes Kochheim
*/
public class CompletionEntityAnnotatedBuilder {
private CompletionAnnotatedEntity result;
public CompletionEntityAnnotatedBuilder(String id) {
result = new CompletionAnnotatedEntity(id);
}
public CompletionEntityAnnotatedBuilder name(String name) {
result.setName(name);
return this;
}
public CompletionEntityAnnotatedBuilder suggest(String[] input) {
return suggest(input, null);
}
public CompletionEntityAnnotatedBuilder suggest(String[] input, Integer weight) {
Completion suggest = new Completion(input);
if (weight != null) {
suggest.setWeight(weight);
}
result.setSuggest(suggest);
return this;
}
public CompletionAnnotatedEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}

View File

@ -1,58 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.completion;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
/**
* @author Mewes Kochheim
*/
public class CompletionEntityBuilder {
private CompletionEntity result;
public CompletionEntityBuilder(String id) {
result = new CompletionEntity(id);
}
public CompletionEntityBuilder name(String name) {
result.setName(name);
return this;
}
public CompletionEntityBuilder suggest(String[] input) {
return suggest(input, null);
}
public CompletionEntityBuilder suggest(String[] input, Integer weight) {
Completion suggest = new Completion(input);
suggest.setWeight(weight);
result.setSuggest(suggest);
return this;
}
public CompletionEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}

View File

@ -1,57 +0,0 @@
package org.springframework.data.elasticsearch.core.completion;
import org.elasticsearch.search.suggest.completion.context.ContextMapping;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.CompletionContext;
import org.springframework.data.elasticsearch.annotations.CompletionContextType;
import org.springframework.data.elasticsearch.annotations.CompletionField;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author Mewes Kochheim
* @author Robert Gruendler
*/
@Document(indexName = "test-index-context-completion", type = "context-completion-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class ContextCompletionEntity {
public static final String LANGUAGE_CATEGORY = "language";
@Id
private String id;
private String name;
@CompletionField(maxInputLength = 100, contexts = {
@CompletionContext(name = LANGUAGE_CATEGORY, type = ContextMapping.Type.CATEGORY)
})
private Completion suggest;
private ContextCompletionEntity() {
}
public ContextCompletionEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Completion getSuggest() {
return suggest;
}
public void setSuggest(Completion suggest) {
this.suggest = suggest;
}
}

View File

@ -1,57 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.completion;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import java.util.List;
import java.util.Map;
/**
* @author Robert Gruendler
*/
public class ContextCompletionEntityBuilder {
private ContextCompletionEntity result;
public ContextCompletionEntityBuilder(String id) {
result = new ContextCompletionEntity(id);
}
public ContextCompletionEntityBuilder name(String name) {
result.setName(name);
return this;
}
public ContextCompletionEntityBuilder suggest(String[] input, Map<String, List<String>> contexts) {
Completion suggest = new Completion(input);
suggest.setContexts(contexts);
result.setSuggest(suggest);
return this;
}
public ContextCompletionEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}

View File

@ -15,9 +15,7 @@
*/
package org.springframework.data.elasticsearch.core.completion;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;
@ -28,84 +26,85 @@ import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.SuggestionBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.CompletionField;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.entities.NonDocumentEntity;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertEquals;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Franck Marchand
* @author Artur Konczak
* @author Mewes Kochheim
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class ElasticsearchTemplateCompletionTests {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
private void loadCompletionObjectEntities() {
elasticsearchTemplate.deleteIndex(CompletionEntity.class);
elasticsearchTemplate.createIndex(CompletionEntity.class);
elasticsearchTemplate.refresh(CompletionEntity.class);
elasticsearchTemplate.putMapping(CompletionEntity.class);
IndexInitializer.init(elasticsearchTemplate, CompletionEntity.class);
List<IndexQuery> indexQueries = new ArrayList<>();
indexQueries.add(new CompletionEntityBuilder("1").name("Rizwan Idrees").suggest(new String[]{"Rizwan Idrees"}).buildIndex());
indexQueries.add(new CompletionEntityBuilder("2").name("Franck Marchand").suggest(new String[]{"Franck", "Marchand"}).buildIndex());
indexQueries.add(new CompletionEntityBuilder("3").name("Mohsin Husen").suggest(new String[]{"Mohsin", "Husen"}).buildIndex());
indexQueries.add(new CompletionEntityBuilder("4").name("Artur Konczak").suggest(new String[]{"Artur", "Konczak"}).buildIndex());
indexQueries.add(
new CompletionEntityBuilder("1").name("Rizwan Idrees").suggest(new String[] { "Rizwan Idrees" }).buildIndex());
indexQueries.add(new CompletionEntityBuilder("2").name("Franck Marchand")
.suggest(new String[] { "Franck", "Marchand" }).buildIndex());
indexQueries.add(
new CompletionEntityBuilder("3").name("Mohsin Husen").suggest(new String[] { "Mohsin", "Husen" }).buildIndex());
indexQueries.add(new CompletionEntityBuilder("4").name("Artur Konczak").suggest(new String[] { "Artur", "Konczak" })
.buildIndex());
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(CompletionEntity.class);
}
private void loadAnnotatedCompletionObjectEntities() {
elasticsearchTemplate.deleteIndex(AnnotatedCompletionEntity.class);
elasticsearchTemplate.createIndex(AnnotatedCompletionEntity.class);
elasticsearchTemplate.refresh(AnnotatedCompletionEntity.class);
elasticsearchTemplate.putMapping(AnnotatedCompletionEntity.class);
IndexInitializer.init(elasticsearchTemplate, AnnotatedCompletionEntity.class);
NonDocumentEntity nonDocumentEntity = new NonDocumentEntity();
nonDocumentEntity.setSomeField1("foo");
nonDocumentEntity.setSomeField2("bar");
List<IndexQuery> indexQueries = new ArrayList<>();
indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Franck Marchand").suggest(new String[]{"Franck", "Marchand"}).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mohsin Husen").suggest(new String[]{"Mohsin", "Husen"}).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Rizwan Idrees").suggest(new String[]{"Rizwan", "Idrees"}).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("4").name("Artur Konczak").suggest(new String[]{"Artur", "Konczak"}).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Franck Marchand")
.suggest(new String[] { "Franck", "Marchand" }).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mohsin Husen")
.suggest(new String[] { "Mohsin", "Husen" }).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Rizwan Idrees")
.suggest(new String[] { "Rizwan", "Idrees" }).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("4").name("Artur Konczak")
.suggest(new String[] { "Artur", "Konczak" }).buildIndex());
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(AnnotatedCompletionEntity.class);
}
private void loadAnnotatedCompletionObjectEntitiesWithWeights() {
elasticsearchTemplate.deleteIndex(AnnotatedCompletionEntity.class);
elasticsearchTemplate.createIndex(AnnotatedCompletionEntity.class);
elasticsearchTemplate.putMapping(AnnotatedCompletionEntity.class);
elasticsearchTemplate.refresh(AnnotatedCompletionEntity.class);
IndexInitializer.init(elasticsearchTemplate, AnnotatedCompletionEntity.class);
List<IndexQuery> indexQueries = new ArrayList<>();
indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Mewes Kochheim1").suggest(new String[]{"Mewes Kochheim1"},4).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mewes Kochheim2").suggest(new String[]{"Mewes Kochheim2"}, 1).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Mewes Kochheim3").suggest(new String[]{"Mewes Kochheim3"}, 2).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("4").name("Mewes Kochheim4").suggest(new String[]{"Mewes Kochheim4"}, Integer.MAX_VALUE).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("1").name("Mewes Kochheim1")
.suggest(new String[] { "Mewes Kochheim1" }, 4).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("2").name("Mewes Kochheim2")
.suggest(new String[] { "Mewes Kochheim2" }, 1).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("3").name("Mewes Kochheim3")
.suggest(new String[] { "Mewes Kochheim3" }, 2).buildIndex());
indexQueries.add(new AnnotatedCompletionEntityBuilder("4").name("Mewes Kochheim4")
.suggest(new String[] { "Mewes Kochheim4" }, Integer.MAX_VALUE).buildIndex());
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(AnnotatedCompletionEntity.class);
@ -113,74 +112,286 @@ public class ElasticsearchTemplateCompletionTests {
@Test
public void shouldPutMappingForGivenEntity() throws Exception {
//given
// given
Class entity = CompletionEntity.class;
elasticsearchTemplate.createIndex(entity);
//when
assertThat(elasticsearchTemplate.putMapping(entity), is(true));
// when
assertThat(elasticsearchTemplate.putMapping(entity)).isTrue();
}
@Test
public void shouldFindSuggestionsForGivenCriteriaQueryUsingCompletionEntity() {
//given
// given
loadCompletionObjectEntities();
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO);
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m",
Fuzziness.AUTO);
//when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest",completionSuggestionFuzzyBuilder), CompletionEntity.class);
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), CompletionEntity.class);
CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest");
List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getEntries().get(0).getOptions();
//then
assertThat(options.size(), is(2));
assertThat(options.get(0).getText().string(), isOneOf("Marchand", "Mohsin"));
assertThat(options.get(1).getText().string(), isOneOf("Marchand", "Mohsin"));
// then
assertThat(options).hasSize(2);
assertThat(options.get(0).getText().string()).isIn("Marchand", "Mohsin");
assertThat(options.get(1).getText().string()).isIn("Marchand", "Mohsin");
}
@Test
public void shouldFindSuggestionsForGivenCriteriaQueryUsingAnnotatedCompletionEntity() {
//given
loadAnnotatedCompletionObjectEntities();
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO);
//when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), CompletionEntity.class);
// given
loadAnnotatedCompletionObjectEntities();
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m",
Fuzziness.AUTO);
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), CompletionEntity.class);
CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest");
List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getEntries().get(0).getOptions();
//then
assertThat(options.size(), is(2));
assertThat(options.get(0).getText().string(), isOneOf("Marchand", "Mohsin"));
assertThat(options.get(1).getText().string(), isOneOf("Marchand", "Mohsin"));
// then
assertThat(options).hasSize(2);
assertThat(options.get(0).getText().string()).isIn("Marchand", "Mohsin");
assertThat(options.get(1).getText().string()).isIn("Marchand", "Mohsin");
}
@Test
public void shouldFindSuggestionsWithWeightsForGivenCriteriaQueryUsingAnnotatedCompletionEntity() {
//given
loadAnnotatedCompletionObjectEntitiesWithWeights();
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO);
//when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest",completionSuggestionFuzzyBuilder), AnnotatedCompletionEntity.class);
// given
loadAnnotatedCompletionObjectEntitiesWithWeights();
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m",
Fuzziness.AUTO);
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder),
AnnotatedCompletionEntity.class);
CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest");
List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getEntries().get(0).getOptions();
//then
assertThat(options.size(), is(4));
// then
assertThat(options).hasSize(4);
for (CompletionSuggestion.Entry.Option option : options) {
if (option.getText().string().equals("Mewes Kochheim1")) {
assertEquals(4, option.getScore(), 0);
} else if (option.getText().string().equals("Mewes Kochheim2")) {
assertEquals(1, option.getScore(), 0);
} else if (option.getText().string().equals("Mewes Kochheim3")) {
assertEquals(2, option.getScore(), 0);
} else if (option.getText().string().equals("Mewes Kochheim4")) {
assertEquals(Integer.MAX_VALUE, option.getScore(), 0);
} else {
switch (option.getText().string()) {
case "Mewes Kochheim1":
assertThat(option.getScore()).isEqualTo(4);
break;
case "Mewes Kochheim2":
assertThat(option.getScore()).isEqualTo(1);
break;
case "Mewes Kochheim3":
assertThat(option.getScore()).isEqualTo(2);
break;
case "Mewes Kochheim4":
assertThat(option.getScore()).isEqualTo(Integer.MAX_VALUE);
break;
default:
fail("Unexpected option");
break;
}
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
static class NonDocumentEntity {
@Id private String someId;
private String someField1;
private String someField2;
public String getSomeField1() {
return someField1;
}
public void setSomeField1(String someField1) {
this.someField1 = someField1;
}
public String getSomeField2() {
return someField2;
}
public void setSomeField2(String someField2) {
this.someField2 = someField2;
}
}
/**
* @author Mewes Kochheim
*/
@Document(indexName = "test-index-core-completion", type = "completion-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class CompletionEntity {
@Id private String id;
private String name;
@CompletionField(maxInputLength = 100) private Completion suggest;
private CompletionEntity() {}
public CompletionEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Completion getSuggest() {
return suggest;
}
public void setSuggest(Completion suggest) {
this.suggest = suggest;
}
}
/**
* @author Mewes Kochheim
*/
static class CompletionEntityBuilder {
private CompletionEntity result;
public CompletionEntityBuilder(String id) {
result = new CompletionEntity(id);
}
public CompletionEntityBuilder name(String name) {
result.setName(name);
return this;
}
public CompletionEntityBuilder suggest(String[] input) {
return suggest(input, null);
}
public CompletionEntityBuilder suggest(String[] input, Integer weight) {
Completion suggest = new Completion(input);
suggest.setWeight(weight);
result.setSuggest(suggest);
return this;
}
public CompletionEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}
/**
* @author Mewes Kochheim
*/
@Document(indexName = "test-index-annotated-completion", type = "annotated-completion-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class AnnotatedCompletionEntity {
@Id private String id;
private String name;
@CompletionField(maxInputLength = 100) private Completion suggest;
private AnnotatedCompletionEntity() {}
public AnnotatedCompletionEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Completion getSuggest() {
return suggest;
}
public void setSuggest(Completion suggest) {
this.suggest = suggest;
}
}
/**
* @author Franck Marchand
* @author Mohsin Husen
* @author Mewes Kochheim
*/
static class AnnotatedCompletionEntityBuilder {
private AnnotatedCompletionEntity result;
public AnnotatedCompletionEntityBuilder(String id) {
result = new AnnotatedCompletionEntity(id);
}
public AnnotatedCompletionEntityBuilder name(String name) {
result.setName(name);
return this;
}
public AnnotatedCompletionEntityBuilder suggest(String[] input) {
return suggest(input, null);
}
public AnnotatedCompletionEntityBuilder suggest(String[] input, Integer weight) {
Completion suggest = new Completion(input);
suggest.setWeight(weight);
result.setSuggest(suggest);
return this;
}
public AnnotatedCompletionEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}
}

View File

@ -15,6 +15,14 @@
*/
package org.springframework.data.elasticsearch.core.completion;
import static org.assertj.core.api.Assertions.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.ToXContent;
@ -24,40 +32,33 @@ import org.elasticsearch.search.suggest.SuggestionBuilder;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.elasticsearch.search.suggest.completion.context.CategoryQueryContext;
import org.elasticsearch.search.suggest.completion.context.ContextMapping;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.CompletionContext;
import org.springframework.data.elasticsearch.annotations.CompletionField;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.entities.NonDocumentEntity;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/**
* @author Robert Gruendler
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class ElasticsearchTemplateCompletionWithContextsTests {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
private void loadContextCompletionObjectEntities() {
elasticsearchTemplate.deleteIndex(ContextCompletionEntity.class);
elasticsearchTemplate.createIndex(ContextCompletionEntity.class);
elasticsearchTemplate.refresh(ContextCompletionEntity.class);
elasticsearchTemplate.putMapping(ContextCompletionEntity.class);
IndexInitializer.init(elasticsearchTemplate, ContextCompletionEntity.class);
NonDocumentEntity nonDocumentEntity = new NonDocumentEntity();
nonDocumentEntity.setSomeField1("foo");
@ -67,19 +68,23 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
Map<String, List<String>> context1 = new HashMap<>();
context1.put(ContextCompletionEntity.LANGUAGE_CATEGORY, Arrays.asList("java", "elastic"));
indexQueries.add(new ContextCompletionEntityBuilder("1").name("Rizwan Idrees").suggest(new String[]{"Rizwan Idrees"}, context1).buildIndex());
indexQueries.add(new ContextCompletionEntityBuilder("1").name("Rizwan Idrees")
.suggest(new String[] { "Rizwan Idrees" }, context1).buildIndex());
Map<String, List<String>> context2 = new HashMap<>();
context2.put(ContextCompletionEntity.LANGUAGE_CATEGORY, Arrays.asList("kotlin", "mongo"));
indexQueries.add(new ContextCompletionEntityBuilder("2").name("Franck Marchand").suggest(new String[]{"Franck", "Marchand"}, context2).buildIndex());
indexQueries.add(new ContextCompletionEntityBuilder("2").name("Franck Marchand")
.suggest(new String[] { "Franck", "Marchand" }, context2).buildIndex());
Map<String, List<String>> context3 = new HashMap<>();
context3.put(ContextCompletionEntity.LANGUAGE_CATEGORY, Arrays.asList("kotlin", "elastic"));
indexQueries.add(new ContextCompletionEntityBuilder("3").name("Mohsin Husen").suggest(new String[]{"Mohsin", "Husen"}, context3).buildIndex());
indexQueries.add(new ContextCompletionEntityBuilder("3").name("Mohsin Husen")
.suggest(new String[] { "Mohsin", "Husen" }, context3).buildIndex());
Map<String, List<String>> context4 = new HashMap<>();
context4.put(ContextCompletionEntity.LANGUAGE_CATEGORY, Arrays.asList("java", "kotlin", "redis"));
indexQueries.add(new ContextCompletionEntityBuilder("4").name("Artur Konczak").suggest(new String[]{"Artur", "Konczak"}, context4).buildIndex());
indexQueries.add(new ContextCompletionEntityBuilder("4").name("Artur Konczak")
.suggest(new String[] { "Artur", "Konczak" }, context4).buildIndex());
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(ContextCompletionEntity.class);
@ -87,19 +92,22 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
@Test
public void shouldPutMappingForGivenEntity() throws Exception {
//given
Class entity = ContextCompletionEntity.class;
// given
Class<?> entity = ContextCompletionEntity.class;
elasticsearchTemplate.createIndex(entity);
//when
assertThat(elasticsearchTemplate.putMapping(entity), is(true));
// when
assertThat(elasticsearchTemplate.putMapping(entity)).isTrue();
}
@Test // DATAES-536
public void shouldFindSuggestionsForGivenCriteriaQueryUsingContextCompletionEntityOfMongo() {
//given
// given
loadContextCompletionObjectEntities();
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO);
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m",
Fuzziness.AUTO);
Map<String, List<? extends ToXContent>> contextMap = new HashMap<>();
List<CategoryQueryContext> contexts = new ArrayList<>(1);
@ -112,22 +120,26 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
((CompletionSuggestionBuilder) completionSuggestionFuzzyBuilder).contexts(contextMap);
//when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), ContextCompletionEntity.class);
assertNotNull(suggestResponse.getSuggest());
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder),
ContextCompletionEntity.class);
assertThat(suggestResponse.getSuggest()).isNotNull();
CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest");
List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getEntries().get(0).getOptions();
//then
assertThat(options.size(), is(1));
assertThat(options.get(0).getText().string(), isOneOf("Marchand"));
// then
assertThat(options).hasSize(1);
assertThat(options.get(0).getText().string()).isEqualTo("Marchand");
}
@Test // DATAES-536
public void shouldFindSuggestionsForGivenCriteriaQueryUsingContextCompletionEntityOfElastic() {
//given
// given
loadContextCompletionObjectEntities();
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO);
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m",
Fuzziness.AUTO);
Map<String, List<? extends ToXContent>> contextMap = new HashMap<>();
List<CategoryQueryContext> contexts = new ArrayList<>(1);
@ -140,22 +152,26 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
((CompletionSuggestionBuilder) completionSuggestionFuzzyBuilder).contexts(contextMap);
//when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), ContextCompletionEntity.class);
assertNotNull(suggestResponse.getSuggest());
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder),
ContextCompletionEntity.class);
assertThat(suggestResponse.getSuggest()).isNotNull();
CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest");
List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getEntries().get(0).getOptions();
//then
assertThat(options.size(), is(1));
assertThat(options.get(0).getText().string(), isOneOf( "Mohsin"));
// then
assertThat(options).hasSize(1);
assertThat(options.get(0).getText().string()).isEqualTo("Mohsin");
}
@Test // DATAES-536
public void shouldFindSuggestionsForGivenCriteriaQueryUsingContextCompletionEntityOfKotlin() {
//given
// given
loadContextCompletionObjectEntities();
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m", Fuzziness.AUTO);
SuggestionBuilder completionSuggestionFuzzyBuilder = SuggestBuilders.completionSuggestion("suggest").prefix("m",
Fuzziness.AUTO);
Map<String, List<? extends ToXContent>> contextMap = new HashMap<>();
List<CategoryQueryContext> contexts = new ArrayList<>(1);
@ -168,15 +184,127 @@ public class ElasticsearchTemplateCompletionWithContextsTests {
((CompletionSuggestionBuilder) completionSuggestionFuzzyBuilder).contexts(contextMap);
//when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder), ContextCompletionEntity.class);
assertNotNull(suggestResponse.getSuggest());
// when
final SearchResponse suggestResponse = elasticsearchTemplate.suggest(
new SuggestBuilder().addSuggestion("test-suggest", completionSuggestionFuzzyBuilder),
ContextCompletionEntity.class);
assertThat(suggestResponse.getSuggest()).isNotNull();
CompletionSuggestion completionSuggestion = suggestResponse.getSuggest().getSuggestion("test-suggest");
List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getEntries().get(0).getOptions();
//then
assertThat(options.size(), is(2));
assertThat(options.get(0).getText().string(), isOneOf("Marchand", "Mohsin"));
assertThat(options.get(1).getText().string(), isOneOf("Marchand", "Mohsin"));
// then
assertThat(options).hasSize(2);
assertThat(options.get(0).getText().string()).isIn("Marchand", "Mohsin");
assertThat(options.get(1).getText().string()).isIn("Marchand", "Mohsin");
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
static class NonDocumentEntity {
@Id private String someId;
private String someField1;
private String someField2;
public String getSomeField1() {
return someField1;
}
public void setSomeField1(String someField1) {
this.someField1 = someField1;
}
public String getSomeField2() {
return someField2;
}
public void setSomeField2(String someField2) {
this.someField2 = someField2;
}
}
/**
* @author Mewes Kochheim
* @author Robert Gruendler
*/
@Document(indexName = "test-index-context-completion", type = "context-completion-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class ContextCompletionEntity {
public static final String LANGUAGE_CATEGORY = "language";
@Id private String id;
private String name;
@CompletionField(maxInputLength = 100, contexts = {
@CompletionContext(name = LANGUAGE_CATEGORY, type = ContextMapping.Type.CATEGORY) }) private Completion suggest;
private ContextCompletionEntity() {}
public ContextCompletionEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Completion getSuggest() {
return suggest;
}
public void setSuggest(Completion suggest) {
this.suggest = suggest;
}
}
/**
* @author Robert Gruendler
*/
static class ContextCompletionEntityBuilder {
private ContextCompletionEntity result;
public ContextCompletionEntityBuilder(String id) {
result = new ContextCompletionEntity(id);
}
public ContextCompletionEntityBuilder name(String name) {
result.setName(name);
return this;
}
public ContextCompletionEntityBuilder suggest(String[] input, Map<String, List<String>> contexts) {
Completion suggest = new Completion(input);
suggest.setContexts(contexts);
result.setSuggest(suggest);
return this;
}
public ContextCompletionEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}
}

View File

@ -15,8 +15,7 @@
*/
package org.springframework.data.elasticsearch.core.convert;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import org.junit.Test;
import org.springframework.core.convert.ConversionService;
@ -26,32 +25,40 @@ import org.springframework.data.mapping.context.MappingContext;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Peter-Josef Meisch
*/
public class MappingElasticsearchConverterTests {
@Test(expected = IllegalArgumentException.class)
public void shouldFailToInitializeGivenMappingContextIsNull() {
// given
new MappingElasticsearchConverter(null);
}
@Test
public void shouldReturnMappingContextWithWhichItWasInitialized() {
// given
MappingContext mappingContext = new SimpleElasticsearchMappingContext();
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(mappingContext);
// then
assertThat(converter.getMappingContext(), is(notNullValue()));
assertThat(converter.getMappingContext(), is(sameInstance(mappingContext)));
assertThat(converter.getMappingContext()).isNotNull();
assertThat(converter.getMappingContext()).isSameAs(mappingContext);
}
@Test
public void shouldReturnDefaultConversionService() {
// given
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext());
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(
new SimpleElasticsearchMappingContext());
// when
ConversionService conversionService = converter.getConversionService();
// then
assertThat(conversionService, is(notNullValue()));
assertThat(conversionService).isNotNull();
}
}

View File

@ -1,111 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet;
import static org.springframework.data.elasticsearch.annotations.FieldType.Integer;
import static org.springframework.data.elasticsearch.annotations.FieldType.Text;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.*;
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
@Document(indexName = "test-index-articles", type = "article", shards = 1, replicas = 0, refreshInterval = "-1")
public class ArticleEntity {
@Id
private String id;
private String title;
@Field(type = Text, fielddata = true)
private String subject;
@MultiField(
mainField = @Field(type = Text),
otherFields = {
@InnerField(suffix = "untouched", type = Text, store = true, fielddata = true, analyzer = "keyword"),
@InnerField(suffix = "sort", type = Text, store = true, analyzer = "keyword")
}
)
private List<String> authors = new ArrayList<>();
@Field(type = Integer, store = true)
private List<Integer> publishedYears = new ArrayList<>();
private int score;
private ArticleEntity() {
}
public ArticleEntity(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public List<Integer> getPublishedYears() {
return publishedYears;
}
public void setPublishedYears(List<Integer> publishedYears) {
this.publishedYears = publishedYears;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}

View File

@ -1,69 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
public class ArticleEntityBuilder {
private ArticleEntity result;
public ArticleEntityBuilder(String id) {
result = new ArticleEntity(id);
}
public ArticleEntityBuilder title(String title) {
result.setTitle(title);
return this;
}
public ArticleEntityBuilder subject(String subject) {
result.setSubject(subject);
return this;
}
public ArticleEntityBuilder addAuthor(String author) {
result.getAuthors().add(author);
return this;
}
public ArticleEntityBuilder addPublishedYear(Integer year) {
result.getPublishedYears().add(year);
return this;
}
public ArticleEntityBuilder score(int score) {
result.setScore(score);
return this;
}
public ArticleEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}

View File

@ -16,10 +16,22 @@
package org.springframework.data.elasticsearch.core.facet;
import static org.assertj.core.api.Assertions.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.FacetedPage;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
@ -38,19 +50,17 @@ import org.springframework.data.elasticsearch.core.facet.result.TermResult;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Jonathan Yan
* @author Artur Konczak
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class ElasticsearchTemplateFacetTests {
@ -63,20 +73,22 @@ public class ElasticsearchTemplateFacetTests {
private static final int YEAR_2001 = 2001;
private static final int YEAR_2000 = 2000;
private static final String PUBLISHED_YEARS = "publishedYears";
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
elasticsearchTemplate.deleteIndex(ArticleEntity.class);
elasticsearchTemplate.createIndex(ArticleEntity.class);
elasticsearchTemplate.putMapping(ArticleEntity.class);
elasticsearchTemplate.refresh(ArticleEntity.class);
IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex();
IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex();
IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex();
IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex();
IndexInitializer.init(elasticsearchTemplate, ArticleEntity.class);
IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").addAuthor(RIZWAN_IDREES)
.addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex();
IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").addAuthor(RIZWAN_IDREES)
.addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex();
IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").addAuthor(RIZWAN_IDREES)
.addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex();
IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").addAuthor(RIZWAN_IDREES)
.addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex();
elasticsearchTemplate.index(article1);
elasticsearchTemplate.index(article2);
@ -90,32 +102,34 @@ public class ElasticsearchTemplateFacetTests {
// given
String facetName = "fauthors";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").build()).build();
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").build()).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4l));
assertThat(term.getTerm()).isEqualTo(RIZWAN_IDREES);
assertThat(term.getCount()).isEqualTo(4);
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK);
assertThat(term.getCount()).isEqualTo(3);
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN);
assertThat(term.getCount()).isEqualTo(2);
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1l));
assertThat(term.getTerm()).isEqualTo(JONATHAN_YAN);
assertThat(term.getCount()).isEqualTo(1);
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
assertThat(facet.getTotal()).isEqualTo(4);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(0);
}
@Test
@ -124,56 +138,63 @@ public class ElasticsearchTemplateFacetTests {
// given
String facetName = "fauthors";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").build()).build();
.withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").build())
.build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4l));
assertThat(term.getTerm()).isEqualTo(RIZWAN_IDREES);
assertThat(term.getCount()).isEqualTo(4);
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK);
assertThat(term.getCount()).isEqualTo(3);
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN);
assertThat(term.getCount()).isEqualTo(2);
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
assertThat(facet.getTotal()).isEqualTo(4);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(0);
}
@Test
public void shouldExcludeTermsFromFacetedAuthorsForGivenQuery() {
// given
String facetName = "fauthors";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").excludeTerms(RIZWAN_IDREES, ARTUR_KONCZAK).build()).build();
.withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched")
.excludeTerms(RIZWAN_IDREES, ARTUR_KONCZAK).build())
.build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(2));
assertThat(facet.getTerms()).hasSize(2);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN);
assertThat(term.getCount()).isEqualTo(2);
Term term1 = facet.getTerms().get(1);
assertThat(term1.getTerm(), is(JONATHAN_YAN));
assertThat(term1.getCount(), is(1l));
assertThat(term1.getTerm()).isEqualTo(JONATHAN_YAN);
assertThat(term1.getCount()).isEqualTo(1);
assertThat(facet.getTotal(), is(2l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
assertThat(facet.getTotal()).isEqualTo(2);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(0);
}
@Test
@ -183,31 +204,33 @@ public class ElasticsearchTemplateFacetTests {
String facetName = "fauthors";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").ascTerm().build()).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK);
assertThat(term.getCount()).isEqualTo(3);
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1l));
assertThat(term.getTerm()).isEqualTo(JONATHAN_YAN);
assertThat(term.getCount()).isEqualTo(1);
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN);
assertThat(term.getCount()).isEqualTo(2);
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4l));
assertThat(term.getTerm()).isEqualTo(RIZWAN_IDREES);
assertThat(term.getCount()).isEqualTo(4);
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
assertThat(facet.getTotal()).isEqualTo(4);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(0);
}
@Test
@ -217,31 +240,33 @@ public class ElasticsearchTemplateFacetTests {
String facetName = "fauthors";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").ascCount().build()).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1l));
assertThat(term.getTerm()).isEqualTo(JONATHAN_YAN);
assertThat(term.getCount()).isEqualTo(1);
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN);
assertThat(term.getCount()).isEqualTo(2);
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK);
assertThat(term.getCount()).isEqualTo(3);
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4l));
assertThat(term.getTerm()).isEqualTo(RIZWAN_IDREES);
assertThat(term.getCount()).isEqualTo(4);
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
assertThat(facet.getTotal()).isEqualTo(4);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(0);
}
@Test
@ -251,29 +276,31 @@ public class ElasticsearchTemplateFacetTests {
String facetName = "fyears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(facetName).fields("publishedYears").descCount().build()).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(equalTo(3)));
assertThat(facet.getTerms()).hasSize(3);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Long.toString(YEAR_2000)));
assertThat(term.getCount(), is(3l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2000));
assertThat(term.getCount()).isEqualTo(3);
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Long.toString(YEAR_2001)));
assertThat(term.getCount(), is(2l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2001));
assertThat(term.getCount()).isEqualTo(2);
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Long.toString(YEAR_2002)));
assertThat(term.getCount(), is(1l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2002));
assertThat(term.getCount()).isEqualTo(1);
assertThat(facet.getTotal(), is(3l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
assertThat(facet.getTotal()).isEqualTo(3);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(0);
}
@Test
@ -282,79 +309,86 @@ public class ElasticsearchTemplateFacetTests {
// given
String facetName = "fyears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("publishedYears").descCount().build()).build();
.withFacet(
new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("publishedYears").descCount().build())
.build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(equalTo(3)));
assertThat(facet.getTerms()).hasSize(3);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Long.toString(YEAR_2000)));
assertThat(term.getCount(), is(3l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2000));
assertThat(term.getCount()).isEqualTo(3);
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Long.toString(YEAR_2001)));
assertThat(term.getCount(), is(2l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2001));
assertThat(term.getCount()).isEqualTo(2);
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Long.toString(YEAR_2002)));
assertThat(term.getCount(), is(1l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2002));
assertThat(term.getCount()).isEqualTo(1);
assertThat(facet.getTotal(), is(3l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
assertThat(facet.getTotal()).isEqualTo(3);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(0);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExeptionsForMultiFieldFacet() {
// given
String facetName = "fyears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(facetName).fields("publishedYears", "authors.untouched").ascTerm().build()).build();
.withFacet(
new TermFacetRequestBuilder(facetName).fields("publishedYears", "authors.untouched").ascTerm().build())
.build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(equalTo(7)));
assertThat(facet.getTerms()).hasSize(7);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Long.toString(YEAR_2000)));
assertThat(term.getCount(), is(3l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2000));
assertThat(term.getCount()).isEqualTo(3);
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Long.toString(YEAR_2001)));
assertThat(term.getCount(), is(2l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2001));
assertThat(term.getCount()).isEqualTo(2);
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Long.toString(YEAR_2002)));
assertThat(term.getCount(), is(1l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2002));
assertThat(term.getCount()).isEqualTo(1);
term = facet.getTerms().get(3);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK);
assertThat(term.getCount()).isEqualTo(3);
term = facet.getTerms().get(4);
assertThat(term.getTerm(), is(JONATHAN_YAN));
assertThat(term.getCount(), is(1l));
assertThat(term.getTerm()).isEqualTo(JONATHAN_YAN);
assertThat(term.getCount()).isEqualTo(1);
term = facet.getTerms().get(5);
assertThat(term.getTerm(), is(MOHSIN_HUSEN));
assertThat(term.getCount(), is(2l));
assertThat(term.getTerm()).isEqualTo(MOHSIN_HUSEN);
assertThat(term.getCount()).isEqualTo(2);
term = facet.getTerms().get(6);
assertThat(term.getTerm(), is(RIZWAN_IDREES));
assertThat(term.getCount(), is(4l));
assertThat(term.getTerm()).isEqualTo(RIZWAN_IDREES);
assertThat(term.getCount()).isEqualTo(4);
assertThat(facet.getTotal(), is(16l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(1l));
assertThat(facet.getTotal()).isEqualTo(16);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(1);
}
@Test
@ -365,51 +399,51 @@ public class ElasticsearchTemplateFacetTests {
String stringFacetName = "fyears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(numberFacetName).fields("publishedYears").ascTerm().build())
.withFacet(new TermFacetRequestBuilder(stringFacetName).fields("authors.untouched").ascTerm().build())
.build();
.withFacet(new TermFacetRequestBuilder(stringFacetName).fields("authors.untouched").ascTerm().build()).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult numberFacet = (TermResult) result.getFacet(numberFacetName);
assertThat(numberFacet.getTerms().size(), is(equalTo(3)));
assertThat(numberFacet.getTerms()).hasSize(3);
Term numberTerm = numberFacet.getTerms().get(0);
assertThat(numberTerm.getTerm(), is(Long.toString(YEAR_2000)));
assertThat(numberTerm.getCount(), is(3l));
assertThat(numberTerm.getTerm()).isEqualTo(Long.toString(YEAR_2000));
assertThat(numberTerm.getCount()).isEqualTo(3);
numberTerm = numberFacet.getTerms().get(1);
assertThat(numberTerm.getTerm(), is(Long.toString(YEAR_2001)));
assertThat(numberTerm.getCount(), is(2l));
assertThat(numberTerm.getTerm()).isEqualTo(Long.toString(YEAR_2001));
assertThat(numberTerm.getCount()).isEqualTo(2);
numberTerm = numberFacet.getTerms().get(2);
assertThat(numberTerm.getTerm(), is(Long.toString(YEAR_2002)));
assertThat(numberTerm.getCount(), is(1l));
assertThat(numberTerm.getTerm()).isEqualTo(Long.toString(YEAR_2002));
assertThat(numberTerm.getCount()).isEqualTo(1);
TermResult stringFacet = (TermResult) result.getFacet(stringFacetName);
Term stringTerm = stringFacet.getTerms().get(0);
assertThat(stringTerm.getTerm(), is(ARTUR_KONCZAK));
assertThat(stringTerm.getCount(), is(3l));
assertThat(stringTerm.getTerm()).isEqualTo(ARTUR_KONCZAK);
assertThat(stringTerm.getCount()).isEqualTo(3);
stringTerm = stringFacet.getTerms().get(1);
assertThat(stringTerm.getTerm(), is(JONATHAN_YAN));
assertThat(stringTerm.getCount(), is(1l));
assertThat(stringTerm.getTerm()).isEqualTo(JONATHAN_YAN);
assertThat(stringTerm.getCount()).isEqualTo(1);
stringTerm = stringFacet.getTerms().get(2);
assertThat(stringTerm.getTerm(), is(MOHSIN_HUSEN));
assertThat(stringTerm.getCount(), is(2l));
assertThat(stringTerm.getTerm()).isEqualTo(MOHSIN_HUSEN);
assertThat(stringTerm.getCount()).isEqualTo(2);
stringTerm = stringFacet.getTerms().get(3);
assertThat(stringTerm.getTerm(), is(RIZWAN_IDREES));
assertThat(stringTerm.getCount(), is(4l));
assertThat(stringTerm.getTerm()).isEqualTo(RIZWAN_IDREES);
assertThat(stringTerm.getCount()).isEqualTo(4);
assertThat(stringFacet.getTotal(), is(4l));
assertThat(stringFacet.getOther(), is(0l));
assertThat(stringFacet.getMissing(), is(0l));
assertThat(stringFacet.getTotal()).isEqualTo(4);
assertThat(stringFacet.getOther()).isEqualTo(0);
assertThat(stringFacet.getMissing()).isEqualTo(0);
}
@Test(expected = UnsupportedOperationException.class)
public void shouldThrowExceptionForNativeFacets() {
@ -417,202 +451,351 @@ public class ElasticsearchTemplateFacetTests {
String facetName = "fyears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new NativeFacetRequest()).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(equalTo(3)));
assertThat(facet.getTerms()).hasSize(3);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(Long.toString(YEAR_2000)));
assertThat(term.getCount(), is(3l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2000));
assertThat(term.getCount()).isEqualTo(3);
term = facet.getTerms().get(1);
assertThat(term.getTerm(), is(Long.toString(YEAR_2001)));
assertThat(term.getCount(), is(2l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2001));
assertThat(term.getCount()).isEqualTo(2);
term = facet.getTerms().get(2);
assertThat(term.getTerm(), is(Long.toString(YEAR_2002)));
assertThat(term.getCount(), is(1l));
assertThat(term.getTerm()).isEqualTo(Long.toString(YEAR_2002));
assertThat(term.getCount()).isEqualTo(1);
assertThat(facet.getTotal(), is(6l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(1l));
assertThat(facet.getTotal()).isEqualTo(6);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(1);
}
@Test
public void shouldFilterResultByRegexForGivenQuery() {
// given
String facetName = "regex_authors";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").regex("Art.*").build()).build();
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withFacet(
new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").regex("Art.*").build())
.build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(1));
assertThat(facet.getTerms()).hasSize(1);
Term term = facet.getTerms().get(0);
assertThat(term.getTerm(), is(ARTUR_KONCZAK));
assertThat(term.getCount(), is(3l));
assertThat(term.getTerm()).isEqualTo(ARTUR_KONCZAK);
assertThat(term.getCount()).isEqualTo(3);
assertThat(facet.getTotal(), is(1l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
assertThat(facet.getTotal()).isEqualTo(1);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(0);
}
@Test
public void shouldReturnAllTermsForGivenQuery() {
// given
// given
String facetName = "all_authors";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").allTerms().build()).build();
.withFacet(
new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").allTerms().build())
.build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
TermResult facet = (TermResult) result.getFacet(facetName);
assertThat(facet.getTerms().size(), is(4));
assertThat(facet.getTerms()).hasSize(4);
assertThat(facet.getTotal(), is(4l));
assertThat(facet.getOther(), is(0l));
assertThat(facet.getMissing(), is(0l));
assertThat(facet.getTotal()).isEqualTo(4);
assertThat(facet.getOther()).isEqualTo(0);
assertThat(facet.getMissing()).isEqualTo(0);
}
@Test
public void shouldReturnRangeFacetForGivenQuery() {
// given
String facetName = "rangeYears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(
new RangeFacetRequestBuilder(facetName).field(PUBLISHED_YEARS)
.to(YEAR_2000).range(YEAR_2000, YEAR_2002).from(YEAR_2002).build()
).build();
.withFacet(new RangeFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).to(YEAR_2000)
.range(YEAR_2000, YEAR_2002).from(YEAR_2002).build())
.build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
RangeResult facet = (RangeResult) result.getFacet(facetName);
assertThat(facet.getRanges().size(), is(equalTo(3)));
assertThat(facet.getRanges()).hasSize(3);
Range range = facet.getRanges().get(0);
assertThat(range.getFrom(), is(Double.NEGATIVE_INFINITY));
assertThat(range.getTo(), is((double) YEAR_2000));
assertThat(range.getCount(), is(0L));
assertThat(range.getTotal(), is(0.0));
assertThat(range.getFrom()).isEqualTo(Double.NEGATIVE_INFINITY);
assertThat(range.getTo()).isEqualTo((double) YEAR_2000);
assertThat(range.getCount()).isEqualTo(0);
assertThat(range.getTotal()).isEqualTo(0.0);
range = facet.getRanges().get(1);
assertThat(range.getFrom(), is((double) YEAR_2000));
assertThat(range.getTo(), is((double) YEAR_2002));
assertThat(range.getCount(), is(3L));
assertThat(range.getTotal(), is(12004.0));
assertThat(range.getFrom()).isEqualTo((double) YEAR_2000);
assertThat(range.getTo()).isEqualTo((double) YEAR_2002);
assertThat(range.getCount()).isEqualTo(3);
assertThat(range.getTotal()).isEqualTo(12004.0);
range = facet.getRanges().get(2);
assertThat(range.getFrom(), is((double) YEAR_2002));
assertThat(range.getTo(), is(Double.POSITIVE_INFINITY));
assertThat(range.getCount(), is(1L));
assertThat(range.getTotal(), is(6003.0));
assertThat(range.getFrom()).isEqualTo((double) YEAR_2002);
assertThat(range.getTo()).isEqualTo(Double.POSITIVE_INFINITY);
assertThat(range.getCount()).isEqualTo(1);
assertThat(range.getTotal()).isEqualTo(6003.0);
}
@Test
public void shouldReturnKeyValueRangeFacetForStringValuesInGivenQuery() {
// given
String facetName = "rangeScoreOverYears";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(
new RangeFacetRequestBuilder(facetName).fields(PUBLISHED_YEARS, "score")
.to(YEAR_2000).range(YEAR_2000, YEAR_2002).from(YEAR_2002).build()
).build();
.withFacet(new RangeFacetRequestBuilder(facetName).fields(PUBLISHED_YEARS, "score").to(YEAR_2000)
.range(YEAR_2000, YEAR_2002).from(YEAR_2002).build())
.build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
RangeResult facet = (RangeResult) result.getFacet(facetName);
assertThat(facet.getRanges().size(), is(equalTo(3)));
assertThat(facet.getRanges()).hasSize(3);
Range range = facet.getRanges().get(0);
assertThat(range.getFrom(), is(Double.NEGATIVE_INFINITY));
assertThat(range.getTo(), is((double) YEAR_2000));
assertThat(range.getCount(), is(0L));
assertThat(range.getTotal(), is(0.0));
assertThat(range.getFrom()).isEqualTo(Double.NEGATIVE_INFINITY);
assertThat(range.getTo()).isEqualTo((double) YEAR_2000);
assertThat(range.getCount()).isEqualTo(0);
assertThat(range.getTotal()).isEqualTo(0.0);
range = facet.getRanges().get(1);
assertThat(range.getFrom(), is((double) YEAR_2000));
assertThat(range.getTo(), is((double) YEAR_2002));
assertThat(range.getCount(), is(3L));
assertThat(range.getTotal(), is(90.0));
assertThat(range.getFrom()).isEqualTo((double) YEAR_2000);
assertThat(range.getTo()).isEqualTo((double) YEAR_2002);
assertThat(range.getCount()).isEqualTo(3);
assertThat(range.getTotal()).isEqualTo(90.0);
range = facet.getRanges().get(2);
assertThat(range.getFrom(), is((double) YEAR_2002));
assertThat(range.getTo(), is(Double.POSITIVE_INFINITY));
assertThat(range.getCount(), is(1L));
assertThat(range.getTotal(), is(40.0));
assertThat(range.getFrom()).isEqualTo((double) YEAR_2002);
assertThat(range.getTo()).isEqualTo(Double.POSITIVE_INFINITY);
assertThat(range.getCount()).isEqualTo(1);
assertThat(range.getTotal()).isEqualTo(40.0);
}
@Test
public void shouldReturnStatisticalFacetForGivenQuery() {
// given
String facetName = "statPublishedYear";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new StatisticalFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).build()
).build();
.withFacet(new StatisticalFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).build()).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
StatisticalResult facet = (StatisticalResult) result.getFacet(facetName);
assertThat(facet.getCount(), is(equalTo(6L)));
assertThat(facet.getMax(), is(equalTo(2002.0)));
assertThat(facet.getMin(), is(equalTo(2000.0)));
assertThat(facet.getCount()).isEqualTo(6);
assertThat(facet.getMax()).isEqualTo(2002.0);
assertThat(facet.getMin()).isEqualTo(2000.0);
}
@Test
public void shouldReturnHistogramFacetForGivenQuery() {
// given
String facetName = "numberPublicationPerYear";
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withFacet(new HistogramFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).interval(1).build()
).build();
.withFacet(new HistogramFacetRequestBuilder(facetName).field(PUBLISHED_YEARS).interval(1).build()).build();
// when
FacetedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
// then
assertThat(result.getNumberOfElements(), is(equalTo(4)));
assertThat(result.getNumberOfElements()).isEqualTo(4);
HistogramResult facet = (HistogramResult) result.getFacet(facetName);
assertThat(facet.getIntervalUnit().size(), is(equalTo(3)));
assertThat(facet.getIntervalUnit()).hasSize(3);
IntervalUnit unit = facet.getIntervalUnit().get(0);
assertThat(unit.getKey(), is(Long.valueOf(YEAR_2000)));
assertThat(unit.getCount(), is(3L));
assertThat(unit.getKey()).isEqualTo(Long.valueOf(YEAR_2000));
assertThat(unit.getCount()).isEqualTo(3);
unit = facet.getIntervalUnit().get(1);
assertThat(unit.getKey(), is(Long.valueOf(YEAR_2001)));
assertThat(unit.getCount(), is(2L));
assertThat(unit.getKey()).isEqualTo(Long.valueOf(YEAR_2001));
assertThat(unit.getCount()).isEqualTo(2);
unit = facet.getIntervalUnit().get(2);
assertThat(unit.getKey(), is(Long.valueOf(YEAR_2002)));
assertThat(unit.getCount(), is(1L));
assertThat(unit.getKey()).isEqualTo(Long.valueOf(YEAR_2002));
assertThat(unit.getCount()).isEqualTo(1);
}
@Test
public void shouldNotThrowExceptionForNoFacets()
{
public void shouldNotThrowExceptionForNoFacets() {
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
AggregatedPage<ArticleEntity> result = elasticsearchTemplate.queryForPage(searchQuery, ArticleEntity.class);
assertThat(result.hasFacets(), is(false));
assertThat(result.hasFacets()).isEqualTo(false);
}
}
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
@Document(indexName = "test-index-articles-core-facet", type = "article", shards = 1, replicas = 0, refreshInterval = "-1")
static class ArticleEntity {
@Id private String id;
private String title;
@Field(type = FieldType.Text, fielddata = true) private String subject;
@MultiField(mainField = @Field(type = FieldType.Text),
otherFields = {
@InnerField(suffix = "untouched", type = FieldType.Text, store = true, fielddata = true,
analyzer = "keyword"),
@InnerField(suffix = "sort", type = FieldType.Text, store = true,
analyzer = "keyword") }) private List<String> authors = new ArrayList<>();
@Field(type = FieldType.Integer, store = true) private List<Integer> publishedYears = new ArrayList<>();
private int score;
private ArticleEntity() {
}
public ArticleEntity(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public List<Integer> getPublishedYears() {
return publishedYears;
}
public void setPublishedYears(List<Integer> publishedYears) {
this.publishedYears = publishedYears;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
static class ArticleEntityBuilder {
private ArticleEntity result;
public ArticleEntityBuilder(String id) {
result = new ArticleEntity(id);
}
public ArticleEntityBuilder title(String title) {
result.setTitle(title);
return this;
}
public ArticleEntityBuilder subject(String subject) {
result.setSubject(subject);
return this;
}
public ArticleEntityBuilder addAuthor(String author) {
result.getAuthors().add(author);
return this;
}
public ArticleEntityBuilder addPublishedYear(Integer year) {
result.getPublishedYears().add(year);
return this;
}
public ArticleEntityBuilder score(int score) {
result.setScore(score);
return this;
}
public ArticleEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}
}

View File

@ -1,102 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
@Document(indexName = "test-index-log", type = "test-log-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class LogEntity {
private static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
@Id
private String id;
private String action;
private long sequenceCode;
@Field(type = Ip)
private String ip;
@Field(type = Date)
private Date date;
private LogEntity() {
}
public LogEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAction() {
return action;
}
public String toString() {
return new StringBuffer().append("{id:").append(id).append(",action:").append(action).append(",code:").append(sequenceCode).append(",date:").append(format.format(date)).append("}").toString();
}
public void setAction(String action) {
this.action = action;
}
public long getSequenceCode() {
return sequenceCode;
}
public void setSequenceCode(long sequenceCode) {
this.sequenceCode = sequenceCode;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}

View File

@ -1,67 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.facet;
import java.util.Date;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
/**
* Simple type to test facets
*
* @author Artur Konczak
* @author Mohsin Husen
*/
public class LogEntityBuilder {
private LogEntity result;
public LogEntityBuilder(String id) {
result = new LogEntity(id);
}
public LogEntityBuilder action(String action) {
result.setAction(action);
return this;
}
public LogEntityBuilder code(long sequenceCode) {
result.setSequenceCode(sequenceCode);
return this;
}
public LogEntityBuilder date(Date date) {
result.setDate(date);
return this;
}
public LogEntityBuilder ip(String ip) {
result.setIp(ip);
return this;
}
public LogEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}

View File

@ -1,64 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.geo;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author Franck Marchand
* @author Mohsin Husen
*/
@Document(indexName = "test-index-author-marker", type = "geo-class-point-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class AuthorMarkerEntity {
@Id
private String id;
private String name;
private GeoPoint location;
private AuthorMarkerEntity() {
}
public AuthorMarkerEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GeoPoint getLocation() {
return location;
}
public void setLocation(GeoPoint location) {
this.location = location;
}
}

View File

@ -1,53 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.geo;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
/**
* @author Franck Marchand
* @author Mohsin Husen
*/
public class AuthorMarkerEntityBuilder {
private AuthorMarkerEntity result;
public AuthorMarkerEntityBuilder(String id) {
result = new AuthorMarkerEntity(id);
}
public AuthorMarkerEntityBuilder name(String name) {
result.setName(name);
return this;
}
public AuthorMarkerEntityBuilder location(double latitude, double longitude) {
result.setLocation(new GeoPoint(latitude, longitude));
return this;
}
public AuthorMarkerEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}

View File

@ -15,55 +15,66 @@
*/
package org.springframework.data.elasticsearch.core.geo;
import static org.assertj.core.api.Assertions.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
import org.elasticsearch.common.geo.GeoHashUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.data.geo.Point;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Franck Marchand
* @author Artur Konczak
* @author Peter-Josef Meisch
*
* Basic info:
* latitude - horizontal lines (equator = 0.0, values -90.0 to 90.0)
* longitude - vertical lines (Greenwich = 0.0, values -180 to 180)
* London [lat,lon] = [51.50985,-0.118082] - geohash = gcpvj3448
* Bouding Box for London = (bbox=-0.489,51.28,0.236,51.686)
* bbox = left,bottom,right,top
* bbox = min Longitude , min Latitude , max Longitude , max Latitude
*
* Basic info: latitude - horizontal lines (equator = 0.0, values -90.0 to 90.0) longitude -
* vertical lines (Greenwich = 0.0, values -180 to 180) London [lat,lon] = [51.50985,-0.118082] - geohash =
* gcpvj3448 Bouding Box for London = (bbox=-0.489,51.28,0.236,51.686) bbox = left,bottom,right,top bbox = min
* Longitude , min Latitude , max Longitude , max Latitude
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class ElasticsearchTemplateGeoTests {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, AuthorMarkerEntity.class);
IndexInitializer.init(elasticsearchTemplate, LocationMarkerEntity.class);
}
private void loadClassBaseEntities() {
elasticsearchTemplate.deleteIndex(AuthorMarkerEntity.class);
elasticsearchTemplate.createIndex(AuthorMarkerEntity.class);
elasticsearchTemplate.putMapping(AuthorMarkerEntity.class);
elasticsearchTemplate.refresh(AuthorMarkerEntity.class);
List<IndexQuery> indexQueries = new ArrayList<>();
indexQueries.add(new AuthorMarkerEntityBuilder("1").name("Franck Marchand").location(45.7806d, 3.0875d).buildIndex());
indexQueries
.add(new AuthorMarkerEntityBuilder("1").name("Franck Marchand").location(45.7806d, 3.0875d).buildIndex());
indexQueries.add(new AuthorMarkerEntityBuilder("2").name("Mohsin Husen").location(51.5171d, 0.1062d).buildIndex());
indexQueries.add(new AuthorMarkerEntityBuilder("3").name("Rizwan Idrees").location(51.5171d, 0.1062d).buildIndex());
elasticsearchTemplate.bulkIndex(indexQueries);
@ -71,33 +82,29 @@ public class ElasticsearchTemplateGeoTests {
}
private void loadAnnotationBaseEntities() {
elasticsearchTemplate.deleteIndex(LocationMarkerEntity.class);
elasticsearchTemplate.createIndex(LocationMarkerEntity.class);
elasticsearchTemplate.putMapping(LocationMarkerEntity.class);
elasticsearchTemplate.refresh(LocationMarkerEntity.class);
List<IndexQuery> indexQueries = new ArrayList<>();
double[] lonLatArray = {0.100000, 51.000000};
double[] lonLatArray = { 0.100000, 51.000000 };
String latLonString = "51.000000, 0.100000";
String geohash = "u10j46mkfekr";
GeoHashUtils.stringEncode(0.100000,51.000000);
LocationMarkerEntity location1 = LocationMarkerEntity.builder()
.id("1").name("Artur Konczak")
.locationAsString(latLonString)
.locationAsArray(lonLatArray)
GeoHashUtils.stringEncode(0.100000, 51.000000);
LocationMarkerEntity location1 = LocationMarkerEntity.builder() //
.id("1").name("Artur Konczak") //
.locationAsString(latLonString) //
.locationAsArray(lonLatArray) //
.locationAsGeoHash(geohash)
.build();
LocationMarkerEntity location2 = LocationMarkerEntity.builder()
.id("2").name("Mohsin Husen")
.locationAsString(geohash.substring(0, 8))
.locationAsArray(lonLatArray)
.locationAsGeoHash(geohash.substring(0, 8))
LocationMarkerEntity location2 = LocationMarkerEntity.builder() //
.id("2").name("Mohsin Husen") //
.locationAsString(geohash.substring(0, 8)) //
.locationAsArray(lonLatArray) //
.locationAsGeoHash(geohash.substring(0, 8)) //
.build();
LocationMarkerEntity location3 = LocationMarkerEntity.builder()
.id("3").name("Rizwan Idrees")
.locationAsString(geohash)
.locationAsArray(lonLatArray)
.locationAsGeoHash(geohash)
LocationMarkerEntity location3 = LocationMarkerEntity.builder() //
.id("3").name("Rizwan Idrees") //
.locationAsString(geohash) //
.locationAsArray(lonLatArray) //
.locationAsGeoHash(geohash) //
.build();
indexQueries.add(buildIndex(location1));
indexQueries.add(buildIndex(location2));
@ -109,197 +116,237 @@ public class ElasticsearchTemplateGeoTests {
@Test
public void shouldPutMappingForGivenEntityWithGeoLocation() throws Exception {
//given
Class entity = AuthorMarkerEntity.class;
// given
Class<?> entity = AuthorMarkerEntity.class;
elasticsearchTemplate.createIndex(entity);
//when
assertThat(elasticsearchTemplate.putMapping(entity), is(true));
// when
assertThat(elasticsearchTemplate.putMapping(entity)).isTrue();
}
@Test
public void shouldFindAuthorMarkersInRangeForGivenCriteriaQuery() {
//given
// given
loadClassBaseEntities();
CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery(
new Criteria("location").within(new GeoPoint(45.7806d, 3.0875d), "20km"));
//when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, AuthorMarkerEntity.class);
//then
assertThat(geoAuthorsForGeoCriteria.size(), is(1));
assertEquals("Franck Marchand", geoAuthorsForGeoCriteria.get(0).getName());
// when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery,
AuthorMarkerEntity.class);
// then
assertThat(geoAuthorsForGeoCriteria).hasSize(1);
assertThat(geoAuthorsForGeoCriteria.get(0).getName()).isEqualTo("Franck Marchand");
}
@Test
public void shouldFindSelectedAuthorMarkerInRangeForGivenCriteriaQuery() {
//given
// given
loadClassBaseEntities();
CriteriaQuery geoLocationCriteriaQuery2 = new CriteriaQuery(
new Criteria("name").is("Mohsin Husen").and("location").within(new GeoPoint(51.5171d, 0.1062d), "20km"));
//when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria2 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery2, AuthorMarkerEntity.class);
//then
assertThat(geoAuthorsForGeoCriteria2.size(), is(1));
assertEquals("Mohsin Husen", geoAuthorsForGeoCriteria2.get(0).getName());
// when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria2 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery2,
AuthorMarkerEntity.class);
// then
assertThat(geoAuthorsForGeoCriteria2).hasSize(1);
assertThat(geoAuthorsForGeoCriteria2.get(0).getName()).isEqualTo("Mohsin Husen");
}
@Test
public void shouldFindStringAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() {
//given
// given
loadAnnotationBaseEntities();
CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery(
new Criteria("locationAsString").within(new GeoPoint(51.000000, 0.100000), "1km"));
//when
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, LocationMarkerEntity.class);
// when
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery,
LocationMarkerEntity.class);
//then
assertThat(geoAuthorsForGeoCriteria.size(), is(1));
// then
assertThat(geoAuthorsForGeoCriteria).hasSize(1);
}
@Test
public void shouldFindDoubleAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() {
//given
// given
loadAnnotationBaseEntities();
CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery(
new Criteria("locationAsArray").within(new GeoPoint(51.001000, 0.10100), "1km"));
//when
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, LocationMarkerEntity.class);
//then
assertThat(geoAuthorsForGeoCriteria.size(), is(3));
// when
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery,
LocationMarkerEntity.class);
// then
assertThat(geoAuthorsForGeoCriteria).hasSize(3);
}
@Test
public void shouldFindAnnotatedGeoMarkersInRangeForGivenCriteriaQuery() {
//given
// given
loadAnnotationBaseEntities();
CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery(
new Criteria("locationAsArray").within("51.001000, 0.10100", "1km"));
//when
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, LocationMarkerEntity.class);
// when
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery,
LocationMarkerEntity.class);
//then
assertThat(geoAuthorsForGeoCriteria.size(), is(3));
// then
assertThat(geoAuthorsForGeoCriteria).hasSize(3);
}
@Test
public void shouldFindAnnotatedGeoMarkersInRangeForGivenCriteriaQueryUsingGeohashLocation() {
//given
loadAnnotationBaseEntities();
CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery(
new Criteria("locationAsArray").within("u1044", "3km"));
//when
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery, LocationMarkerEntity.class);
//then
assertThat(geoAuthorsForGeoCriteria.size(), is(3));
// given
loadAnnotationBaseEntities();
CriteriaQuery geoLocationCriteriaQuery = new CriteriaQuery(new Criteria("locationAsArray").within("u1044", "3km"));
// when
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery,
LocationMarkerEntity.class);
// then
assertThat(geoAuthorsForGeoCriteria).hasSize(3);
}
@Test
public void shouldFindAllMarkersForNativeSearchQuery() {
//Given
// given
loadAnnotationBaseEntities();
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsArray").setCorners(52, -1, 50, 1));
//When
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(queryBuilder.build(), LocationMarkerEntity.class);
//Then
assertThat(geoAuthorsForGeoCriteria.size(), is(3));
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
.withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsArray").setCorners(52, -1, 50, 1));
// when
List<LocationMarkerEntity> geoAuthorsForGeoCriteria = elasticsearchTemplate.queryForList(queryBuilder.build(),
LocationMarkerEntity.class);
// then
assertThat(geoAuthorsForGeoCriteria).hasSize(3);
}
@Test
public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoBox() {
//given
// given
loadClassBaseEntities();
CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery(
new Criteria("location").boundedBy(
new GeoBox(new GeoPoint(53.5171d, 0),
new GeoPoint(49.5171d, 0.2062d))
)
);
//when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class);
new Criteria("location").boundedBy(new GeoBox(new GeoPoint(53.5171d, 0), new GeoPoint(49.5171d, 0.2062d))));
//then
assertThat(geoAuthorsForGeoCriteria3.size(), is(2));
assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees"))));
// when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3,
AuthorMarkerEntity.class);
// then
assertThat(geoAuthorsForGeoCriteria3).hasSize(2);
assertThat(geoAuthorsForGeoCriteria3.stream().map(AuthorMarkerEntity::getName))
.containsExactlyInAnyOrder("Mohsin Husen", "Rizwan Idrees");
}
@Test
public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeohash() {
//given
loadClassBaseEntities();
CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery(
new Criteria("location").boundedBy(GeoHashUtils.stringEncode(0, 53.5171d), GeoHashUtils.stringEncode(0.2062d, 49.5171d)));
//when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class);
//then
assertThat(geoAuthorsForGeoCriteria3.size(), is(2));
assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees"))));
// given
loadClassBaseEntities();
CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery(new Criteria("location")
.boundedBy(GeoHashUtils.stringEncode(0, 53.5171d), GeoHashUtils.stringEncode(0.2062d, 49.5171d)));
// when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3,
AuthorMarkerEntity.class);
// then
assertThat(geoAuthorsForGeoCriteria3).hasSize(2);
assertThat(geoAuthorsForGeoCriteria3.stream().map(AuthorMarkerEntity::getName))
.containsExactlyInAnyOrder("Mohsin Husen", "Rizwan Idrees");
}
@Test
public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingGeoPoints() {
//given
// given
loadClassBaseEntities();
CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery(
new Criteria("location").boundedBy(
new GeoPoint(53.5171d, 0),
new GeoPoint(49.5171d, 0.2062d))
);
//when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class);
new Criteria("location").boundedBy(new GeoPoint(53.5171d, 0), new GeoPoint(49.5171d, 0.2062d)));
//then
assertThat(geoAuthorsForGeoCriteria3.size(), is(2));
assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees"))));
// when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3,
AuthorMarkerEntity.class);
// then
assertThat(geoAuthorsForGeoCriteria3).hasSize(2);
assertThat(geoAuthorsForGeoCriteria3.stream().map(AuthorMarkerEntity::getName))
.containsExactlyInAnyOrder("Mohsin Husen", "Rizwan Idrees");
}
@Test
public void shouldFindAuthorMarkersInBoxForGivenCriteriaQueryUsingPoints() {
//given
// given
loadClassBaseEntities();
CriteriaQuery geoLocationCriteriaQuery3 = new CriteriaQuery(
new Criteria("location").boundedBy(
new Point(53.5171d, 0),
new Point(49.5171d, 0.2062d ))
);
//when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3, AuthorMarkerEntity.class);
new Criteria("location").boundedBy(new Point(53.5171d, 0), new Point(49.5171d, 0.2062d)));
//then
assertThat(geoAuthorsForGeoCriteria3.size(), is(2));
assertThat(geoAuthorsForGeoCriteria3, containsInAnyOrder(hasProperty("name", equalTo("Mohsin Husen")), hasProperty("name", equalTo("Rizwan Idrees"))));
// when
List<AuthorMarkerEntity> geoAuthorsForGeoCriteria3 = elasticsearchTemplate.queryForList(geoLocationCriteriaQuery3,
AuthorMarkerEntity.class);
// then
assertThat(geoAuthorsForGeoCriteria3).hasSize(2);
assertThat(geoAuthorsForGeoCriteria3.stream().map(AuthorMarkerEntity::getName))
.containsExactlyInAnyOrder("Mohsin Husen", "Rizwan Idrees");
}
@Test
public void shouldFindLocationWithGeoHashPrefix() {
//given
// given
loadAnnotationBaseEntities();
NativeSearchQueryBuilder location1 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u"));
NativeSearchQueryBuilder location2 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u1"));
NativeSearchQueryBuilder location3 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10"));
NativeSearchQueryBuilder location4 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j"));
NativeSearchQueryBuilder location5 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j4"));
NativeSearchQueryBuilder location11 = new NativeSearchQueryBuilder().withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j46mkfek"));
NativeSearchQueryBuilder location1 = new NativeSearchQueryBuilder()
.withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u"));
NativeSearchQueryBuilder location2 = new NativeSearchQueryBuilder()
.withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u1"));
NativeSearchQueryBuilder location3 = new NativeSearchQueryBuilder()
.withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10"));
NativeSearchQueryBuilder location4 = new NativeSearchQueryBuilder()
.withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j"));
NativeSearchQueryBuilder location5 = new NativeSearchQueryBuilder()
.withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j4"));
NativeSearchQueryBuilder location11 = new NativeSearchQueryBuilder()
.withFilter(QueryBuilders.geoBoundingBoxQuery("locationAsGeoHash").setCorners("u10j46mkfek"));
//when
List<LocationMarkerEntity> result1 = elasticsearchTemplate.queryForList(location1.build(), LocationMarkerEntity.class);
List<LocationMarkerEntity> result2 = elasticsearchTemplate.queryForList(location2.build(), LocationMarkerEntity.class);
List<LocationMarkerEntity> result3 = elasticsearchTemplate.queryForList(location3.build(), LocationMarkerEntity.class);
List<LocationMarkerEntity> result4 = elasticsearchTemplate.queryForList(location4.build(), LocationMarkerEntity.class);
List<LocationMarkerEntity> result5 = elasticsearchTemplate.queryForList(location5.build(), LocationMarkerEntity.class);
List<LocationMarkerEntity> result11 = elasticsearchTemplate.queryForList(location11.build(), LocationMarkerEntity.class);
// when
List<LocationMarkerEntity> result1 = elasticsearchTemplate.queryForList(location1.build(),
LocationMarkerEntity.class);
List<LocationMarkerEntity> result2 = elasticsearchTemplate.queryForList(location2.build(),
LocationMarkerEntity.class);
List<LocationMarkerEntity> result3 = elasticsearchTemplate.queryForList(location3.build(),
LocationMarkerEntity.class);
List<LocationMarkerEntity> result4 = elasticsearchTemplate.queryForList(location4.build(),
LocationMarkerEntity.class);
List<LocationMarkerEntity> result5 = elasticsearchTemplate.queryForList(location5.build(),
LocationMarkerEntity.class);
List<LocationMarkerEntity> result11 = elasticsearchTemplate.queryForList(location11.build(),
LocationMarkerEntity.class);
//then
assertThat(result1.size(), is(3));
assertThat(result2.size(), is(3));
assertThat(result3.size(), is(3));
assertThat(result4.size(), is(3));
assertThat(result5.size(), is(3));
assertThat(result11.size(), is(2));
// then
assertThat(result1).hasSize(3);
assertThat(result2).hasSize(3);
assertThat(result3).hasSize(3);
assertThat(result4).hasSize(3);
assertThat(result5).hasSize(3);
assertThat(result11).hasSize(2);
}
private IndexQuery buildIndex(LocationMarkerEntity result) {
@ -308,4 +355,106 @@ public class ElasticsearchTemplateGeoTests {
indexQuery.setObject(result);
return indexQuery;
}
/**
* @author Franck Marchand
* @author Mohsin Husen
*/
@Document(indexName = "test-index-author-marker-core-geo", type = "geo-class-point-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class AuthorMarkerEntity {
@Id private String id;
private String name;
private GeoPoint location;
private AuthorMarkerEntity() {}
public AuthorMarkerEntity(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GeoPoint getLocation() {
return location;
}
public void setLocation(GeoPoint location) {
this.location = location;
}
}
/**
* @author Franck Marchand
* @author Mohsin Husen
*/
static class AuthorMarkerEntityBuilder {
private AuthorMarkerEntity result;
public AuthorMarkerEntityBuilder(String id) {
result = new AuthorMarkerEntity(id);
}
public AuthorMarkerEntityBuilder name(String name) {
result.setName(name);
return this;
}
public AuthorMarkerEntityBuilder location(double latitude, double longitude) {
result.setLocation(new GeoPoint(latitude, longitude));
return this;
}
public AuthorMarkerEntity build() {
return result;
}
public IndexQuery buildIndex() {
IndexQuery indexQuery = new IndexQuery();
indexQuery.setId(result.getId());
indexQuery.setObject(result);
return indexQuery;
}
}
/**
* @author Franck Marchand
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-location-marker-core-geo", type = "geo-annotation-point-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class LocationMarkerEntity {
@Id private String id;
private String name;
@GeoPointField private String locationAsString;
@GeoPointField private double[] locationAsArray;
@GeoPointField private String locationAsGeoHash;
}
}

View File

@ -1,51 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.core.geo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
/**
* @author Franck Marchand
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-location-marker", type = "geo-annotation-point-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class LocationMarkerEntity {
@Id
private String id;
private String name;
@GeoPointField
private String locationAsString;
@GeoPointField
private double[] locationAsArray;
@GeoPointField
private String locationAsGeoHash;
}

View File

@ -16,37 +16,51 @@
package org.springframework.data.elasticsearch.core.query;
import static org.apache.commons.lang.RandomStringUtils.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import static org.springframework.data.elasticsearch.utils.IndexBuilder.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.lang.Double;
import java.lang.Long;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class CriteriaQueryTests {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
elasticsearchTemplate.deleteIndex(SampleEntity.class);
elasticsearchTemplate.createIndex(SampleEntity.class);
elasticsearchTemplate.putMapping(SampleEntity.class);
@ -55,6 +69,7 @@ public class CriteriaQueryTests {
@Test
public void shouldPerformAndOperation() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
@ -67,19 +82,23 @@ public class CriteriaQueryTests {
indexQuery.setObject(sampleEntity);
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("test").and("message")
.contains("some"));
CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("test").and("message").contains("some"));
// when
SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
// then
assertThat(sampleEntity1, is(notNullValue()));
assertThat(sampleEntity1).isNotNull();
}
@Ignore("DATAES-30")
// @Ignore("DATAES-30")
@Test
public void shouldPerformOrOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@ -106,19 +125,23 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("some").or("message")
.contains("test"));
CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("some").or("message").contains("test"));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
assertThat(page).isNotNull();
assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1);
}
@Test
public void shouldPerformAndOperationWithinCriteria() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
@ -134,18 +157,23 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().and(new Criteria("message").contains("some")));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
assertThat(page).isNotNull();
assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1);
}
@Ignore("DATAES-30")
// @Ignore("DATAES-30")
@Test
public void shouldPerformOrOperationWithinCriteria() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
@ -161,15 +189,18 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().or(new Criteria("message").contains("some")));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
assertThat(page).isNotNull();
assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1);
}
@Test
public void shouldPerformIsOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -187,17 +218,21 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message"));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1);
}
@Test
public void shouldPerformMultipleIsOperations() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@ -225,17 +260,21 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message"));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(page.getTotalElements()).isEqualTo(1);
}
@Test
public void shouldPerformEndsWithOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
@ -264,15 +303,18 @@ public class CriteriaQueryTests {
elasticsearchTemplate.refresh(SampleEntity.class);
Criteria criteria = new Criteria("message").endsWith("end");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
// when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
// then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(sampleEntity, is(notNullValue()));
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(sampleEntity).isNotNull();
}
@Test
public void shouldPerformStartsWithOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -303,15 +345,18 @@ public class CriteriaQueryTests {
elasticsearchTemplate.refresh(SampleEntity.class);
Criteria criteria = new Criteria("message").startsWith("start");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
// when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
// then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(sampleEntity, is(notNullValue()));
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(sampleEntity).isNotNull();
}
@Test
public void shouldPerformContainsOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -341,15 +386,18 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("contains"));
// when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
// then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(sampleEntity, is(notNullValue()));
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(sampleEntity).isNotNull();
}
@Test
public void shouldExecuteExpression() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -379,15 +427,18 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").expression("+elasticsearch || test"));
// when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
// then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(sampleEntity, is(notNullValue()));
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(sampleEntity).isNotNull();
}
@Test
public void shouldExecuteCriteriaChain() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -416,17 +467,20 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").startsWith("some").endsWith("search")
.contains("message").is("some message search"));
CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").startsWith("some").endsWith("search").contains("message").is("some message search"));
// when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
// then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(sampleEntity, is(notNullValue()));
assertThat(criteriaQuery.getCriteria().getField().getName()).isEqualTo("message");
assertThat(sampleEntity).isNotNull();
}
@Test
public void shouldPerformIsNotOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -456,16 +510,19 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("foo").not());
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertTrue(criteriaQuery.getCriteria().isNegating());
assertThat(page, is(notNullValue()));
assertFalse(page.iterator().next().getMessage().contains("foo"));
assertThat(criteriaQuery.getCriteria().isNegating()).isTrue();
assertThat(page).isNotNull();
assertThat(page.iterator().next().getMessage()).doesNotContain("foo");
}
@Test
public void shouldPerformBetweenOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -497,14 +554,17 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100, 150));
// when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
// then
assertThat(sampleEntity, is(notNullValue()));
assertThat(sampleEntity).isNotNull();
}
@Test
public void shouldPerformBetweenOperationWithoutUpperBound() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -536,15 +596,18 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(350, null));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
assertThat(page).isNotNull();
assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1);
}
@Test
public void shouldPerformBetweenOperationWithoutLowerBound() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -576,15 +639,18 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(null, 550));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
assertThat(page).isNotNull();
assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1);
}
@Test
public void shouldPerformLessThanEqualOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -616,15 +682,18 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").lessThanEqual(750));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
assertThat(page).isNotNull();
assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1);
}
@Test
public void shouldPerformGreaterThanEquals() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -656,15 +725,18 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").greaterThanEqual(950));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
assertThat(page).isNotNull();
assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1);
}
@Test
public void shouldPerformBoostOperation() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
// first document
@ -696,14 +768,17 @@ public class CriteriaQueryTests {
elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
assertThat(page.getTotalElements()).isGreaterThanOrEqualTo(1);
}
@Test
public void shouldReturnDocumentAboveMinimalScoreGivenCriteria() {
// given
List<IndexQuery> indexQueries = new ArrayList<>();
@ -715,11 +790,34 @@ public class CriteriaQueryTests {
elasticsearchTemplate.refresh(SampleEntity.class);
// when
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("a").or(new Criteria("message").contains("b")));
CriteriaQuery criteriaQuery = new CriteriaQuery(
new Criteria("message").contains("a").or(new Criteria("message").contains("b")));
criteriaQuery.setMinScore(2.0F);
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
// then
assertThat(page.getTotalElements(), is(1L));
assertThat(page.getContent().get(0).getMessage(), is("ab"));
assertThat(page.getTotalElements()).isEqualTo(1);
assertThat(page.getContent().get(0).getMessage()).isEqualTo("ab");
}
@Builder
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Document(indexName = "test-index-sample-core-query", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@org.springframework.data.elasticsearch.annotations.Field(type = Text, store = true,
fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
}

View File

@ -1,50 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Kevin Letur
*/
public class AbstractInheritedEntity {
@Id
private String id;
@Field(type = FieldType.Date, index = false)
private Date createdDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}

View File

@ -1,42 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class Author {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -1,62 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Nordine Bittich
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-book", type = "book", shards = 1, replicas = 0, refreshInterval = "-1")
public class Book {
@Id
private String id;
private String name;
@Field(type = FieldType.Object)
private Author author;
@Field(type = FieldType.Nested)
private Map<Integer, Collection<String>> buckets = new HashMap<>();
@MultiField(
mainField = @Field(type = FieldType.Text, analyzer = "whitespace"),
otherFields = {
@InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop", searchAnalyzer = "standard")
}
)
private String description;
}

View File

@ -1,54 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Car {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}

View File

@ -1,47 +0,0 @@
/*
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-copy-to", type = "test", shards = 1, replicas = 0, refreshInterval = "-1")
public class CopyToEntity {
@Id private String id;
@Field(type = FieldType.Keyword, copyTo = "name") private String firstName;
@Field(type = FieldType.Keyword, copyTo = "name") private String lastName;
@Field(type = FieldType.Keyword) private String name;
}

View File

@ -1,70 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Document(indexName = "test-index-double-keyed-entity", type = "double-keyed-entity", shards = 1, replicas = 0, refreshInterval = "-1")
public class DoubleIDEntity {
@Id
private Double id;
private String type;
private String message;
@Version
private Long version;
public Double getId() {
return id;
}
public void setId(Double id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}

View File

@ -1,61 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Mapping;
import org.springframework.data.elasticsearch.annotations.Setting;
/**
* Sample DynamicSettingAndMappingEntity for test out dynamic setting using @Setting Annotation
*
* @author Mohsin Husen
*/
@Document(indexName = "test-index-dynamic-setting-and-mapping", type = "test-setting-type")
@Setting(settingPath = "/settings/test-settings.json")
@Mapping(mappingPath = "/mappings/test-mappings.json")
public class DynamicSettingAndMappingEntity {
@Id
private String id;
private String name;
private String email;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

View File

@ -1,51 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Mapping;
/**
* Sample FieldDynamicMappingEntity for test dynamic mapping using @Mapping Annotation at field level
*
* @author Ted Liang
*/
@Document(indexName = "test-index-field-dynamic-mapping", type = "test-field-mapping-type")
public class FieldDynamicMappingEntity {
@Id
private String id;
@Mapping(mappingPath = "/mappings/test-field-mappings.json")
private byte[] file;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
}

View File

@ -1,49 +0,0 @@
/*
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.elasticsearch.index.VersionType;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author Ivan Greene
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample", type = "test-type", shards = 1, replicas = 0,
refreshInterval = "-1", versionType = VersionType.EXTERNAL_GTE)
public class GTEVersionEntity {
@Version
private Long version;
@Id
private String id;
private String name;
}

View File

@ -1,48 +0,0 @@
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.geo.Box;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Point;
import org.springframework.data.geo.Polygon;
/**
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-geo", type = "geo-test-index", shards = 1, replicas = 0, refreshInterval = "-1")
public class GeoEntity {
@Id
private String id;
//geo shape - Spring Data
private Box box;
private Circle circle;
private Polygon polygon;
//geo point - Custom implementation + Spring Data
@GeoPointField
private Point pointA;
private GeoPoint pointB;
@GeoPointField
private String pointC;
@GeoPointField
private double[] pointD;
}

View File

@ -1,59 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import java.util.List;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Mohsin Husen
*/
public class GirlFriend {
private String name;
private String type;
@Field(type = FieldType.Nested)
private List<Car> cars;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
}

View File

@ -1,37 +0,0 @@
/*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import java.util.HashSet;
import java.util.Set;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* Created by akonczak on 21/08/2016.
*/
@Document(indexName = "test-index-group", type = "group")
public class Group {
@Id
String id;
@Field(type = FieldType.Nested, ignoreFields ={"groups"})
private Set<User> users = new HashSet<>();
}

View File

@ -1,83 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author Abdul Waheed
* @author Mohsin Husen
*/
@Document(indexName = "test-index-1", type = "hetro", replicas = 0, shards = 1)
public class HetroEntity1 {
@Id
private String id;
private String firstName;
@Version
private Long version;
public HetroEntity1(String id, String firstName) {
this.id = id;
this.firstName = firstName;
this.version = System.currentTimeMillis();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SampleEntity)) {
return false;
}
if (this == obj) {
return true;
}
HetroEntity1 rhs = (HetroEntity1) obj;
return new EqualsBuilder().append(this.id, rhs.id).append(this.firstName, rhs.firstName).append(this.version, rhs.version).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(id).append(firstName).append(version).toHashCode();
}
}

View File

@ -1,83 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author Abdul Waheed
* @author Mohsin Husen
*/
@Document(indexName = "test-index-2", type = "hetro", replicas = 0, shards = 1)
public class HetroEntity2 {
@Id
private String id;
private String lastName;
@Version
private Long version;
public HetroEntity2(String id, String lastName) {
this.id = id;
this.lastName = lastName;
this.version = System.currentTimeMillis();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SampleEntity)) {
return false;
}
if (this == obj) {
return true;
}
HetroEntity2 rhs = (HetroEntity2) obj;
return new EqualsBuilder().append(this.id, rhs.id).append(this.lastName, rhs.lastName).append(this.version, rhs.version).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(id).append(lastName).append(version).toHashCode();
}
}

View File

@ -1,70 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Document(indexName = "test-index-integer-keyed-entity", type = "integer-keyed-entity", shards = 1, replicas = 0, refreshInterval = "-1")
public class IntegerIDEntity {
@Id
private Integer id;
private String type;
private String message;
@Version
private Long version;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}

View File

@ -1,31 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* MinimalEntity
*
* @author Philipp Jardas
*/
@Document(indexName = "test-index-minimal", type = "type")
public class MinimalEntity {
@Id
private String id;
}

View File

@ -1,46 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.springframework.data.annotation.Id;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class NonDocumentEntity {
@Id
private String someId;
private String someField1;
private String someField2;
public String getSomeField1() {
return someField1;
}
public void setSomeField1(String someField1) {
this.someField1 = someField1;
}
public String getSomeField2() {
return someField2;
}
public void setSomeField2(String someField2) {
this.someField2 = someField2;
}
}

View File

@ -1,52 +0,0 @@
/*
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField;
import org.springframework.data.elasticsearch.annotations.Setting;
/**
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-normalizer", type = "test", shards = 1, replicas = 0, refreshInterval = "-1")
@Setting(settingPath = "/settings/test-normalizer.json")
public class NormalizerEntity {
@Id private String id;
@Field(type = FieldType.Keyword, normalizer = "lower_case_normalizer")
private String name;
@MultiField(mainField = @Field(type = FieldType.Text), otherFields = { @InnerField(suffix = "lower_case",
type = FieldType.Keyword, normalizer = "lower_case_normalizer") })
private String description;
}

View File

@ -1,101 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.springframework.core.style.ToStringCreator;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.Parent;
/**
* ParentEntity
*
* @author Philipp Jardas
* @author Mohsin Husen
*/
@Document(indexName = ParentEntity.INDEX, type = ParentEntity.PARENT_TYPE, shards = 1, replicas = 0, refreshInterval = "-1")
public class ParentEntity {
public static final String INDEX = "parent-child";
public static final String PARENT_TYPE = "parent-entity";
public static final String CHILD_TYPE = "child-entity";
@Id
private String id;
@Field(type = FieldType.Text, store = true)
private String name;
public ParentEntity() {
}
public ParentEntity(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
return new ToStringCreator(this).append("id", id).append("name", name).toString();
}
@Document(indexName = INDEX, type = CHILD_TYPE, shards = 1, replicas = 0, refreshInterval = "-1")
public static class ChildEntity {
@Id
private String id;
@Field(type = FieldType.Text, store = true)
@Parent(type = PARENT_TYPE)
private String parentId;
@Field(type = FieldType.Text, store = true)
private String name;
public ChildEntity() {
}
public ChildEntity(String id, String parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
public String getId() {
return id;
}
public String getParentId() {
return parentId;
}
public String getName() {
return name;
}
@Override
public String toString() {
return new ToStringCreator(this).append("id", id).append("parentId", parentId).append("name", name).toString();
}
}
}

View File

@ -1,77 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Document(indexName = "test-index-person", type = "user", shards = 1, replicas = 0, refreshInterval = "-1")
public class Person {
@Id
private String id;
private String name;
@Field(type = FieldType.Nested)
private List<Car> car;
@Field(type = FieldType.Nested, includeInParent = true)
private List<Book> books;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Car> getCar() {
return car;
}
public void setCar(List<Car> car) {
this.car = car;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}

View File

@ -1,88 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Document(indexName = "test-index-person-multiple-level-nested", type = "user", shards = 1, replicas = 0, refreshInterval = "-1")
public class PersonMultipleLevelNested {
@Id
private String id;
private String name;
@Field(type = FieldType.Nested)
private List<GirlFriend> girlFriends;
@Field(type = FieldType.Nested)
private List<Car> cars;
@Field(type = FieldType.Nested, includeInParent = true)
private List<Car> bestCars;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<GirlFriend> getGirlFriends() {
return girlFriends;
}
public void setGirlFriends(List<GirlFriend> girlFriends) {
this.girlFriends = girlFriends;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public List<Car> getBestCars() {
return bestCars;
}
public void setBestCars(List<Car> bestCars) {
this.bestCars = bestCars;
}
}

View File

@ -1,97 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Date;
import java.util.List;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-product", type = "test-product-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class Product {
@Id
private String id;
private List<String> title;
private String name;
private String description;
private String text;
private List<String> categories;
private Float weight;
@Field(type = FieldType.Float)
private Float price;
private Integer popularity;
private boolean available;
private String location;
private Date lastModified;
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Product other = (Product) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
}

View File

@ -1,73 +0,0 @@
package org.springframework.data.elasticsearch.entities;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.Text;
import java.util.Date;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
/**
* @author Jakub Vavrik
*/
@Document(indexName = "test-index-date-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleDateMappingEntity {
@Id
private String id;
@Field(type = Text, index = false, store = true, analyzer = "standard")
private String message;
@Field(type = Date, format = DateFormat.custom, pattern = "dd.MM.yyyy hh:mm")
private Date customFormatDate;
@Field(type = Date)
private Date defaultFormatDate;
@Field(type = Date, format = DateFormat.basic_date)
private Date basicFormatDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getCustomFormatDate() {
return customFormatDate;
}
public void setCustomFormatDate(Date customFormatDate) {
this.customFormatDate = customFormatDate;
}
public Date getDefaultFormatDate() {
return defaultFormatDate;
}
public void setDefaultFormatDate(Date defaultFormatDate) {
this.defaultFormatDate = defaultFormatDate;
}
public Date getBasicFormatDate() {
return basicFormatDate;
}
public void setBasicFormatDate(Date basicFormatDate) {
this.basicFormatDate = basicFormatDate;
}
}

View File

@ -1,25 +0,0 @@
package org.springframework.data.elasticsearch.entities;
import java.util.HashMap;
import java.util.Map;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.DynamicTemplates;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Petr Kukral
*/
@Document(indexName = "test-dynamictemplates", type = "test-dynamictemplatestype", indexStoreType = "memory", shards = 1,
replicas = 0, refreshInterval = "-1")
@DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings.json")
public class SampleDynamicTemplatesEntity {
@Id
private String id;
@Field(type = FieldType.Object)
private Map<String, String> names = new HashMap<String, String>();
}

View File

@ -1,25 +0,0 @@
package org.springframework.data.elasticsearch.entities;
import java.util.HashMap;
import java.util.Map;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.DynamicTemplates;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Petr Kukral
*/
@Document(indexName = "test-dynamictemplates", type = "test-dynamictemplatestype", indexStoreType = "memory", shards = 1,
replicas = 0, refreshInterval = "-1")
@DynamicTemplates(mappingPath = "/mappings/test-dynamic_templates_mappings_two.json")
public class SampleDynamicTemplatesEntityTwo {
@Id
private String id;
@Field(type = FieldType.Object)
private Map<String, String> names = new HashMap<String, String>();
}

View File

@ -1,99 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleEntity {
@Id
private String id;
@Field(type = Text, store = true, fielddata = true)
private String type;
@Field(type = Text, store = true, fielddata = true)
private String message;
private int rate;
@ScriptedField
private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version
private Long version;
@Score
private float score;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SampleEntity that = (SampleEntity) o;
if (available != that.available) return false;
if (rate != that.rate) return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) : that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (location != null ? !location.equals(that.location) : that.location != null) return false;
if (message != null ? !message.equals(that.message) : that.message != null) return false;
if (type != null ? !type.equals(that.type) : that.type != null) return false;
if (version != null ? !version.equals(that.version) : that.version != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}

View File

@ -1,96 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.UUID;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
/**
* @author Gad Akuka
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-uuid-keyed", type = "test-type-uuid-keyed", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleEntityUUIDKeyed {
@Id
private UUID id;
private String type;
@Field(type = FieldType.Text, fielddata = true)
private String message;
private int rate;
@ScriptedField
private Long scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version
private Long version;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SampleEntityUUIDKeyed that = (SampleEntityUUIDKeyed) o;
if (available != that.available) return false;
if (rate != that.rate) return false;
if (highlightedMessage != null ? !highlightedMessage.equals(that.highlightedMessage) : that.highlightedMessage != null)
return false;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (location != null ? !location.equals(that.location) : that.location != null) return false;
if (message != null ? !message.equals(that.message) : that.message != null) return false;
if (type != null ? !type.equals(that.type) : that.type != null) return false;
if (version != null ? !version.equals(that.version) : that.version != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
result = 31 * result + (message != null ? message.hashCode() : 0);
result = 31 * result + rate;
result = 31 * result + (available ? 1 : 0);
result = 31 * result + (highlightedMessage != null ? highlightedMessage.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (version != null ? version.hashCode() : 0);
return result;
}
}

View File

@ -1,39 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import static org.springframework.data.elasticsearch.annotations.FieldType.Text;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
/**
* @author Kevin Leturc
*/
@Document(indexName = "test-index-sample-inherited", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleInheritedEntity extends AbstractInheritedEntity {
@Field(type = Text, index = false, store = true, analyzer = "standard")
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -1,68 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import static org.springframework.data.elasticsearch.annotations.FieldType.Text;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Document(indexName = "test-index-sample-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleMappingEntity {
@Id
private String id;
@Field(type = Text, index = false, store = true, analyzer = "standard")
private String message;
private NestedEntity nested;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
static class NestedEntity {
@Field(type = Text)
private String someField;
public String getSomeField() {
return someField;
}
public void setSomeField(String someField) {
this.someField = someField;
}
}
}

View File

@ -1,79 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import static org.springframework.data.elasticsearch.annotations.FieldType.Text;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
/**
* @author Jakub Vavrik
*/
@Document(indexName = "test-index-recursive-mapping", type = "mapping", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleTransientEntity {
@Id
private String id;
@Field(type = Text, index = false, store = true, analyzer = "standard")
private String message;
@Transient
private NestedEntity nested;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
static class NestedEntity {
@Field
private static NestedEntity someField = new NestedEntity();
@Field
private Boolean something;
public NestedEntity getSomeField() {
return someField;
}
public void setSomeField(NestedEntity someField) {
this.someField = someField;
}
public Boolean getSomething() {
return something;
}
public void setSomething(Boolean something) {
this.something = something;
}
}
}

View File

@ -1,34 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Stuart Stevenson
* @author Mohsin Husen
*/
@Document(indexName = "test-index-simple-recursive", type = "circular-object", shards = 1, replicas = 0, refreshInterval = "-1")
public class SimpleRecursiveEntity {
@Id
private String id;
@Field(type = FieldType.Object, ignoreFields = {"circularObject"})
private SimpleRecursiveEntity circularObject;
}

View File

@ -1,39 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* SpELEntity
*
* @author Artur Konczak
*/
@Document(indexName = "#{'test-index-abz'+'-'+'entity'}", type = "#{'my'+'Type'}", shards = 1,
replicas = 0, refreshInterval = "-1")
public class SpELEntity {
@Id private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}

View File

@ -1,50 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.math.BigDecimal;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* @author Artur Konczak
* @author Mohsin Husen
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-stock", type = "price", shards = 1, replicas = 0, refreshInterval = "-1")
public class StockPrice {
@Id
private String id;
private String symbol;
@Field(type = FieldType.Double)
private BigDecimal price;
}

View File

@ -1,52 +0,0 @@
/*
* Copyright 2014-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Mapping;
import org.springframework.data.elasticsearch.annotations.Setting;
/**
* Sample DynamicSettingAndMappingEntity for test out dynamic setting using @Setting Annotation
*
* @author Mohsin Husen
*/
@Document(indexName = "test-index-synonym", type = "synonym-type")
@Setting(settingPath = "/synonyms/settings.json")
@Mapping(mappingPath = "/synonyms/mappings.json")
public class SynonymEntity {
@Id
private String id;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

View File

@ -1,28 +0,0 @@
package org.springframework.data.elasticsearch.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* Created by akonczak on 12/12/2015.
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-server-configuration", type = "test-type", useServerConfiguration = true, shards = 10, replicas = 10, refreshInterval = "-1")
public class UseServerConfigurationEntity {
@Id
private String id;
private String val;
}

View File

@ -1,36 +0,0 @@
/*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.entities;
import java.util.HashSet;
import java.util.Set;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
/**
* Created by akonczak on 21/08/2016.
*/
@Document(indexName = "test-index-user", type = "user")
public class User {
@Id
private String id;
@Field(type= FieldType.Nested,ignoreFields={"users"})
private Set<Group> groups = new HashSet<>();
}

View File

@ -15,17 +15,20 @@
*/
package org.springframework.data.elasticsearch.immutable;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.Optional;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.repository.CrudRepository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ -34,6 +37,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Oliver Gierke
* @author Mark Paluch
* @author Christoph Strobl
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:immutable-repository-test.xml")
@ -50,27 +54,46 @@ public class ImmutableElasticsearchRepositoryTests {
operations.refresh(ImmutableEntity.class);
}
/**
* @see DATAES-281
*/
@Test
@Ignore("fix me - UnsupportedOperation")
@Test // DATAES-281
public void shouldSaveAndFindImmutableDocument() {
// when
ImmutableEntity entity = repository.save(new ImmutableEntity("test name"));
assertThat(entity.getId(), is(notNullValue()));
assertThat(entity.getId()).isNotNull();
// then
Optional<ImmutableEntity> entityFromElasticSearch = repository.findById(entity.getId());
assertThat(entityFromElasticSearch.isPresent(), is(true));
assertThat(entityFromElasticSearch).isPresent();
entityFromElasticSearch.ifPresent(immutableEntity -> {
assertThat(immutableEntity.getName(), is("test name"));
assertThat(immutableEntity.getId(), is(entity.getId()));
assertThat(immutableEntity.getName()).isEqualTo("test name");
assertThat(immutableEntity.getId()).isEqualTo(entity.getId());
});
}
/**
* @author Young Gu
* @author Oliver Gierke
*/
@Document(indexName = "test-index-immutable")
@NoArgsConstructor(force = true)
@Getter
static class ImmutableEntity {
private final String id, name;
public ImmutableEntity(String name) {
this.id = null;
this.name = name;
}
}
/**
* @author Young Gu
* @author Oliver Gierke
*/
public interface ImmutableElasticsearchRepository extends CrudRepository<ImmutableEntity, String> {}
}

View File

@ -1,27 +0,0 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.repositories.book;
import org.springframework.data.elasticsearch.entities.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public interface SampleElasticSearchBookRepository extends ElasticsearchRepository<Book, String> {
}

View File

@ -17,7 +17,6 @@ package org.springframework.data.elasticsearch.repositories.cdi;
import java.util.Optional;
import org.springframework.data.elasticsearch.entities.Product;
import org.springframework.data.repository.CrudRepository;
/**
@ -26,7 +25,7 @@ import org.springframework.data.repository.CrudRepository;
* @author Mark Paluch
* @author Christoph Strobl
*/
public interface CdiProductRepository extends CrudRepository<Product, String> {
public interface CdiProductRepository extends CrudRepository<CdiRepositoryTests.Product, String> {
Optional<Product> findById(String id);
Optional<CdiRepositoryTests.Product> findById(String id);
}

View File

@ -15,9 +15,19 @@
*/
package org.springframework.data.elasticsearch.repositories.cdi;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.apache.webbeans.cditest.CdiTestContainer;
@ -26,12 +36,18 @@ import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.data.elasticsearch.entities.Product;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.InnerField;
import org.springframework.data.elasticsearch.annotations.MultiField;
/**
* @author Mohsin Husen
* @author Mark Paluch
* @author Christoph Strobl
* @author Peter-Josef Meisch
*/
public class CdiRepositoryTests {
@ -63,12 +79,13 @@ public class CdiRepositoryTests {
personRepository = client.getSamplePersonRepository();
repository.deleteAll();
qualifiedProductRepository = client.getQualifiedProductRepository();
qualifiedProductRepository.deleteAll();
}
@Test
public void testCdiRepository() {
assertNotNull(repository);
assertThat(repository).isNotNull();
Product bean = new Product();
bean.setId("id-1");
@ -76,33 +93,30 @@ public class CdiRepositoryTests {
repository.save(bean);
assertTrue(repository.existsById(bean.getId()));
assertThat(repository.existsById(bean.getId())).isTrue();
Optional<Product> retrieved = repository.findById(bean.getId());
assertTrue(retrieved.isPresent());
assertThat(retrieved).isPresent();
retrieved.ifPresent(product -> {
assertEquals(bean.getId(), product.getId());
assertEquals(bean.getName(), product.getName());
assertThat(bean.getId()).isEqualTo(product.getId());
assertThat(bean.getName()).isEqualTo(product.getName());
});
assertEquals(1, repository.count());
assertThat(repository.count()).isEqualTo(1);
assertTrue(repository.existsById(bean.getId()));
assertThat(repository.existsById(bean.getId())).isTrue();
repository.delete(bean);
assertEquals(0, repository.count());
assertThat(repository.count()).isEqualTo(0);
retrieved = repository.findById(bean.getId());
assertFalse(retrieved.isPresent());
assertThat(retrieved).isNotPresent();
}
/**
* @see DATAES-234
*/
@Test
@Test // DATAES-234
public void testQualifiedCdiRepository() {
assertNotNull(qualifiedProductRepository);
assertThat(qualifiedProductRepository).isNotNull();
Product bean = new Product();
bean.setId("id-1");
@ -110,32 +124,226 @@ public class CdiRepositoryTests {
qualifiedProductRepository.save(bean);
assertTrue(qualifiedProductRepository.existsById(bean.getId()));
assertThat(qualifiedProductRepository.existsById(bean.getId())).isTrue();
Optional<Product> retrieved = qualifiedProductRepository.findById(bean.getId());
assertTrue(retrieved.isPresent());
assertThat(retrieved).isPresent();
retrieved.ifPresent(product -> {
assertEquals(bean.getId(), product.getId());
assertEquals(bean.getName(), product.getName());
assertThat(bean.getId()).isEqualTo(product.getId());
assertThat(bean.getName()).isEqualTo(product.getName());
});
assertEquals(1, qualifiedProductRepository.count());
assertThat(qualifiedProductRepository.count()).isEqualTo(1);
assertTrue(qualifiedProductRepository.existsById(bean.getId()));
assertThat(qualifiedProductRepository.existsById(bean.getId())).isTrue();
qualifiedProductRepository.delete(bean);
assertEquals(0, qualifiedProductRepository.count());
assertThat(qualifiedProductRepository.count()).isEqualTo(0);
retrieved = qualifiedProductRepository.findById(bean.getId());
assertFalse(retrieved.isPresent());
assertThat(retrieved).isNotPresent();
}
@Test // DATAES-113
public void returnOneFromCustomImpl() {
assertThat(personRepository.returnOne()).isEqualTo(1);
}
/**
* @see DATAES-113
* @author Mohsin Husen
* @author Artur Konczak
*/
@Test
public void returnOneFromCustomImpl() {
assertThat(personRepository.returnOne(), is(1));
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-product-cdi-repository", type = "test-product-type", shards = 1, replicas = 0,
refreshInterval = "-1")
static class Product {
@Id private String id;
private List<String> title;
private String name;
private String description;
private String text;
private List<String> categories;
private Float weight;
@Field(type = FieldType.Float) private Float price;
private Integer popularity;
private boolean available;
private String location;
private Date lastModified;
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Product other = (Product) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Document(indexName = "test-index-person-cdi-repository", type = "user", shards = 1, replicas = 0, refreshInterval = "-1")
static class Person {
@Id private String id;
private String name;
@Field(type = FieldType.Nested) private List<Car> car;
@Field(type = FieldType.Nested, includeInParent = true) private List<Book> books;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Car> getCar() {
return car;
}
public void setCar(List<Car> car) {
this.car = car;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Nordine Bittich
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Document(indexName = "test-index-book-cdi-repository", type = "book", shards = 1, replicas = 0, refreshInterval = "-1")
static class Book {
@Id private String id;
private String name;
@Field(type = FieldType.Object) private Author author;
@Field(type = FieldType.Nested) private Map<Integer, Collection<String>> buckets = new HashMap<>();
@MultiField(mainField = @Field(type = FieldType.Text, analyzer = "whitespace"),
otherFields = { @InnerField(suffix = "prefix", type = FieldType.Text, analyzer = "stop",
searchAnalyzer = "standard") }) private String description;
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Artur Konczak
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
static class Car {
private String name;
private String model;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
static class Author {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.repositories.cdi;
import org.springframework.data.elasticsearch.entities.Product;
import org.springframework.data.repository.CrudRepository;
/**
@ -24,6 +23,6 @@ import org.springframework.data.repository.CrudRepository;
*/
@PersonDB
@OtherQualifier
public interface QualifiedProductRepository extends CrudRepository<Product, String> {
public interface QualifiedProductRepository extends CrudRepository<CdiRepositoryTests.Product, String> {
}

View File

@ -15,13 +15,12 @@
*/
package org.springframework.data.elasticsearch.repositories.cdi;
import org.springframework.data.elasticsearch.entities.Person;
import org.springframework.data.repository.Repository;
/**
* @author Mark Paluch
* @see DATAES-113
*/
public interface SamplePersonRepository extends Repository<Person, Long>, SamplePersonRepositoryCustom {
public interface SamplePersonRepository extends Repository<CdiRepositoryTests.Person, Long>, SamplePersonRepositoryCustom {
}

View File

@ -0,0 +1,105 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.repositories.complex.custommethod.autowiring;
import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.lang.Double;
import java.lang.Long;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Version;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.Score;
import org.springframework.data.elasticsearch.annotations.ScriptedField;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.utils.IndexInitializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Artur Konczak
* @author Mohsin Husen
* @author Peter-Josef Meisch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:complex-custom-method-repository-test.xml")
public class ComplexCustomMethodRepositoryTests {
@Autowired private ComplexElasticsearchRepository complexRepository;
@Autowired private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before() {
IndexInitializer.init(elasticsearchTemplate, SampleEntity.class);
}
@Test
public void shouldExecuteComplexCustomMethod() {
// given
// when
String result = complexRepository.doSomethingSpecial();
// then
assertThat(result).isEqualTo("2+2=4");
}
/**
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Chris White
* @author Sascha Woo
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
@Document(indexName = "test-index-sample-repositories-complex-custommethod-autowiring", type = "test-type", shards = 1, replicas = 0, refreshInterval = "-1")
static class SampleEntity {
@Id private String id;
@Field(type = Text, store = true, fielddata = true) private String type;
@Field(type = Text, store = true, fielddata = true) private String message;
private int rate;
@ScriptedField private Double scriptedRate;
private boolean available;
private String highlightedMessage;
private GeoPoint location;
@Version private Long version;
@Score private float score;
}
}

View File

@ -13,14 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.repository.complex;
package org.springframework.data.elasticsearch.repositories.complex.custommethod.autowiring;
import org.springframework.data.elasticsearch.entities.SampleEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* @author Artur Konczak
*/
public interface ComplexElasticsearchRepository extends ElasticsearchRepository<SampleEntity, String>, ComplexElasticsearchRepositoryCustom {
public interface ComplexElasticsearchRepository extends ElasticsearchRepository<ComplexCustomMethodRepositoryTests.SampleEntity, String>, ComplexElasticsearchRepositoryCustom {
}

View File

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.elasticsearch.repository.complex;
package org.springframework.data.elasticsearch.repositories.complex.custommethod.autowiring;
/**
* @author Artur Konczak

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