fixed formatting according to eclipse formatter

This commit is contained in:
Mathieu Fortin 2020-05-19 19:21:51 -04:00
parent 1ed9c7db32
commit 40aa75eec1
6 changed files with 419 additions and 395 deletions

View File

@ -15,15 +15,18 @@ 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 {
@Bean @Bean
RestHighLevelClient client() { RestHighLevelClient client() {
ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo("localhost:9200").build(); ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("localhost:9200")
.build();
return RestClients.create(clientConfiguration).rest(); return RestClients.create(clientConfiguration)
} .rest();
}
@Bean @Bean
public ElasticsearchOperations elasticsearchTemplate() { public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchRestTemplate(client()); return new ElasticsearchRestTemplate(client());
} }
} }

View File

@ -8,11 +8,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.es.config.Config; import com.baeldung.spring.data.es.config.Config;
/** /**
* This Manual test requires: * This Manual test requires: Elasticsearch instance running on localhost:9200.
* Elasticsearch instance running on localhost:9200.
* *
* The following docker command can be used: * The following docker command can be used: docker run -d --name es761 -p
* docker run -d --name es761 -p 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.1 * 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.1
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class) @ContextConfiguration(classes = Config.class)

View File

@ -37,126 +37,137 @@ import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients; import org.springframework.data.elasticsearch.client.RestClients;
/** /**
* This Manual test requires: * This Manual test requires: Elasticsearch instance running on localhost:9200.
* Elasticsearch instance running on localhost:9200.
* *
* The following docker command can be used: * The following docker command can be used: docker run -d --name es761 -p
* docker run -d --name es761 -p 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.1 * 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.1
*/ */
public class ElasticSearchManualTest { public class ElasticSearchManualTest {
private List<Person> listOfPersons = new ArrayList<>(); private List<Person> listOfPersons = new ArrayList<>();
private RestHighLevelClient client = null; private RestHighLevelClient client = null;
@Before @Before
public void setUp() throws UnknownHostException { 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);
ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo("localhost:9200").build(); ClientConfiguration clientConfiguration = ClientConfiguration.builder()
client = RestClients.create(clientConfiguration).rest(); .connectedTo("localhost:9200")
} .build();
client = RestClients.create(clientConfiguration)
.rest();
}
@Test @Test
public void givenJsonString_whenJavaObject_thenIndexDocument() throws Exception { public void givenJsonString_whenJavaObject_thenIndexDocument() throws Exception {
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}"; String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
IndexRequest request = new IndexRequest("people"); IndexRequest request = new IndexRequest("people");
request.source(jsonObject, XContentType.JSON); request.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT); IndexResponse response = client.index(request, RequestOptions.DEFAULT);
String index = response.getIndex(); String index = response.getIndex();
long version = response.getVersion(); long version = response.getVersion();
assertEquals(Result.CREATED, response.getResult()); assertEquals(Result.CREATED, response.getResult());
assertEquals(1, version); assertEquals(1, version);
assertEquals("people", index); assertEquals("people", index);
} }
@Test @Test
public void givenDocumentId_whenJavaObject_thenDeleteDocument() throws Exception { public void givenDocumentId_whenJavaObject_thenDeleteDocument() throws Exception {
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}"; String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
IndexRequest indexRequest = new IndexRequest("people"); IndexRequest indexRequest = new IndexRequest("people");
indexRequest.source(jsonObject, XContentType.JSON); indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT); IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String id = response.getId(); String id = response.getId();
GetRequest getRequest = new GetRequest("people"); GetRequest getRequest = new GetRequest("people");
getRequest.id(id); getRequest.id(id);
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT); GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString()); System.out.println(getResponse.getSourceAsString());
DeleteRequest deleteRequest = new DeleteRequest("people"); DeleteRequest deleteRequest = new DeleteRequest("people");
deleteRequest.id(id); deleteRequest.id(id);
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT); DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
assertEquals(Result.DELETED, deleteResponse.getResult()); assertEquals(Result.DELETED, deleteResponse.getResult());
} }
@Test @Test
public void givenSearchRequest_whenMatchAll_thenReturnAllResults() throws Exception { public void givenSearchRequest_whenMatchAll_thenReturnAllResults() throws Exception {
SearchRequest searchRequest = new SearchRequest(); SearchRequest searchRequest = new SearchRequest();
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = response.getHits().getHits(); SearchHit[] searchHits = response.getHits()
List<Person> results = Arrays.stream(searchHits).map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class)) .getHits();
.collect(Collectors.toList()); List<Person> results = Arrays.stream(searchHits)
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
.collect(Collectors.toList());
results.forEach(System.out::println); results.forEach(System.out::println);
} }
@Test @Test
public void givenSearchParameters_thenReturnResults() throws Exception { public void givenSearchParameters_thenReturnResults() throws Exception {
SearchSourceBuilder builder = SearchSourceBuilder builder = new SearchSourceBuilder().postFilter(QueryBuilders.rangeQuery("age")
new SearchSourceBuilder().postFilter(QueryBuilders.rangeQuery("age").from(5).to(15)); .from(5)
.to(15));
SearchRequest searchRequest = new SearchRequest(); SearchRequest searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH); searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder); searchRequest.source(builder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
builder = new SearchSourceBuilder().postFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette")); builder = new SearchSourceBuilder().postFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette"));
searchRequest = new SearchRequest(); searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH); searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder); searchRequest.source(builder);
SearchResponse response2 = client.search(searchRequest, RequestOptions.DEFAULT); SearchResponse response2 = client.search(searchRequest, RequestOptions.DEFAULT);
builder = new SearchSourceBuilder().postFilter(QueryBuilders.matchQuery("John", "Name*")); builder = new SearchSourceBuilder().postFilter(QueryBuilders.matchQuery("John", "Name*"));
searchRequest = new SearchRequest(); searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH); searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder); searchRequest.source(builder);
SearchResponse response3 = client.search(searchRequest, RequestOptions.DEFAULT); SearchResponse response3 = client.search(searchRequest, RequestOptions.DEFAULT);
response2.getHits(); response2.getHits();
response3.getHits(); response3.getHits();
final List<Person> results = final List<Person> results = Stream.of(response.getHits()
Stream.of(response.getHits().getHits(), .getHits(),
response2.getHits().getHits(), response2.getHits()
response3.getHits().getHits()) .getHits(),
.flatMap(Arrays::stream) response3.getHits()
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class)) .getHits())
.collect(Collectors.toList()); .flatMap(Arrays::stream)
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
.collect(Collectors.toList());
results.forEach(System.out::println); results.forEach(System.out::println);
} }
@Test @Test
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException { public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("fullName", "Test") XContentBuilder builder = XContentFactory.jsonBuilder()
.field("salary", "11500").field("age", "10").endObject(); .startObject()
.field("fullName", "Test")
.field("salary", "11500")
.field("age", "10")
.endObject();
IndexRequest indexRequest = new IndexRequest("people"); IndexRequest indexRequest = new IndexRequest("people");
indexRequest.source(builder); indexRequest.source(builder);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT); IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
assertEquals(Result.CREATED, response.getResult()); assertEquals(Result.CREATED, response.getResult());
} }
} }

View File

@ -39,150 +39,162 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** /**
* This Manual test requires: * This Manual test requires: Elasticsearch instance running on localhost:9200.
* Elasticsearch instance running on localhost:9200.
* *
* The following docker command can be used: * The following docker command can be used: docker run -d --name es761 -p
* docker run -d --name es761 -p 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.1 * 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.1
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class) @ContextConfiguration(classes = Config.class)
public class GeoQueriesManualTest { public class GeoQueriesManualTest {
private static final String WONDERS_OF_WORLD = "wonders-of-world"; private static final String WONDERS_OF_WORLD = "wonders-of-world";
@Autowired @Autowired
private RestHighLevelClient client; private RestHighLevelClient client;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
String jsonObject = "{\"properties\":{\"name\":{\"type\":\"text\",\"index\":false},\"region\":{\"type\":\"geo_shape\"},\"location\":{\"type\":\"geo_point\"}}}"; String jsonObject = "{\"properties\":{\"name\":{\"type\":\"text\",\"index\":false},\"region\":{\"type\":\"geo_shape\"},\"location\":{\"type\":\"geo_point\"}}}";
CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD); CreateIndexRequest req = new CreateIndexRequest(WONDERS_OF_WORLD);
req.mapping(jsonObject, XContentType.JSON); req.mapping(jsonObject, XContentType.JSON);
client.indices().create(req, RequestOptions.DEFAULT); client.indices()
} .create(req, RequestOptions.DEFAULT);
}
@Test @Test
public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() throws IOException { public void givenGeoShapeData_whenExecutedGeoShapeQuery_thenResultNonEmpty() throws IOException {
String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,30.2],[80.1, 25]]}}"; String jsonObject = "{\"name\":\"Agra\",\"region\":{\"type\":\"envelope\",\"coordinates\":[[75,30.2],[80.1, 25]]}}";
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD); IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
indexRequest.source(jsonObject, XContentType.JSON); indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT); IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String tajMahalId = response.getId(); String tajMahalId = response.getId();
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD); RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
client.indices().refresh(refreshRequest, RequestOptions.DEFAULT); client.indices()
.refresh(refreshRequest, RequestOptions.DEFAULT);
Coordinate topLeft = new Coordinate(74, 31.2); Coordinate topLeft = new Coordinate(74, 31.2);
Coordinate bottomRight = new Coordinate(81.1, 24); Coordinate bottomRight = new Coordinate(81.1, 24);
GeoShapeQueryBuilder qb = QueryBuilders.geoShapeQuery("region", GeoShapeQueryBuilder qb = QueryBuilders.geoShapeQuery("region", new EnvelopeBuilder(topLeft, bottomRight).buildGeometry());
new EnvelopeBuilder(topLeft, bottomRight).buildGeometry()); qb.relation(ShapeRelation.INTERSECTS);
qb.relation(ShapeRelation.INTERSECTS);
SearchSourceBuilder source = new SearchSourceBuilder().query(qb); SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD); SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
searchRequest.source(source); searchRequest.source(source);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
List<String> ids = Arrays.stream(searchResponse.getHits().getHits()).map(SearchHit::getId) List<String> ids = Arrays.stream(searchResponse.getHits()
.collect(Collectors.toList()); .getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
assertTrue(ids.contains(tajMahalId)); assertTrue(ids.contains(tajMahalId));
} }
@Test @Test
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() throws Exception { public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() throws Exception {
String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}"; String jsonObject = "{\"name\":\"Pyramids of Giza\",\"location\":[31.131302,29.976480]}";
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD); IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
indexRequest.source(jsonObject, XContentType.JSON); indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT); IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String pyramidsOfGizaId = response.getId(); String pyramidsOfGizaId = response.getId();
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD); RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
client.indices().refresh(refreshRequest, RequestOptions.DEFAULT); client.indices()
.refresh(refreshRequest, RequestOptions.DEFAULT);
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location").setCorners(31, 30, 28, 32); QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location")
.setCorners(31, 30, 28, 32);
SearchSourceBuilder source = new SearchSourceBuilder().query(qb); SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD); SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
searchRequest.source(source); searchRequest.source(source);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
List<String> ids = Arrays.stream(searchResponse.getHits().getHits()).map(SearchHit::getId) List<String> ids = Arrays.stream(searchResponse.getHits()
.collect(Collectors.toList()); .getHits())
assertTrue(ids.contains(pyramidsOfGizaId)); .map(SearchHit::getId)
} .collect(Collectors.toList());
assertTrue(ids.contains(pyramidsOfGizaId));
}
@Test @Test
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() throws Exception { public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() throws Exception {
String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}"; String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"location\":[31.131302,29.976480]}";
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD); IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
indexRequest.source(jsonObject, XContentType.JSON); indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT); IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String lighthouseOfAlexandriaId = response.getId(); String lighthouseOfAlexandriaId = response.getId();
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD); RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
client.indices().refresh(refreshRequest, RequestOptions.DEFAULT); client.indices()
.refresh(refreshRequest, RequestOptions.DEFAULT);
QueryBuilder qb = QueryBuilder qb = QueryBuilders.geoDistanceQuery("location")
QueryBuilders.geoDistanceQuery("location") .point(29.976, 31.131)
.point(29.976, 31.131) .distance(10, DistanceUnit.MILES);
.distance(10, DistanceUnit.MILES);
SearchSourceBuilder source = new SearchSourceBuilder().query(qb); SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD); SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
searchRequest.source(source); searchRequest.source(source);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
List<String> ids = Arrays.stream(searchResponse.getHits().getHits()).map(SearchHit::getId) List<String> ids = Arrays.stream(searchResponse.getHits()
.collect(Collectors.toList()); .getHits())
assertTrue(ids.contains(lighthouseOfAlexandriaId)); .map(SearchHit::getId)
} .collect(Collectors.toList());
assertTrue(ids.contains(lighthouseOfAlexandriaId));
}
@Test @Test
public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() throws Exception { public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() throws Exception {
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]}";
IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD); IndexRequest indexRequest = new IndexRequest(WONDERS_OF_WORLD);
indexRequest.source(jsonObject, XContentType.JSON); indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT); IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String greatRannOfKutchid = response.getId(); String greatRannOfKutchid = response.getId();
RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD); RefreshRequest refreshRequest = new RefreshRequest(WONDERS_OF_WORLD);
client.indices().refresh(refreshRequest, RequestOptions.DEFAULT); client.indices()
.refresh(refreshRequest, RequestOptions.DEFAULT);
List<GeoPoint> allPoints = new ArrayList<GeoPoint>(); List<GeoPoint> allPoints = new ArrayList<GeoPoint>();
allPoints.add(new GeoPoint(22.733, 68.859)); allPoints.add(new GeoPoint(22.733, 68.859));
allPoints.add(new GeoPoint(24.733, 68.859)); allPoints.add(new GeoPoint(24.733, 68.859));
allPoints.add(new GeoPoint(23, 70.859)); allPoints.add(new GeoPoint(23, 70.859));
QueryBuilder qb = QueryBuilders.geoPolygonQuery("location", allPoints); QueryBuilder qb = QueryBuilders.geoPolygonQuery("location", allPoints);
SearchSourceBuilder source = new SearchSourceBuilder().query(qb); SearchSourceBuilder source = new SearchSourceBuilder().query(qb);
SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD); SearchRequest searchRequest = new SearchRequest(WONDERS_OF_WORLD);
searchRequest.source(source); searchRequest.source(source);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
List<String> ids = Arrays.stream(searchResponse.getHits().getHits()).map(SearchHit::getId) List<String> ids = Arrays.stream(searchResponse.getHits()
.collect(Collectors.toList()); .getHits())
assertTrue(ids.contains(greatRannOfKutchid)); .map(SearchHit::getId)
} .collect(Collectors.toList());
assertTrue(ids.contains(greatRannOfKutchid));
}
@After @After
public void destroy() throws Exception { public void destroy() throws Exception {
DeleteIndexRequest deleteIndex = new DeleteIndexRequest(WONDERS_OF_WORLD); DeleteIndexRequest deleteIndex = new DeleteIndexRequest(WONDERS_OF_WORLD);
client.indices().delete(deleteIndex, RequestOptions.DEFAULT); client.indices()
} .delete(deleteIndex, RequestOptions.DEFAULT);
}
} }

View File

@ -31,11 +31,10 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** /**
* This Manual test requires: * This Manual test requires: Elasticsearch instance running on localhost:9200.
* Elasticsearch instance running on localhost:9200.
* *
* The following docker command can be used: * The following docker command can be used: docker run -d --name es761 -p
* docker run -d --name es761 -p 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.1 * 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.1
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class) @ContextConfiguration(classes = Config.class)
@ -91,81 +90,79 @@ public class ElasticSearchManualTest {
@Test @Test
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() { public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
final Page<Article> articleByAuthorName = articleRepository.findByAuthorsName(johnSmith.getName(), final Page<Article> articleByAuthorName = articleRepository.findByAuthorsName(johnSmith.getName(), PageRequest.of(0, 10));
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 = articleRepository.findByAuthorsNameUsingCustomQuery("Smith", final Page<Article> articleByAuthorName = articleRepository.findByAuthorsNameUsingCustomQuery("Smith", PageRequest.of(0, 10));
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 = articleRepository.findByFilteredTagQuery("elasticsearch", final Page<Article> articleByAuthorName = articleRepository.findByFilteredTagQuery("elasticsearch", PageRequest.of(0, 10));
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 = articleRepository.findByAuthorsNameAndFilteredTagQuery("Doe", final Page<Article> articleByAuthorName = articleRepository.findByAuthorsNameAndFilteredTagQuery("Doe", "elasticsearch", PageRequest.of(0, 10));
"elasticsearch", PageRequest.of(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements()); assertEquals(2L, articleByAuthorName.getTotalElements());
} }
@Test @Test
public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() { public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() {
final Query searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*")) final Query searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*"))
.build(); .build();
final SearchHits<Article> articles = final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits()); assertEquals(1, articles.getTotalHits());
} }
@Test @Test
public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() { public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() {
final Query searchQuery = new NativeSearchQueryBuilder().withQuery(fuzzyQuery("title", "serch")).build(); final Query searchQuery = new NativeSearchQueryBuilder().withQuery(fuzzyQuery("title", "serch"))
.build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits()); assertEquals(1, articles.getTotalHits());
final Article article = articles.getSearchHit(0).getContent(); final Article article = articles.getSearchHit(0)
.getContent();
final String newTitle = "Getting started with Search Engines"; final String newTitle = "Getting started with Search Engines";
article.setTitle(newTitle); article.setTitle(newTitle);
articleRepository.save(article); articleRepository.save(article);
assertEquals(newTitle, articleRepository.findById(article.getId()).get().getTitle()); assertEquals(newTitle, articleRepository.findById(article.getId())
.get()
.getTitle());
} }
@Test @Test
public void givenSavedDoc_whenDelete_thenRemovedFromIndex() { public void givenSavedDoc_whenDelete_thenRemovedFromIndex() {
final String articleTitle = "Spring Data Elasticsearch"; final String articleTitle = "Spring Data Elasticsearch";
final Query searchQuery = new NativeSearchQueryBuilder() final Query searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%"))
.withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")).build(); .build();
final SearchHits<Article> articles = final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits()); assertEquals(1, articles.getTotalHits());
final long count = articleRepository.count(); final long count = articleRepository.count();
articleRepository.delete(articles.getSearchHit(0).getContent()); articleRepository.delete(articles.getSearchHit(0)
.getContent());
assertEquals(count - 1, articleRepository.count()); assertEquals(count - 1, articleRepository.count());
} }
@Test @Test
public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() { public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() {
final Query searchQuery = new NativeSearchQueryBuilder() final Query searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND))
.withQuery(matchQuery("title", "Search engines").operator(AND)).build(); .build();
final SearchHits<Article> articles = final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits()); assertEquals(1, articles.getTotalHits());
} }
} }

View File

@ -48,199 +48,201 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/** /**
* This Manual test requires: * This Manual test requires: Elasticsearch instance running on localhost:9200.
* Elasticsearch instance running on localhost:9200.
* *
* The following docker command can be used: * The following docker command can be used: docker run -d --name es761 -p
* docker run -d --name es761 -p 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.1 * 9200:9200 -e "discovery.type=single-node" elasticsearch:7.6.1
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class) @ContextConfiguration(classes = Config.class)
public class ElasticSearchQueryManualTest { public class ElasticSearchQueryManualTest {
@Autowired @Autowired
private ElasticsearchRestTemplate elasticsearchTemplate; private ElasticsearchRestTemplate elasticsearchTemplate;
@Autowired @Autowired
private ArticleRepository articleRepository; private ArticleRepository articleRepository;
@Autowired @Autowired
private RestHighLevelClient client; private RestHighLevelClient client;
private final Author johnSmith = new Author("John Smith"); private final Author johnSmith = new Author("John Smith");
private final Author johnDoe = new Author("John Doe"); private final Author johnDoe = new Author("John Doe");
@Before @Before
public void before() { public void before() {
Article article = new Article("Spring Data Elasticsearch"); Article article = new Article("Spring Data Elasticsearch");
article.setAuthors(asList(johnSmith, johnDoe)); article.setAuthors(asList(johnSmith, johnDoe));
article.setTags("elasticsearch", "spring data"); article.setTags("elasticsearch", "spring data");
articleRepository.save(article); articleRepository.save(article);
article = new Article("Search engines"); article = new Article("Search engines");
article.setAuthors(asList(johnDoe)); article.setAuthors(asList(johnDoe));
article.setTags("search engines", "tutorial"); article.setTags("search engines", "tutorial");
articleRepository.save(article); articleRepository.save(article);
article = new Article("Second Article About Elasticsearch"); article = new Article("Second Article About Elasticsearch");
article.setAuthors(asList(johnSmith)); article.setAuthors(asList(johnSmith));
article.setTags("elasticsearch", "spring data"); article.setTags("elasticsearch", "spring data");
articleRepository.save(article); articleRepository.save(article);
article = new Article("Elasticsearch Tutorial"); article = new Article("Elasticsearch Tutorial");
article.setAuthors(asList(johnDoe)); article.setAuthors(asList(johnDoe));
article.setTags("elasticsearch"); article.setTags("elasticsearch");
articleRepository.save(article); articleRepository.save(article);
} }
@After @After
public void after() { public void after() {
articleRepository.deleteAll(); articleRepository.deleteAll();
} }
@Test @Test
public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() { public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() {
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(Operator.AND))
.withQuery(matchQuery("title", "Search engines").operator(Operator.AND)).build(); .build();
final SearchHits<Article> articles = final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); assertEquals(1, articles.getTotalHits());
assertEquals(1, articles.getTotalHits()); }
}
@Test @Test
public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() { public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() {
final NativeSearchQuery searchQuery = final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Engines Solutions"))
new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Engines Solutions")) .build();
.build();
final SearchHits<Article> articles = final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits()); assertEquals(1, articles.getTotalHits());
assertEquals("Search engines", articles.getSearchHit(0).getContent().getTitle()); assertEquals("Search engines", articles.getSearchHit(0)
} .getContent()
.getTitle());
}
@Test @Test
public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() { public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() {
final NativeSearchQuery searchQuery = final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "elasticsearch data"))
new NativeSearchQueryBuilder().withQuery(matchQuery("title", "elasticsearch data")) .build();
.build();
final SearchHits<Article> articles = final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(3, articles.getTotalHits()); assertEquals(3, articles.getTotalHits());
} }
@Test @Test
public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() { public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch"))
.withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")) .build();
.build();
SearchHits<Article> articles = SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits()); assertEquals(1, articles.getTotalHits());
searchQuery = new NativeSearchQueryBuilder() searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About"))
.withQuery(matchQuery("title.verbatim", "Second Article About")) .build();
.build();
articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(0, articles.getTotalHits()); assertEquals(0, articles.getTotalHits());
} }
@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);
ScoreMode.None);
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); .build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(2, articles.getTotalHits()); assertEquals(2, articles.getTotalHits());
} }
@Test @Test
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() throws Exception { public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() throws Exception {
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("title"); final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags")
.field("title");
final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation); final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation);
final SearchRequest searchRequest = new SearchRequest("blog").source(builder); final SearchRequest searchRequest = new SearchRequest("blog").source(builder);
final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
final Map<String, Aggregation> results = response.getAggregations().asMap(); final Map<String, Aggregation> results = response.getAggregations()
final ParsedStringTerms topTags = (ParsedStringTerms) results.get("top_tags"); .asMap();
final ParsedStringTerms topTags = (ParsedStringTerms) results.get("top_tags");
final List<String> keys = topTags.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).sorted() final List<String> keys = topTags.getBuckets()
.collect(toList()); .stream()
assertEquals( .map(MultiBucketsAggregation.Bucket::getKeyAsString)
asList("about", "article", "data", "elasticsearch", "engines", "search", "second", "spring", "tutorial"), keys); .sorted()
} .collect(toList());
assertEquals(asList("about", "article", "data", "elasticsearch", "engines", "search", "second", "spring", "tutorial"), keys);
}
@Test @Test
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() throws Exception { public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() throws Exception {
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags") final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags")
.order(BucketOrder.count(false)); .field("tags")
.order(BucketOrder.count(false));
final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation); final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation);
final SearchRequest searchRequest = new SearchRequest().indices("blog").source(builder); final SearchRequest searchRequest = new SearchRequest().indices("blog")
.source(builder);
final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT); final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
final Map<String, Aggregation> results = response.getAggregations().asMap(); final Map<String, Aggregation> results = response.getAggregations()
final ParsedStringTerms topTags = (ParsedStringTerms) results.get("top_tags"); .asMap();
final ParsedStringTerms topTags = (ParsedStringTerms) results.get("top_tags");
final List<String> keys = topTags.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString) final List<String> keys = topTags.getBuckets()
.collect(toList()); .stream()
assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys); .map(MultiBucketsAggregation.Bucket::getKeyAsString)
} .collect(toList());
assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys);
}
@Test @Test
public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() { public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() {
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1))
.withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)).build(); .build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits()); assertEquals(1, articles.getTotalHits());
} }
@Test @Test
public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() { public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() {
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "spring date elasticserch").operator(Operator.AND)
.withQuery( .fuzziness(Fuzziness.ONE)
matchQuery("title", "spring date elasticserch").operator(Operator.AND).fuzziness(Fuzziness.ONE).prefixLength(3)) .prefixLength(3))
.build(); .build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(1, articles.getTotalHits()); assertEquals(1, articles.getTotalHits());
} }
@Test @Test
public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() { public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() {
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder() final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(multiMatchQuery("tutorial").field("title")
.withQuery( .field("tags")
multiMatchQuery("tutorial").field("title").field("tags").type(MultiMatchQueryBuilder.Type.BEST_FIELDS)) .type(MultiMatchQueryBuilder.Type.BEST_FIELDS))
.build(); .build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(2, articles.getTotalHits()); assertEquals(2, articles.getTotalHits());
} }
@Test @Test
public void givenBoolQuery_whenQueryByAuthorsName_thenFoundArticlesByThatAuthorAndFilteredTag() { public void givenBoolQuery_whenQueryByAuthorsName_thenFoundArticlesByThatAuthorAndFilteredTag() {
final QueryBuilder builder = boolQuery() final QueryBuilder builder = boolQuery().must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe")), ScoreMode.None))
.must(nestedQuery("authors", boolQuery().must(termQuery("authors.name", "doe")), ScoreMode.None)) .filter(termQuery("tags", "elasticsearch"));
.filter(termQuery("tags", "elasticsearch"));
final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); final NativeSearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder)
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog")); .build();
final SearchHits<Article> articles = elasticsearchTemplate.search(searchQuery, Article.class, IndexCoordinates.of("blog"));
assertEquals(2, articles.getTotalHits()); assertEquals(2, articles.getTotalHits());
} }
} }