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> <parent>
<groupId>com.baeldung</groupId> <groupId>com.baeldung</groupId>
<artifactId>parent-spring-4</artifactId> <artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-4</relativePath> <relativePath>../parent-spring-5</relativePath>
</parent> </parent>
<dependencies> <dependencies>
@ -19,50 +19,20 @@
<groupId>org.springframework</groupId> <groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId> <artifactId>spring-core</artifactId>
<version>${spring.version}</version> <version>${spring.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.data</groupId> <groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId> <artifactId>spring-data-elasticsearch</artifactId>
<version>${spring-data-elasticsearch.version}</version> <version>${spring-data-elasticsearch.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>${spatial4j.version}</version>
</dependency>
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts</artifactId>
<version>${jts.version}</version>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</exclusions>
</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> <dependency>
<groupId>org.elasticsearch</groupId> <groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId> <artifactId>elasticsearch</artifactId>
@ -73,17 +43,62 @@
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>
<version>${fastjson.version}</version> <version>${fastjson.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.locationtech.spatial4j</groupId>
<artifactId>spatial4j</artifactId>
<version>${spatial4j.version}</version>
</dependency>
<dependency>
<groupId>com.vividsolutions</groupId>
<artifactId>jts</artifactId>
<version>${jts.version}</version>
<exclusions>
<exclusion>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
</exclusion>
</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>
</dependencies> </dependencies>
<properties> <properties>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<spring-data-elasticsearch.version>2.0.5.RELEASE</spring-data-elasticsearch.version> <spring-data-elasticsearch.version>3.0.8.RELEASE</spring-data-elasticsearch.version>
<jna.version>4.2.2</jna.version> <jna.version>4.5.2</jna.version>
<elasticsearch.version>2.4.2</elasticsearch.version> <elasticsearch.version>5.6.0</elasticsearch.version>
<fastjson.version>1.2.21</fastjson.version> <fastjson.version>1.2.47</fastjson.version>
<spatial4j.version>0.4.1</spatial4j.version> <spatial4j.version>0.6</spatial4j.version>
<jts.version>1.13</jts.version> <jts.version>1.13</jts.version>
<log4j.version>2.9.1</log4j.version>
</properties> </properties>
</project> </project>

View File

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

View File

@ -1,8 +1,8 @@
package com.baeldung.spring.data.es.model; 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.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.Arrays;
import java.util.List; import java.util.List;
@ -19,13 +19,13 @@ public class Article {
@Id @Id
private String 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; private String title;
@Field(type = Nested) @Field(type = Nested, includeInParent = true)
private List<Author> authors; private List<Author> authors;
@Field(type = String, index = not_analyzed) @Field(type = Keyword)
private String[] tags; private String[] tags;
public Article() { public Article() {

View File

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

View File

@ -1,5 +1,7 @@
package com.baeldung.spring.data.es.service; package com.baeldung.spring.data.es.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
@ -24,8 +26,8 @@ public class ArticleServiceImpl implements ArticleService {
} }
@Override @Override
public Article findOne(String id) { public Optional<Article> findOne(String id) {
return articleRepository.findOne(id); return articleRepository.findById(id);
} }
@Override @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; package com.baeldung.elasticsearch;
import com.alibaba.fastjson.JSON; import static org.junit.Assert.assertEquals;
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 java.io.IOException; import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.elasticsearch.node.NodeBuilder.nodeBuilder; import org.elasticsearch.action.DocWriteResponse.Result;
import static org.junit.Assert.assertEquals; import org.elasticsearch.action.delete.DeleteResponse;
import static org.junit.Assert.assertTrue; 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 { public class ElasticSearchManualTest {
private List<Person> listOfPersons = new ArrayList<>(); private List<Person> listOfPersons = new ArrayList<>();
private Client client = null; private Client client = null;
@Before @Before
public void setUp() { public void setUp() throws UnknownHostException {
Person person1 = new Person(10, "John Doe", new Date()); Person person1 = new Person(10, "John Doe", new Date());
Person person2 = new Person(25, "Janette Doe", new Date()); Person person2 = new Person(25, "Janette Doe", new Date());
listOfPersons.add(person1); listOfPersons.add(person1);
listOfPersons.add(person2); listOfPersons.add(person2);
Node node = nodeBuilder()
.clusterName("elasticsearch") client = new PreBuiltTransportClient(Settings.builder().put("client.transport.sniff", true)
.client(true) .put("cluster.name","elasticsearch").build())
.node(); .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
client = node.client();
} }
@Test @Test
@ -47,11 +51,12 @@ public class ElasticSearchManualTest {
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}"; String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
IndexResponse response = client IndexResponse response = client
.prepareIndex("people", "Doe") .prepareIndex("people", "Doe")
.setSource(jsonObject) .setSource(jsonObject, XContentType.JSON)
.get(); .get();
String index = response.getIndex(); String index = response.getIndex();
String type = response.getType(); String type = response.getType();
assertTrue(response.isCreated());
assertEquals(Result.CREATED, response.getResult());
assertEquals(index, "people"); assertEquals(index, "people");
assertEquals(type, "Doe"); assertEquals(type, "Doe");
} }
@ -61,13 +66,14 @@ public class ElasticSearchManualTest {
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}"; String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
IndexResponse response = client IndexResponse response = client
.prepareIndex("people", "Doe") .prepareIndex("people", "Doe")
.setSource(jsonObject) .setSource(jsonObject, XContentType.JSON)
.get(); .get();
String id = response.getId(); String id = response.getId();
DeleteResponse deleteResponse = client DeleteResponse deleteResponse = client
.prepareDelete("people", "Doe", id) .prepareDelete("people", "Doe", id)
.get(); .get();
assertTrue(deleteResponse.isFound());
assertEquals(Result.DELETED,deleteResponse.getResult());
} }
@Test @Test
@ -142,6 +148,7 @@ public class ElasticSearchManualTest {
.prepareIndex("people", "Doe") .prepareIndex("people", "Doe")
.setSource(builder) .setSource(builder)
.get(); .get();
assertTrue(response.isCreated());
assertEquals(Result.CREATED, response.getResult());
} }
} }

View File

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

View File

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

View File

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