DATAES-630 - Remove GetResultMapper and friends from core package.

Original PR: #331
This commit is contained in:
Peter-Josef Meisch
2019-10-25 22:05:58 +02:00
committed by GitHub
parent d4f23a50e7
commit 4e7f1ccb4b
39 changed files with 600 additions and 2004 deletions

View File

@@ -21,6 +21,7 @@ import java.util.Arrays;
import java.util.Collections;
import org.junit.Test;
import org.springframework.data.elasticsearch.core.document.Document;
/**
* Unit tests for {@link Document}.

View File

@@ -21,12 +21,12 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.ElasticsearchConfigurationSupport;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.junit.junit4.TestNodeResource;
/**
* configuration class for the classic ElasticsearchTemplate. Needs a {@link TestNodeResource} bean that should be set up in
* the test as ClassRule and exported as bean.
* configuration class for the classic ElasticsearchTemplate. Needs a {@link TestNodeResource} bean that should be set
* up in the test as ClassRule and exported as bean.
*
* @author Peter-Josef Meisch
*/
@@ -41,8 +41,9 @@ public class ElasticsearchTestConfiguration extends ElasticsearchConfigurationSu
}
@Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" })
public ElasticsearchTemplate elasticsearchTemplate(Client elasticsearchClient, MappingElasticsearchConverter entityMapper) {
return new ElasticsearchTemplate(elasticsearchClient, entityMapper);
public ElasticsearchTemplate elasticsearchTemplate(Client elasticsearchClient,
ElasticsearchConverter elasticsearchConverter) {
return new ElasticsearchTemplate(elasticsearchClient, elasticsearchConverter);
}
}

View File

@@ -18,6 +18,8 @@ package org.springframework.data.elasticsearch.client.reactive;
import static org.assertj.core.api.Assertions.*;
import lombok.SneakyThrows;
import org.junit.ClassRule;
import org.springframework.data.elasticsearch.junit.junit4.TestNodeResource;
import reactor.test.StepVerifier;
import java.io.IOException;
@@ -68,9 +70,11 @@ import org.springframework.test.context.junit4.SpringRunner;
* @author Peter-Josef Meisch
*/
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:infrastructure.xml")
public class ReactiveElasticsearchClientTests {
@ClassRule
public static TestNodeResource testNodeResource = new TestNodeResource();
public @Rule ElasticsearchVersionRule elasticsearchVersion = ElasticsearchVersionRule.any();
static final String INDEX_I = "idx-1-reactive-client-tests";

View File

@@ -30,10 +30,8 @@ import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.EntityMapper;
import org.springframework.data.elasticsearch.core.ReactiveElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
/**
@@ -102,13 +100,6 @@ public class ElasticsearchConfigurationSupportUnitTests {
assertThat(context.getBean(ReactiveElasticsearchTemplate.class)).isNotNull();
}
@Test // DATAES-530
public void usesConfiguredEntityMapper() {
AbstractApplicationContext context = new AnnotationConfigApplicationContext(EntityMapperConfig.class);
assertThat(context.getBean(EntityMapper.class)).isInstanceOf(MappingElasticsearchConverter.class);
}
@Configuration
static class StubConfig extends ElasticsearchConfigurationSupport {

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;
import java.util.List;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
/**
* @author Artur Konczak
* @author Mohsin Husen
*/
public class CustomResultMapper implements ResultsMapper {
private EntityMapper entityMapper;
public CustomResultMapper(EntityMapper entityMapper) {
this.entityMapper = entityMapper;
}
@Override
public EntityMapper getEntityMapper() {
return entityMapper;
}
@Override
public <T> T mapResult(GetResponse response, Class<T> clazz) {
return null; // To change body of implemented methods use File | Settings | File Templates.
}
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
return null; // To change body of implemented methods use File | Settings | File Templates.
}
@Override
public <T> List<T> mapResults(MultiGetResponse responses, Class<T> clazz) {
return null;
}
}

View File

@@ -1,336 +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;
import static java.util.Arrays.*;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.data.elasticsearch.annotations.FieldType.*;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
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.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import com.fasterxml.jackson.databind.util.ArrayIterator;
/**
* @author Artur Konczak
* @author Mohsin Husen
* @author Chris White
* @author Mark Paluch
* @author Ilkang Na
* @author Christoph Strobl
* @author Peter-Josef Meisch
*/
public class DefaultResultMapperTests {
private SimpleElasticsearchMappingContext context = new SimpleElasticsearchMappingContext();
private EntityMapper entityMapper = new MappingElasticsearchConverter(context);
private DefaultResultMapper resultMapper = new DefaultResultMapper(context, entityMapper);
private SearchResponse response = mock(SearchResponse.class);
@Test
public void shouldMapAggregationsToPage() {
// given
SearchHit[] hits = { createCarHit("Ford", "Grat"), createCarHit("BMW", "Arrow") };
SearchHits searchHits = mock(SearchHits.class);
when(searchHits.getTotalHits()).thenReturn(new TotalHits(2L, TotalHits.Relation.EQUAL_TO));
when(searchHits.iterator()).thenReturn(new ArrayIterator(hits));
when(response.getHits()).thenReturn(searchHits);
Aggregations aggregations = new Aggregations(asList(createCarAggregation()));
when(response.getAggregations()).thenReturn(aggregations);
// when
AggregatedPage<Car> page = resultMapper.mapResults(response, Car.class, Pageable.unpaged());
// then
page.hasFacets();
assertThat(page.hasAggregations()).isTrue();
assertThat(page.getAggregation("Diesel").getName()).isEqualTo("Diesel");
}
@Test
public void shouldMapSearchRequestToPage() {
// given
SearchHit[] hits = { createCarHit("Ford", "Grat"), createCarHit("BMW", "Arrow") };
SearchHits searchHits = mock(SearchHits.class);
when(searchHits.getTotalHits()).thenReturn(new TotalHits(2L, TotalHits.Relation.EQUAL_TO));
when(searchHits.iterator()).thenReturn(new ArrayIterator(hits));
when(response.getHits()).thenReturn(searchHits);
// when
Page<Car> page = resultMapper.mapResults(response, Car.class, Pageable.unpaged());
// then
assertThat(page.hasContent()).isTrue();
assertThat(page.getTotalElements()).isEqualTo(2);
assertThat(page.getContent().get(0).getName()).isEqualTo("Ford");
}
@Test
public void shouldMapPartialSearchRequestToObject() {
// given
SearchHit[] hits = { createCarPartialHit("Ford", "Grat"), createCarPartialHit("BMW", "Arrow") };
SearchHits searchHits = mock(SearchHits.class);
when(searchHits.getTotalHits()).thenReturn(new TotalHits(2L, TotalHits.Relation.EQUAL_TO));
when(searchHits.iterator()).thenReturn(new ArrayIterator(hits));
when(response.getHits()).thenReturn(searchHits);
// when
Page<Car> page = resultMapper.mapResults(response, Car.class, Pageable.unpaged());
// then
assertThat(page.hasContent()).isTrue();
assertThat(page.getTotalElements()).isEqualTo(2);
assertThat(page.getContent().get(0).getName()).isEqualTo("Ford");
}
@Test
public void shouldMapGetRequestToObject() {
// given
GetResponse response = mock(GetResponse.class);
when(response.isExists()).thenReturn(true);
Map<String, Object> sourceAsMap = new HashMap<>();
sourceAsMap.put("name", "Ford");
sourceAsMap.put("model", "Grat");
when(response.getSourceAsMap()).thenReturn(sourceAsMap);
when(response.getSourceAsBytesRef()).thenReturn(new BytesArray(" "));
// when
Car result = resultMapper.mapResult(response, Car.class);
// then
assertThat(result).isNotNull();
assertThat(result.getModel()).isEqualTo("Grat");
assertThat(result.getName()).isEqualTo("Ford");
}
@Test // DATAES-281
@Ignore("fix me - UnsupportedOperation")
public void setsIdentifierOnImmutableType() {
GetResponse response = mock(GetResponse.class);
when(response.isExists()).thenReturn(true);
when(response.getSourceAsString()).thenReturn("{}");
when(response.getSourceAsBytesRef()).thenReturn(new BytesArray("{}"));
when(response.getId()).thenReturn("identifier");
ImmutableEntity result = resultMapper.mapResult(response, ImmutableEntity.class);
assertThat(result).isNotNull();
assertThat(result.getId()).isEqualTo("identifier");
}
@Test // DATAES-198
public void setsVersionFromGetResponse() {
GetResponse response = mock(GetResponse.class);
when(response.isExists()).thenReturn(true);
when(response.getSourceAsString()).thenReturn("{}");
when(response.getVersion()).thenReturn(1234L);
MappedEntity result = resultMapper.mapResult(response, MappedEntity.class);
assertThat(result).isNotNull();
assertThat(result.getVersion()).isEqualTo(1234);
}
@Test // DATAES-198
public void setsVersionFromMultiGetResponse() {
GetResponse response1 = mock(GetResponse.class);
when(response1.isExists()).thenReturn(true);
when(response1.getSourceAsString()).thenReturn("{}");
when(response1.getSourceAsBytesRef()).thenReturn(new BytesArray("{}"));
when(response1.isExists()).thenReturn(true);
when(response1.getVersion()).thenReturn(1234L);
GetResponse response2 = mock(GetResponse.class);
when(response2.isExists()).thenReturn(true);
when(response2.getSourceAsString()).thenReturn("{}");
when(response2.getSourceAsBytesRef()).thenReturn(new BytesArray("{}"));
when(response2.isExists()).thenReturn(true);
when(response2.getVersion()).thenReturn(5678L);
MultiGetResponse multiResponse = mock(MultiGetResponse.class);
when(multiResponse.getResponses()).thenReturn(new MultiGetItemResponse[] {
new MultiGetItemResponse(response1, null), new MultiGetItemResponse(response2, null) });
List<MappedEntity> results = resultMapper.mapResults(multiResponse, MappedEntity.class);
assertThat(results).isNotNull().hasSize(2);
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.getSourceRef()).thenReturn(new BytesArray("{}"));
when(hit1.getVersion()).thenReturn(1234L);
SearchHit hit2 = mock(SearchHit.class);
when(hit2.getSourceRef()).thenReturn(new BytesArray("{}"));
when(hit2.getVersion()).thenReturn(5678L);
SearchHits searchHits = mock(SearchHits.class);
when(searchHits.getTotalHits()).thenReturn(new TotalHits(2L, TotalHits.Relation.EQUAL_TO));
when(searchHits.iterator()).thenReturn(Arrays.asList(hit1, hit2).iterator());
SearchResponse searchResponse = mock(SearchResponse.class);
when(searchResponse.getHits()).thenReturn(searchHits);
AggregatedPage<MappedEntity> results = resultMapper.mapResults(searchResponse, MappedEntity.class,
mock(Pageable.class));
assertThat(results).isNotNull();
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);
String json = createJsonCar(name, model);
when(hit.getSourceAsString()).thenReturn(json);
when(hit.getSourceRef()).thenReturn(new BytesArray(json));
Map<String, Object> map = new LinkedHashMap<>();
map.put("name", name);
map.put("model", model);
when(hit.getSourceAsMap()).thenReturn(map);
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));
when(hit.iterator()).thenReturn(createCarFields(name, model).values().iterator());
return hit;
}
private String createJsonCar(String name, String model) {
String q = "\"";
StringBuffer sb = new StringBuffer();
sb.append("{").append(q).append("name").append(q).append(":").append(q).append(name).append(q).append(",");
sb.append(q).append("model").append(q).append(":").append(q).append(model).append(q).append("}");
return sb.toString();
}
private Map<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)));
return result;
}
@Document(indexName = "test-index-immutable-internal")
@NoArgsConstructor(force = true)
@Getter
static class ImmutableEntity {
private final String id, name;
}
@Data
static class Car {
private String name;
private String model;
}
@Data
@Document(indexName = "test-index-sample-default-result-mapper", type = "test-type")
static class MappedEntity {
@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

@@ -29,8 +29,9 @@ import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.search.SearchHit;
import org.junit.Test;
import org.springframework.data.elasticsearch.Document;
import org.springframework.data.elasticsearch.SearchDocument;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.document.DocumentAdapters;
import org.springframework.data.elasticsearch.core.document.SearchDocument;
/**
* Unit tests for {@link DocumentAdapters}.

View File

@@ -23,6 +23,7 @@ import lombok.Builder;
import lombok.Data;
import java.io.IOException;
import java.lang.Object;
import java.util.HashMap;
import java.util.Map;

View File

@@ -35,20 +35,14 @@ import java.lang.Object;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.util.Lists;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateRequestBuilder;
@@ -56,22 +50,17 @@ import org.elasticsearch.cluster.metadata.AliasMetaData;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
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.annotation.Version;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.elasticsearch.ElasticsearchException;
@@ -83,18 +72,13 @@ import org.springframework.data.elasticsearch.annotations.MultiField;
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.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.elasticsearch.core.query.*;
import org.springframework.data.util.CloseableIterator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.util.ReflectionTestUtils;
/**
* Base for testing rest/transport templates
* Base for testing rest/transport templates. Contains the test common to both implementing classes.
*
* @author Rizwan Idrees
* @author Mohsin Husen
@@ -116,9 +100,7 @@ import org.springframework.test.util.ReflectionTestUtils;
* @author Farid Azaza
* @author Gyula Attila Csorogi
*/
@RunWith(SpringRunner.class)
@ContextConfiguration("classpath:elasticsearch-template-test.xml")
public class ElasticsearchTemplateTests {
public abstract class ElasticsearchTemplateTests {
private static final String INDEX_NAME_SAMPLE_ENTITY = "test-index-sample-core-template";
private static final String INDEX_1_NAME = "test-index-1";
@@ -126,32 +108,6 @@ public class ElasticsearchTemplateTests {
private static final String INDEX_3_NAME = "test-index-3";
private static final String TYPE_NAME = "test-type";
private final SearchResultMapper searchResultMapper = new SearchResultMapperAdapter() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> result = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
if (response.getHits().getHits().length <= 0) {
return new AggregatedPageImpl<T>(Collections.emptyList(), response.getScrollId());
}
String message = (String) searchHit.getSourceAsMap().get("message");
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(searchHit.getId());
sampleEntity.setMessage(message);
result.add(sampleEntity);
}
if (result.size() > 0) {
return new AggregatedPageImpl<T>((List<T>) result, response.getScrollId());
}
return new AggregatedPageImpl<T>(Collections.emptyList(), response.getScrollId());
}
};
@Autowired protected ElasticsearchOperations elasticsearchTemplate;
@Before
@@ -296,21 +252,7 @@ public class ElasticsearchTemplateTests {
// when
SearchQuery query = new NativeSearchQueryBuilder().withIds(Arrays.asList(documentId, documentId2))
.withFields("message", "type").build();
List<SampleEntity> sampleEntities = elasticsearchTemplate.multiGet(query, SampleEntity.class,
new MultiGetResultMapper() {
@Override
public <T> LinkedList<T> mapResults(MultiGetResponse responses, Class<T> clazz) {
LinkedList<T> list = new LinkedList<>();
for (MultiGetItemResponse response : responses.getResponses()) {
SampleEntity entity = new SampleEntity();
entity.setId(response.getResponse().getId());
entity.setMessage((String) response.getResponse().getSource().get("message"));
entity.setType((String) response.getResponse().getSource().get("type"));
list.add((T) entity);
}
return list;
}
});
List<SampleEntity> sampleEntities = elasticsearchTemplate.multiGet(query, SampleEntity.class);
// then
assertThat(sampleEntities).hasSize(2);
@@ -1012,8 +954,9 @@ public class ElasticsearchTemplateTests {
// given
String documentId = randomNumeric(5);
String message = "some test message";
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message(message)
.version(System.currentTimeMillis()).build();
String type = "some type";
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message(message).type(type)
.version(System.currentTimeMillis()).location(new GeoPoint(1.2, 3.4)).build();
IndexQuery indexQuery = getIndexQuery(sampleEntity);
@@ -1021,22 +964,17 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.refresh(SampleEntity.class);
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).withFields("message").build();
// when
Page<String> page = elasticsearchTemplate.queryForPage(searchQuery, String.class, new SearchResultMapperAdapter() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<String> values = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
values.add((String) searchHit.getSourceAsMap().get("message"));
}
return new AggregatedPageImpl<>((List<T>) values);
}
});
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
// then
assertThat(page).isNotNull();
assertThat(page.getTotalElements()).isEqualTo(1);
assertThat(page.getContent().get(0)).isEqualTo(message);
final SampleEntity actual = page.getContent().get(0);
assertThat(actual.message).isEqualTo(message);
assertThat(actual.getType()).isNull();
assertThat(actual.getLocation()).isNull();
}
@Test
@@ -1173,14 +1111,13 @@ public class ElasticsearchTemplateTests {
criteriaQuery.addFields("message");
criteriaQuery.setPageable(PageRequest.of(0, 10));
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(1000, criteriaQuery, SampleEntity.class,
searchResultMapper);
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(1000, criteriaQuery, SampleEntity.class);
String scrollId = scroll.getScrollId();
List<SampleEntity> sampleEntities = new ArrayList<>();
while (scroll.hasContent()) {
sampleEntities.addAll(scroll.getContent());
scrollId = scroll.getScrollId();
scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class, searchResultMapper);
scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class);
}
elasticsearchTemplate.clearScroll(scrollId);
assertThat(sampleEntities).hasSize(30);
@@ -1201,14 +1138,13 @@ public class ElasticsearchTemplateTests {
.withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).withFields("message").withQuery(matchAllQuery())
.withPageable(PageRequest.of(0, 10)).build();
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(1000, searchQuery, SampleEntity.class,
searchResultMapper);
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(1000, searchQuery, SampleEntity.class);
String scrollId = scroll.getScrollId();
List<SampleEntity> sampleEntities = new ArrayList<>();
while (scroll.hasContent()) {
sampleEntities.addAll(scroll.getContent());
scrollId = scroll.getScrollId();
scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class, searchResultMapper);
scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class);
}
elasticsearchTemplate.clearScroll(scrollId);
assertThat(sampleEntities).hasSize(30);
@@ -1230,14 +1166,13 @@ public class ElasticsearchTemplateTests {
criteriaQuery.addTypes(TYPE_NAME);
criteriaQuery.setPageable(PageRequest.of(0, 10));
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(1000, criteriaQuery, SampleEntity.class,
searchResultMapper);
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(1000, criteriaQuery, SampleEntity.class);
String scrollId = scroll.getScrollId();
List<SampleEntity> sampleEntities = new ArrayList<>();
while (scroll.hasContent()) {
sampleEntities.addAll(scroll.getContent());
scrollId = scroll.getScrollId();
scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class, searchResultMapper);
scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class);
}
elasticsearchTemplate.clearScroll(scrollId);
assertThat(sampleEntities).hasSize(30);
@@ -1257,14 +1192,13 @@ public class ElasticsearchTemplateTests {
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).withPageable(PageRequest.of(0, 10)).build();
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(1000, searchQuery, SampleEntity.class,
searchResultMapper);
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(1000, searchQuery, SampleEntity.class);
String scrollId = scroll.getScrollId();
List<SampleEntity> sampleEntities = new ArrayList<>();
while (scroll.hasContent()) {
sampleEntities.addAll(scroll.getContent());
scrollId = scroll.getScrollId();
scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class, searchResultMapper);
scroll = elasticsearchTemplate.continueScroll(scrollId, 1000, SampleEntity.class);
}
elasticsearchTemplate.clearScroll(scrollId);
assertThat(sampleEntities).hasSize(30);
@@ -1555,167 +1489,6 @@ public class ElasticsearchTemplateTests {
assertThat(indexedEntity.getMessage()).isEqualTo(message);
}
@Test
public void shouldReturnHighlightedFieldsForGivenQueryAndFields() {
// given
String documentId = randomNumeric(5);
String actualMessage = "some test message";
String highlightedMessage = "some <em>test</em> message";
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message(actualMessage)
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = getIndexQuery(sampleEntity);
// when
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class);
List<HighlightBuilder.Field> message = new HighlightBuilder().field("message").fields();
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test"))
.withHighlightFields(message.toArray(new HighlightBuilder.Field[message.size()])).build();
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class,
new SearchResultMapperAdapter() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> chunk = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
if (response.getHits().getHits().length <= 0) {
return null;
}
SampleEntity user = new SampleEntity();
user.setId(searchHit.getId());
user.setMessage((String) searchHit.getSourceAsMap().get("message"));
user.setHighlightedMessage(searchHit.getHighlightFields().get("message").fragments()[0].toString());
chunk.add(user);
}
if (chunk.size() > 0) {
return new AggregatedPageImpl<>((List<T>) chunk);
}
return null;
}
});
// then
assertThat(sampleEntities.getContent().get(0).getHighlightedMessage()).isEqualTo(highlightedMessage);
}
@Test // DATAES-412
public void shouldReturnMultipleHighlightFields() {
// given
String documentId = randomNumeric(5);
String actualType = "some test type";
String actualMessage = "some test message";
String highlightedType = "some <em>test</em> type";
String highlightedMessage = "some <em>test</em> message";
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).type(actualType).message(actualMessage)
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = getIndexQuery(sampleEntity);
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class);
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(boolQuery().must(termQuery("type", "test")).must(termQuery("message", "test")))
.withHighlightFields(new HighlightBuilder.Field("type"), new HighlightBuilder.Field("message")).build();
// when
elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapperAdapter() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
for (SearchHit searchHit : response.getHits()) {
Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
HighlightField highlightFieldType = highlightFields.get("type");
HighlightField highlightFieldMessage = highlightFields.get("message");
// then
assertThat(highlightFieldType).isNotNull();
assertThat(highlightFieldMessage).isNotNull();
assertThat(highlightFieldType.fragments()[0].toString()).isEqualTo(highlightedType);
assertThat(highlightFieldMessage.fragments()[0].toString()).isEqualTo(highlightedMessage);
}
return null;
}
});
}
@Test // DATAES-645
public void shouldReturnHighlightedFieldsInScroll() {
// given
long scrollTimeInMillis = 3000;
String documentId = randomNumeric(5);
String actualType = "some test type";
String actualMessage = "some test message";
String highlightedType = "some <em>test</em> type";
String highlightedMessage = "some <em>test</em> message";
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).type(actualType).message(actualMessage)
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = getIndexQuery(sampleEntity);
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class);
HighlightBuilder highlightBuilder = new HighlightBuilder().field("type").field("message");
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(boolQuery().must(termQuery("type", "test")).must(termQuery("message", "test")))
.withPageable(PageRequest.of(0, 10)).withHighlightBuilder(highlightBuilder).build();
SearchResultMapper searchResultMapper = new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
MappingElasticsearchConverter mappingElasticsearchConverter = new MappingElasticsearchConverter(
new SimpleElasticsearchMappingContext());
ArrayList<T> result = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
try {
result
.add((T) mappingElasticsearchConverter.mapToObject(searchHit.getSourceAsString(), SampleEntity.class));
} catch (IOException e) {
e.printStackTrace();
}
Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
HighlightField highlightFieldType = highlightFields.get("type");
HighlightField highlightFieldMessage = highlightFields.get("message");
// then
assertThat(highlightFieldType).isNotNull();
assertThat(highlightFieldMessage).isNotNull();
assertThat(highlightFieldType.fragments()[0].toString()).isEqualTo(highlightedType);
assertThat(highlightFieldMessage.fragments()[0].toString()).isEqualTo(highlightedMessage);
}
return new AggregatedPageImpl<T>(result, pageable, response.getHits().getTotalHits().value,
response.getAggregations(), response.getScrollId(), response.getHits().getMaxScore());
}
@Override
public <T> T mapSearchHit(SearchHit searchHit, Class<T> type) {
return null;
}
};
// when
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(scrollTimeInMillis, searchQuery,
SampleEntity.class, searchResultMapper);
while (scroll.hasContent()) {
scroll = elasticsearchTemplate.continueScroll(scroll.getScrollId(), scrollTimeInMillis, SampleEntity.class,
searchResultMapper);
}
elasticsearchTemplate.clearScroll(scroll.getScrollId());
}
@Test // DATAES-671
public void shouldPassIndicesOptionsForGivenSearchScrollQuery() {
@@ -1738,13 +1511,12 @@ public class ElasticsearchTemplateTests {
List<SampleEntity> entities = new ArrayList<>();
ScrolledPage<SampleEntity> scroll = elasticsearchTemplate.startScroll(scrollTimeInMillis, searchQuery,
SampleEntity.class, searchResultMapper);
SampleEntity.class);
entities.addAll(scroll.getContent());
while (scroll.hasContent()) {
scroll = elasticsearchTemplate.continueScroll(scroll.getScrollId(), scrollTimeInMillis, SampleEntity.class,
searchResultMapper);
scroll = elasticsearchTemplate.continueScroll(scroll.getScrollId(), scrollTimeInMillis, SampleEntity.class);
entities.addAll(scroll.getContent());
}
@@ -1754,84 +1526,6 @@ public class ElasticsearchTemplateTests {
assertThat(entities.size()).isGreaterThanOrEqualTo(1);
}
@Test // DATAES-479
public void shouldHonorTheHighlightBuilderOptions() {
// given
String documentId = randomNumeric(5);
String actualMessage = "some test message with <html> unsafe <script> text";
String highlightedMessage = "some <em>test</em> message with &lt;html&gt; unsafe &lt;script&gt; text";
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message(actualMessage)
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = getIndexQuery(sampleEntity);
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class);
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test"))
.withHighlightBuilder(new HighlightBuilder().encoder("html"))
.withHighlightFields(new HighlightBuilder.Field("message")).build();
// when
elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapperAdapter() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
for (SearchHit searchHit : response.getHits()) {
Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
HighlightField highlightFieldMessage = highlightFields.get("message");
// then
assertThat(highlightFieldMessage).isNotNull();
assertThat(highlightFieldMessage.fragments()[0].toString()).isEqualTo(highlightedMessage);
}
return null;
}
});
}
@Test // DATAES-479
public void shouldHighlightIfBuilderSetEvenIfFieldsNotSet() {
// given
String documentId = randomNumeric(5);
String actualMessage = "some test message text";
String highlightedMessage = "some <em>test</em> message text";
SampleEntity sampleEntity = SampleEntity.builder().id(documentId).message(actualMessage)
.version(System.currentTimeMillis()).build();
IndexQuery indexQuery = getIndexQuery(sampleEntity);
elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class);
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test"))
.withHighlightBuilder(new HighlightBuilder().field("message")).build();
// when
elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class, new SearchResultMapper() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
for (SearchHit searchHit : response.getHits()) {
Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
HighlightField highlightFieldMessage = highlightFields.get("message");
// then
assertThat(highlightFieldMessage).isNotNull();
assertThat(highlightFieldMessage.fragments()[0].toString()).isEqualTo(highlightedMessage);
}
return null;
}
@Override
public <T> T mapSearchHit(SearchHit searchHit, Class<T> type) {
return null;
}
});
}
@Test // DATAES-487
public void shouldReturnSameEntityForMultiSearch() {
@@ -1939,20 +1633,7 @@ public class ElasticsearchTemplateTests {
.withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME).build();
// then
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class,
new SearchResultMapperAdapter() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<SampleEntity> values = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(searchHit.getId());
sampleEntity.setMessage((String) searchHit.getSourceAsMap().get("message"));
values.add(sampleEntity);
}
return new AggregatedPageImpl<>((List<T>) values);
}
});
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
assertThat(page).isNotNull();
assertThat(page.getContent()).hasSize(1);
assertThat(page.getContent().get(0).getId()).isEqualTo(indexQuery.getId());
@@ -2136,29 +1817,7 @@ public class ElasticsearchTemplateTests {
// then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withIndices(INDEX_NAME_SAMPLE_ENTITY).withTypes(TYPE_NAME)
.withQuery(matchAllQuery()).build();
Page<Map> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, Map.class,
new SearchResultMapperAdapter() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<Map> chunk = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
if (response.getHits().getHits().length <= 0) {
return null;
}
Map<String, Object> person = new HashMap<>();
person.put("userId", searchHit.getSourceAsMap().get("userId"));
person.put("email", searchHit.getSourceAsMap().get("email"));
person.put("title", searchHit.getSourceAsMap().get("title"));
person.put("firstName", searchHit.getSourceAsMap().get("firstName"));
person.put("lastName", searchHit.getSourceAsMap().get("lastName"));
chunk.add(person);
}
if (chunk.size() > 0) {
return new AggregatedPageImpl<>((List<T>) chunk);
}
return null;
}
});
Page<Map> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, Map.class);
assertThat(sampleEntities.getTotalElements()).isEqualTo(2);
List<Map> content = sampleEntities.getContent();
@@ -2636,24 +2295,7 @@ public class ElasticsearchTemplateTests {
// when
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withTypes("hetro")
.withIndices(INDEX_1_NAME, INDEX_2_NAME).build();
Page<ResultAggregator> page = elasticsearchTemplate.queryForPage(searchQuery, ResultAggregator.class,
new SearchResultMapperAdapter() {
@Override
public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {
List<ResultAggregator> values = new ArrayList<>();
for (SearchHit searchHit : response.getHits()) {
String id = String.valueOf(searchHit.getSourceAsMap().get("id"));
String firstName = StringUtils.isNotEmpty((String) searchHit.getSourceAsMap().get("firstName"))
? (String) searchHit.getSourceAsMap().get("firstName")
: "";
String lastName = StringUtils.isNotEmpty((String) searchHit.getSourceAsMap().get("lastName"))
? (String) searchHit.getSourceAsMap().get("lastName")
: "";
values.add(new ResultAggregator(id, firstName, lastName));
}
return new AggregatedPageImpl<>((List<T>) values);
}
});
Page<ResultAggregator> page = elasticsearchTemplate.queryForPage(searchQuery, ResultAggregator.class);
assertThat(page.getTotalElements()).isEqualTo(2);
}

View File

@@ -24,7 +24,6 @@ import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
@@ -46,15 +45,12 @@ 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;
import org.springframework.data.elasticsearch.junit.junit4.ElasticsearchVersion;
import org.springframework.data.elasticsearch.junit.junit4.ElasticsearchVersionRule;
import org.springframework.data.elasticsearch.TestUtils;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
@@ -66,6 +62,8 @@ 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.junit.junit4.ElasticsearchVersion;
import org.springframework.data.elasticsearch.junit.junit4.ElasticsearchVersionRule;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StringUtils;
@@ -102,9 +100,7 @@ public class ReactiveElasticsearchTemplateTests {
restTemplate.putMapping(SampleEntity.class);
restTemplate.refresh(SampleEntity.class);
template = new ReactiveElasticsearchTemplate(TestUtils.reactiveClient(), restTemplate.getElasticsearchConverter(),
new DefaultResultMapper(new MappingElasticsearchConverter(
restTemplate.getElasticsearchConverter().getMappingContext(), new DefaultConversionService())));
template = new ReactiveElasticsearchTemplate(TestUtils.reactiveClient(), restTemplate.getElasticsearchConverter());
}
@After

View File

@@ -36,9 +36,8 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
@@ -48,8 +47,8 @@ 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.Document;
import org.springframework.data.elasticsearch.annotations.GeoPointField;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
import org.springframework.data.geo.Box;
@@ -95,7 +94,7 @@ public class MappingElasticsearchConverterUnitTests {
Document shotGunAsMap;
Document bigBunsCafeAsMap;
@Before
@BeforeEach
public void init() {
SimpleElasticsearchMappingContext mappingContext = new SimpleElasticsearchMappingContext();
@@ -126,7 +125,8 @@ public class MappingElasticsearchConverterUnitTests {
t800AsMap.put("id", "t800");
t800AsMap.put("name", "T-800");
t800AsMap.put("gender", "MACHINE");
t800AsMap.put("_class", "org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverterUnitTests$Person");
t800AsMap.put("_class",
"org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverterUnitTests$Person");
observatoryRoad = new Address();
observatoryRoad.city = "Los Angeles";
@@ -143,7 +143,8 @@ public class MappingElasticsearchConverterUnitTests {
sarahAsMap.put("id", "sarah");
sarahAsMap.put("name", "Sarah Connor");
sarahAsMap.put("gender", "MAN");
sarahAsMap.put("_class", "org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverterUnitTests$Person");
sarahAsMap.put("_class",
"org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverterUnitTests$Person");
kyleAsMap = Document.create();
kyleAsMap.put("id", "kyle");
@@ -189,46 +190,48 @@ public class MappingElasticsearchConverterUnitTests {
shotGunAsMap.put("_class", ShotGun.class.getName());
}
@Test
public void shouldFailToInitializeGivenMappingContextIsNull() {
@Test(expected = IllegalArgumentException.class)
public void shouldFailToInitializeGivenMappingContextIsNull() {
// given
assertThatThrownBy(() -> {
new MappingElasticsearchConverter(null);
}).isInstanceOf(IllegalArgumentException.class);
}
// given
new MappingElasticsearchConverter(null);
}
@Test
public void shouldReturnMappingContextWithWhichItWasInitialized() {
@Test
public void shouldReturnMappingContextWithWhichItWasInitialized() {
// given
MappingContext mappingContext = new SimpleElasticsearchMappingContext();
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(mappingContext);
// given
MappingContext mappingContext = new SimpleElasticsearchMappingContext();
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(mappingContext);
// then
assertThat(converter.getMappingContext()).isNotNull();
assertThat(converter.getMappingContext()).isSameAs(mappingContext);
}
// then
assertThat(converter.getMappingContext()).isNotNull();
assertThat(converter.getMappingContext()).isSameAs(mappingContext);
}
@Test
public void shouldReturnDefaultConversionService() {
@Test
public void shouldReturnDefaultConversionService() {
// given
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(
new SimpleElasticsearchMappingContext());
// given
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(
new SimpleElasticsearchMappingContext());
// when
ConversionService conversionService = converter.getConversionService();
// when
ConversionService conversionService = converter.getConversionService();
// then
assertThat(conversionService).isNotNull();
}
// then
assertThat(conversionService).isNotNull();
}
@Test // DATAES-530
@Test // DATAES-530
public void shouldMapObjectToJsonString() throws IOException {
// Given
// When
String jsonResult = mappingElasticsearchConverter.mapToString(Car.builder().model(CAR_MODEL).name(CAR_NAME).build());
String jsonResult = mappingElasticsearchConverter.mapObject(Car.builder().model(CAR_MODEL).name(CAR_NAME).build())
.toJson();
// Then
assertThat(jsonResult).isEqualTo(JSON_STRING);
@@ -239,9 +242,10 @@ public class MappingElasticsearchConverterUnitTests {
// Given
// When
Car result = mappingElasticsearchConverter.mapToObject(JSON_STRING, Car.class);
Car result = mappingElasticsearchConverter.mapDocument(Document.parse(JSON_STRING), Car.class);
// Then
assertThat(result).isNotNull();
assertThat(result.getName()).isEqualTo(CAR_NAME);
assertThat(result.getModel()).isEqualTo(CAR_MODEL);
}
@@ -255,7 +259,7 @@ public class MappingElasticsearchConverterUnitTests {
GeoEntity geoEntity = GeoEntity.builder().pointA(point).pointB(GeoPoint.fromPoint(point)).pointC(pointAsString)
.pointD(pointAsArray).build();
// when
String jsonResult = mappingElasticsearchConverter.mapToString(geoEntity);
String jsonResult = mappingElasticsearchConverter.mapObject(geoEntity).toJson();
// then
assertThat(jsonResult).contains(pointTemplate("pointA", point));
@@ -276,7 +280,7 @@ public class MappingElasticsearchConverterUnitTests {
sample.annotatedTransientProperty = "transient";
// when
String result = mappingElasticsearchConverter.mapToString(sample);
String result = mappingElasticsearchConverter.mapObject(sample).toJson();
// then
assertThat(result).contains("\"property\"");
@@ -736,8 +740,7 @@ public class MappingElasticsearchConverterUnitTests {
@AllArgsConstructor
@Builder
@org.springframework.data.elasticsearch.annotations.Document(indexName = "test-index-geo-core-entity-mapper",
type = "geo-test-index", shards = 1, replicas = 0,
refreshInterval = "-1")
type = "geo-test-index", shards = 1, replicas = 0, refreshInterval = "-1")
static class GeoEntity {
@Id private String id;

View File

@@ -16,13 +16,11 @@
package org.springframework.data.elasticsearch.junit.jupiter;
import org.elasticsearch.client.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.ElasticsearchConfigurationSupport;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter;
import org.springframework.util.Assert;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
/**
* Configuration for Spring Data Elasticsearch using
@@ -35,13 +33,13 @@ public class ElasticsearchTemplateConfiguration extends ElasticsearchConfigurati
@Bean
public Client elasticsearchClient(ClusterConnectionInfo clusterConnectionInfo) {
return clusterConnectionInfo.getClient();
return clusterConnectionInfo.getClient();
}
@Bean(name = { "elasticsearchOperations", "elasticsearchTemplate" })
public ElasticsearchTemplate elasticsearchTemplate(Client elasticsearchClient,
MappingElasticsearchConverter entityMapper) {
return new ElasticsearchTemplate(elasticsearchClient, entityMapper);
ElasticsearchConverter elasticsearchConverter) {
return new ElasticsearchTemplate(elasticsearchClient, elasticsearchConverter);
}
}

View File

@@ -39,12 +39,12 @@ import org.springframework.data.repository.core.support.DefaultRepositoryMetadat
@RunWith(MockitoJUnitRunner.class)
public class ElasticsearchRepositoryFactoryTests {
@Mock private ElasticsearchOperations operations;
@Mock private ElasticsearchOperations operations;
private ElasticsearchRepositoryFactory factory;
@Before
public void before() {
ElasticsearchConverter converter = new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext());
ElasticsearchConverter converter = new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext());
when(operations.getElasticsearchConverter()).thenReturn(converter);
factory = new ElasticsearchRepositoryFactory(operations);
}