update spring data elasticsearch

This commit is contained in:
DOHA 2018-07-28 02:27:47 +03:00
parent 387b92b09a
commit bac0c0714c
11 changed files with 208 additions and 194 deletions

View File

@ -9,9 +9,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-spring-4</artifactId>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-4</relativePath>
<relativePath>../parent-spring-5</relativePath>
</parent>
<dependencies>
@ -19,13 +19,14 @@
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
@ -33,7 +34,18 @@
</dependency>
<dependency>
<groupId>com.spatial4j</groupId>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.locationtech.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>${spatial4j.version}</version>
</dependency>
@ -50,40 +62,43 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>${jna.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring-data-elasticsearch.version>2.0.5.RELEASE</spring-data-elasticsearch.version>
<jna.version>4.2.2</jna.version>
<elasticsearch.version>2.4.2</elasticsearch.version>
<fastjson.version>1.2.21</fastjson.version>
<spatial4j.version>0.4.1</spatial4j.version>
<spring-data-elasticsearch.version>3.0.8.RELEASE</spring-data-elasticsearch.version>
<jna.version>4.5.2</jna.version>
<elasticsearch.version>5.6.0</elasticsearch.version>
<fastjson.version>1.2.47</fastjson.version>
<spatial4j.version>0.6</spatial4j.version>
<jts.version>1.13</jts.version>
<log4j.version>2.9.1</log4j.version>
</properties>
</project>

View File

@ -1,15 +1,13 @@
package com.baeldung.spring.data.es.config;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.NodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@ -23,35 +21,26 @@ import org.springframework.data.elasticsearch.repository.config.EnableElasticsea
@ComponentScan(basePackages = { "com.baeldung.spring.data.es.service" })
public class Config {
@Value("${elasticsearch.home:/usr/local/Cellar/elasticsearch/2.3.2}")
@Value("${elasticsearch.home:/usr/local/Cellar/elasticsearch/5.6.0}")
private String elasticsearchHome;
private static Logger logger = LoggerFactory.getLogger(Config.class);
@Value("${elasticsearch.cluster.name:elasticsearch}")
private String clusterName;
@Bean
public Client client() {
TransportClient client = null;
try {
final Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data");
logger.debug(tmpDir.toAbsolutePath().toString());
// @formatter:off
final Settings.Builder elasticsearchSettings =
Settings.settingsBuilder().put("http.enabled", "false")
.put("path.data", tmpDir.toAbsolutePath().toString())
.put("path.home", elasticsearchHome);
return new NodeBuilder()
.local(true)
.settings(elasticsearchSettings)
.node()
.client();
// @formatter:on
} catch (final IOException ioex) {
logger.error("Cannot create temp dir", ioex);
throw new RuntimeException();
final Settings elasticsearchSettings = Settings.builder()
.put("client.transport.sniff", true)
.put("path.home", elasticsearchHome)
.put("cluster.name", clusterName).build();
client = new PreBuiltTransportClient(elasticsearchSettings);
client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
} catch (UnknownHostException e) {
e.printStackTrace();
}
return client;
}
@Bean

View File

@ -1,8 +1,8 @@
package com.baeldung.spring.data.es.model;
import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed;
import static org.springframework.data.elasticsearch.annotations.FieldType.Keyword;
import static org.springframework.data.elasticsearch.annotations.FieldType.Nested;
import static org.springframework.data.elasticsearch.annotations.FieldType.String;
import static org.springframework.data.elasticsearch.annotations.FieldType.Text;
import java.util.Arrays;
import java.util.List;
@ -19,13 +19,13 @@ public class Article {
@Id
private String id;
@MultiField(mainField = @Field(type = String), otherFields = { @InnerField(index = not_analyzed, suffix = "verbatim", type = String) })
@MultiField(mainField = @Field(type = Text, fielddata = true), otherFields = { @InnerField(suffix = "verbatim", type = Keyword) })
private String title;
@Field(type = Nested)
@Field(type = Nested, includeInParent = true)
private List<Author> authors;
@Field(type = String, index = not_analyzed)
@Field(type = Keyword)
private String[] tags;
public Article() {

View File

@ -1,5 +1,7 @@
package com.baeldung.spring.data.es.service;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@ -8,7 +10,7 @@ import com.baeldung.spring.data.es.model.Article;
public interface ArticleService {
Article save(Article article);
Article findOne(String id);
Optional<Article> findOne(String id);
Iterable<Article> findAll();

View File

@ -1,5 +1,7 @@
package com.baeldung.spring.data.es.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
@ -24,8 +26,8 @@ public class ArticleServiceImpl implements ArticleService {
}
@Override
public Article findOne(String id) {
return articleRepository.findOne(id);
public Optional<Article> findOne(String id) {
return articleRepository.findById(id);
}
@Override

View File

@ -0,0 +1,6 @@
appender.console.type = Console
appender.console.name = console
appender.console.layout.type = PatternLayout
rootLogger.level = info
rootLogger.appenderRef.console.ref = console

View File

@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,45 +1,49 @@
package com.baeldung.elasticsearch;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.node.Node;
import org.elasticsearch.search.SearchHit;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.elasticsearch.action.DocWriteResponse.Result;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.Before;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
public class ElasticSearchManualTest {
private List<Person> listOfPersons = new ArrayList<>();
private Client client = null;
@Before
public void setUp() {
public void setUp() throws UnknownHostException {
Person person1 = new Person(10, "John Doe", new Date());
Person person2 = new Person(25, "Janette Doe", new Date());
listOfPersons.add(person1);
listOfPersons.add(person2);
Node node = nodeBuilder()
.clusterName("elasticsearch")
.client(true)
.node();
client = node.client();
client = new PreBuiltTransportClient(Settings.builder().put("client.transport.sniff", true)
.put("cluster.name","elasticsearch").build())
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
}
@Test
@ -47,11 +51,12 @@ public class ElasticSearchManualTest {
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
IndexResponse response = client
.prepareIndex("people", "Doe")
.setSource(jsonObject)
.setSource(jsonObject, XContentType.JSON)
.get();
String index = response.getIndex();
String type = response.getType();
assertTrue(response.isCreated());
assertEquals(Result.CREATED, response.getResult());
assertEquals(index, "people");
assertEquals(type, "Doe");
}
@ -61,13 +66,14 @@ public class ElasticSearchManualTest {
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
IndexResponse response = client
.prepareIndex("people", "Doe")
.setSource(jsonObject)
.setSource(jsonObject, XContentType.JSON)
.get();
String id = response.getId();
DeleteResponse deleteResponse = client
.prepareDelete("people", "Doe", id)
.get();
assertTrue(deleteResponse.isFound());
assertEquals(Result.DELETED,deleteResponse.getResult());
}
@Test
@ -142,6 +148,7 @@ public class ElasticSearchManualTest {
.prepareIndex("people", "Doe")
.setSource(builder)
.get();
assertTrue(response.isCreated());
assertEquals(Result.CREATED, response.getResult());
}
}

View File

@ -1,13 +1,21 @@
package com.baeldung.elasticsearch;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import com.baeldung.spring.data.es.config.Config;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.geo.ShapeRelation;
import org.elasticsearch.common.geo.builders.ShapeBuilder;
import org.elasticsearch.common.geo.builders.ShapeBuilders;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
@ -20,11 +28,8 @@ import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.Assert.assertTrue;
import com.baeldung.spring.data.es.config.Config;
import com.vividsolutions.jts.geom.Coordinate;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
@ -43,7 +48,7 @@ public class GeoQueriesIntegrationTest {
public void setUp() {
String jsonObject = "{\"Wonders\":{\"properties\":{\"name\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"region\":{\"type\":\"geo_shape\",\"tree\":\"quadtree\",\"precision\":\"1m\"},\"location\":{\"type\":\"geo_point\"}}}}";
CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD);
req.mapping(WONDERS, jsonObject);
req.mapping(WONDERS, jsonObject, XContentType.JSON);
client.admin()
.indices()
.create(req)
@ -51,31 +56,36 @@ public class GeoQueriesIntegrationTest {
}
@Test
public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() {
String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,25],[80.1,30.2]]}}";
public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() throws IOException{
String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,30.2],[80.1, 25]]}}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
.setSource(jsonObject)
.setSource(jsonObject, XContentType.JSON)
.get();
String tajMahalId = response.getId();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
QueryBuilder qb = QueryBuilders.geoShapeQuery("region", ShapeBuilder.newEnvelope()
.topLeft(74.00, 24.0)
.bottomRight(81.1, 31.2))
Coordinate topLeft =new Coordinate(74, 31.2);
Coordinate bottomRight =new Coordinate(81.1, 24);
QueryBuilder qb = QueryBuilders
.geoShapeQuery("region", ShapeBuilders.newEnvelope(topLeft, bottomRight))
.relation(ShapeRelation.WITHIN);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
.setTypes(WONDERS)
.setQuery(qb)
.execute()
.actionGet();
List<String> ids = Arrays.stream(searchResponse.getHits()
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
assertTrue(ids.contains(tajMahalId));
}
@ -83,7 +93,7 @@ public class GeoQueriesIntegrationTest {
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() {
String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
.setSource(jsonObject)
.setSource(jsonObject, XContentType.JSON)
.get();
String pyramidsOfGizaId = response.getId();
client.admin()
@ -92,8 +102,7 @@ public class GeoQueriesIntegrationTest {
.get();
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location")
.bottomLeft(28, 30)
.topRight(31, 32);
.setCorners(31,30,28,32);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
.setTypes(WONDERS)
@ -111,7 +120,7 @@ public class GeoQueriesIntegrationTest {
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() {
String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
.setSource(jsonObject)
.setSource(jsonObject, XContentType.JSON)
.get();
String lighthouseOfAlexandriaId = response.getId();
client.admin()
@ -139,7 +148,7 @@ public class GeoQueriesIntegrationTest {
public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() {
String jsonObject = "{\"name\":\"The Great Rann of Kutch\",\"location\":[69.859741,23.733732]}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS)
.setSource(jsonObject)
.setSource(jsonObject, XContentType.JSON)
.get();
String greatRannOfKutchid = response.getId();
client.admin()
@ -147,10 +156,11 @@ public class GeoQueriesIntegrationTest {
.prepareRefresh(WONDERS_OF_WORLD)
.get();
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location")
.addPoint(22.733, 68.859)
.addPoint(24.733, 68.859)
.addPoint(23, 70.859);
List<GeoPoint> allPoints = new ArrayList<GeoPoint>();
allPoints.add(new GeoPoint(22.733, 68.859));
allPoints.add(new GeoPoint(24.733, 68.859));
allPoints.add(new GeoPoint(23, 70.859));
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location", allPoints);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
.setTypes(WONDERS)

View File

@ -1,9 +1,15 @@
package com.baeldung.spring.data.es;
import com.baeldung.spring.data.es.config.Config;
import com.baeldung.spring.data.es.model.Article;
import com.baeldung.spring.data.es.model.Author;
import com.baeldung.spring.data.es.service.ArticleService;
import static java.util.Arrays.asList;
import static org.elasticsearch.index.query.Operator.AND;
import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.regexpQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -16,15 +22,10 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static java.util.Arrays.asList;
import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.regexpQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.baeldung.spring.data.es.config.Config;
import com.baeldung.spring.data.es.model.Article;
import com.baeldung.spring.data.es.model.Author;
import com.baeldung.spring.data.es.service.ArticleService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
@ -81,25 +82,25 @@ public class ElasticSearchIntegrationTest {
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
final Page<Article> articleByAuthorName = articleService
.findByAuthorName(johnSmith.getName(), new PageRequest(0, 10));
.findByAuthorName(johnSmith.getName(), PageRequest.of(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements());
}
@Test
public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() {
final Page<Article> articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("Smith", new PageRequest(0, 10));
final Page<Article> articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("Smith", PageRequest.of(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements());
}
@Test
public void givenTagFilterQuery_whenSearchByTag_thenArticleIsFound() {
final Page<Article> articleByAuthorName = articleService.findByFilteredTagQuery("elasticsearch", new PageRequest(0, 10));
final Page<Article> articleByAuthorName = articleService.findByFilteredTagQuery("elasticsearch", PageRequest.of(0, 10));
assertEquals(3L, articleByAuthorName.getTotalElements());
}
@Test
public void givenTagFilterQuery_whenSearchByAuthorsName_thenArticleIsFound() {
final Page<Article> articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", new PageRequest(0, 10));
final Page<Article> articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", PageRequest.of(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements());
}
@ -125,7 +126,7 @@ public class ElasticSearchIntegrationTest {
article.setTitle(newTitle);
articleService.save(article);
assertEquals(newTitle, articleService.findOne(article.getId()).getTitle());
assertEquals(newTitle, articleService.findOne(article.getId()).get().getTitle());
}
@Test

View File

@ -1,9 +1,20 @@
package com.baeldung.spring.data.es;
import com.baeldung.spring.data.es.config.Config;
import com.baeldung.spring.data.es.model.Article;
import com.baeldung.spring.data.es.model.Author;
import com.baeldung.spring.data.es.service.ArticleService;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.elasticsearch.index.query.Operator.AND;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;
import static org.elasticsearch.index.query.QueryBuilders.nestedQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Map;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.Fuzziness;
@ -14,7 +25,7 @@ import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -25,20 +36,10 @@ import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery;
import static org.elasticsearch.index.query.QueryBuilders.nestedQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.junit.Assert.assertEquals;
import com.baeldung.spring.data.es.config.Config;
import com.baeldung.spring.data.es.model.Article;
import com.baeldung.spring.data.es.model.Author;
import com.baeldung.spring.data.es.service.ArticleService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
@ -124,7 +125,7 @@ public class ElasticSearchQueryIntegrationTest {
@Test
public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() {
final QueryBuilder builder = nestedQuery("authors", boolQuery().must(termQuery("authors.name", "smith")));
final QueryBuilder builder = nestedQuery("authors", boolQuery().must(termQuery("authors.name", "smith")), ScoreMode.None);
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
@ -134,7 +135,7 @@ public class ElasticSearchQueryIntegrationTest {
@Test
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() {
final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
.execute().actionGet();
@ -150,8 +151,8 @@ public class ElasticSearchQueryIntegrationTest {
@Test
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
.order(Terms.Order.aggregation("_count", false));
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
.order(Terms.Order.count(false));
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
.execute().actionGet();
@ -194,7 +195,7 @@ public class ElasticSearchQueryIntegrationTest {
@Test
public void givenBoolQuery_whenQueryByAuthorsName_thenFoundArticlesByThatAuthorAndFilteredTag() {
final QueryBuilder builder = boolQuery().must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe"))))
final QueryBuilder builder = boolQuery().must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe")), ScoreMode.None))
.filter(termQuery("tags", "elasticsearch"));
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)