fixed tests

This commit is contained in:
Mathieu Fortin 2020-04-13 13:35:47 -04:00
parent c1d547c5f0
commit 2c5c556fed
6 changed files with 211 additions and 265 deletions

View File

@ -37,11 +37,6 @@
<version>${spring-data-elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>

View File

@ -9,8 +9,7 @@ import com.baeldung.spring.data.es.config.Config;
/**
*
* This Manual test requires:
* * Elasticsearch instance running on host
* This Manual test requires: * Elasticsearch instance running on host
*
*/
@RunWith(SpringJUnit4ClassRunner.class)

View File

@ -35,132 +35,113 @@ import org.springframework.data.elasticsearch.client.RestClients;
/**
*
* This Manual test requires:
* * Elasticsearch instance running on host
* * with cluster name = elasticsearch
* This Manual test requires: * Elasticsearch instance running on host * with
* cluster name = elasticsearch
*
*/
public class ElasticSearchManualTest {
private List<Person> listOfPersons = new ArrayList<>();
private RestHighLevelClient client = null;
private List<Person> listOfPersons = new ArrayList<>();
private RestHighLevelClient client = null;
@Before
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);
ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo("localhost:9200").build();
client = RestClients.create(clientConfiguration).rest();
}
@Before
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);
@Test
public void givenJsonString_whenJavaObject_thenIndexDocument() throws Exception {
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
IndexRequest request = new IndexRequest("people", "Doe");
request.source(jsonObject, XContentType.JSON);
ClientConfiguration clientConfiguration = ClientConfiguration.builder().connectedTo("localhost:9200").build();
client = RestClients.create(clientConfiguration).rest();
}
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
String index = response.getIndex();
assertEquals(Result.CREATED, response.getResult());
assertEquals(index, "people");
}
@Test
public void givenJsonString_whenJavaObject_thenIndexDocument() throws Exception {
String jsonObject = "{\"age\":20,\"dateOfBirth\":1471466076564,\"fullName\":\"John Doe\"}";
IndexRequest request = new IndexRequest("people", "Doe");
request.source(jsonObject, XContentType.JSON);
@Test
public void givenDocumentId_whenJavaObject_thenDeleteDocument() throws Exception {
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
IndexRequest indexRequest = new IndexRequest("people", "Doe");
indexRequest.source(jsonObject, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
String index = response.getIndex();
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String id = response.getId();
assertEquals(Result.CREATED, response.getResult());
assertEquals(index, "people");
}
DeleteRequest deleteRequest = new DeleteRequest("people");
deleteRequest.id(id);
deleteRequest.type("Doe");
@Test
public void givenDocumentId_whenJavaObject_thenDeleteDocument() throws Exception {
String jsonObject = "{\"age\":10,\"dateOfBirth\":1471455886564,\"fullName\":\"Johan Doe\"}";
IndexRequest indexRequest = new IndexRequest("people", "Doe");
indexRequest.source(jsonObject, XContentType.JSON);
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
String id = response.getId();
assertEquals(Result.DELETED,deleteResponse.getResult());
}
DeleteRequest deleteRequest = new DeleteRequest("people");
deleteRequest.id(id);
deleteRequest.type("Doe");
@Test
public void givenSearchRequest_whenMatchAll_thenReturnAllResults() throws Exception {
SearchRequest searchRequest = new SearchRequest();
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = response
.getHits()
.getHits();
List<Person> results = Arrays.stream(searchHits)
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
.collect(Collectors.toList());
results.forEach(System.out::println);
}
DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
@Test
public void givenSearchParameters_thenReturnResults() throws Exception {
SearchSourceBuilder builder = new SearchSourceBuilder()
.postFilter(QueryBuilders.rangeQuery("age").from(5).to(15))
.from(0)
.size(60)
assertEquals(Result.DELETED, deleteResponse.getResult());
}
@Test
public void givenSearchRequest_whenMatchAll_thenReturnAllResults() throws Exception {
SearchRequest searchRequest = new SearchRequest();
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = response.getHits().getHits();
List<Person> results = Arrays.stream(searchHits).map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
.collect(Collectors.toList());
results.forEach(System.out::println);
}
@Test
public void givenSearchParameters_thenReturnResults() throws Exception {
SearchSourceBuilder builder = new SearchSourceBuilder().postFilter(QueryBuilders.rangeQuery("age").from(5).to(15))
.from(0).size(60).explain(true);
SearchRequest searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
builder = new SearchSourceBuilder().postFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette"))
.from(0).size(60).explain(true);
searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder);
SearchResponse response2 = client.search(searchRequest, RequestOptions.DEFAULT);
builder = new SearchSourceBuilder().postFilter(QueryBuilders.matchQuery("John", "Name*")).from(0).size(60)
.explain(true);
SearchRequest searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder);
builder = new SearchSourceBuilder()
.postFilter(QueryBuilders.simpleQueryStringQuery("+John -Doe OR Janette"))
.from(0)
.size(60)
.explain(true);
SearchResponse response3 = client.search(searchRequest, RequestOptions.DEFAULT);
searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder);
response2.getHits();
response3.getHits();
SearchResponse response2 = client.search(searchRequest, RequestOptions.DEFAULT);
final List<Person> results = Arrays.stream(response.getHits().getHits())
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class)).collect(Collectors.toList());
results.forEach(System.out::println);
}
builder = new SearchSourceBuilder()
.postFilter(QueryBuilders.matchQuery("John", "Name*"))
.from(0)
.size(60)
.explain(true);
searchRequest = new SearchRequest();
searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequest.source(builder);
@Test
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
XContentBuilder builder = XContentFactory.jsonBuilder().startObject().field("fullName", "Test")
.field("salary", "11500").field("age", "10").endObject();
SearchResponse response3 = client.search(searchRequest, RequestOptions.DEFAULT);
IndexRequest indexRequest = new IndexRequest("people", "Doe");
indexRequest.source(builder);
response2.getHits();
response3.getHits();
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
final List<Person> results = Arrays.stream(response.getHits().getHits())
.map(hit -> JSON.parseObject(hit.getSourceAsString(), Person.class))
.collect(Collectors.toList());
results.forEach(System.out::println);
}
@Test
public void givenContentBuilder_whenHelpers_thanIndexJson() throws IOException {
XContentBuilder builder = XContentFactory
.jsonBuilder()
.startObject()
.field("fullName", "Test")
.field("salary", "11500")
.field("age", "10")
.endObject();
IndexRequest indexRequest = new IndexRequest("people", "Doe");
indexRequest.source(builder);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
assertEquals(Result.CREATED, response.getResult());
}
assertEquals(Result.CREATED, response.getResult());
}
}

View File

@ -33,155 +33,110 @@ import com.baeldung.spring.data.es.config.Config;
/**
*
* This Manual test requires:
* * Elasticsearch instance running on host
* * with cluster name = elasticsearch
* * and further configurations
* This Manual test requires: * Elasticsearch instance running on host * with
* cluster name = elasticsearch * and further configurations
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class GeoQueriesManualTest {
private static final String WONDERS_OF_WORLD = "wonders-of-world";
private static final String WONDERS = "Wonders";
private static final String WONDERS_OF_WORLD = "wonders-of-world";
private static final String WONDERS = "Wonders";
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired
private Client client;
@Autowired
private Client client;
@Before
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, XContentType.JSON);
client.admin()
.indices()
.create(req)
.actionGet();
}
@Before
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, XContentType.JSON);
client.admin().indices().create(req).actionGet();
}
@Test
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, XContentType.JSON)
.get();
String tajMahalId = response.getId();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
Coordinate topLeft = new Coordinate(74, 31.2);
Coordinate bottomRight = new Coordinate(81.1, 24);
QueryBuilder qb = QueryBuilders
.geoShapeQuery("region", new EnvelopeBuilder(topLeft, bottomRight));
@Test
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, XContentType.JSON)
.get();
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD)
.setTypes(WONDERS)
.setQuery(qb)
.execute()
.actionGet();
String tajMahalId = response.getId();
client.admin().indices().prepareRefresh(WONDERS_OF_WORLD).get();
List<String> ids = Arrays.stream(searchResponse.getHits()
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
Coordinate topLeft = new Coordinate(74, 31.2);
Coordinate bottomRight = new Coordinate(81.1, 24);
QueryBuilder qb = QueryBuilders.geoShapeQuery("region", new EnvelopeBuilder(topLeft, bottomRight));
assertTrue(ids.contains(tajMahalId));
}
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD).setTypes(WONDERS).setQuery(qb).execute()
.actionGet();
@Test
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, XContentType.JSON)
.get();
String pyramidsOfGizaId = response.getId();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
List<String> ids = Arrays.stream(searchResponse.getHits().getHits()).map(SearchHit::getId)
.collect(Collectors.toList());
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location")
.setCorners(31,30,28,32);
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(pyramidsOfGizaId));
}
assertTrue(ids.contains(tajMahalId));
}
@Test
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, XContentType.JSON)
.get();
String lighthouseOfAlexandriaId = response.getId();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
@Test
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, XContentType.JSON)
.get();
String pyramidsOfGizaId = response.getId();
client.admin().indices().prepareRefresh(WONDERS_OF_WORLD).get();
QueryBuilder qb = QueryBuilders.geoDistanceQuery("location")
.point(29.976, 31.131)
.distance(10, DistanceUnit.MILES);
QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location").setCorners(31, 30, 28, 32);
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(lighthouseOfAlexandriaId));
}
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(pyramidsOfGizaId));
}
@Test
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, XContentType.JSON)
.get();
String greatRannOfKutchid = response.getId();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
@Test
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, XContentType.JSON)
.get();
String lighthouseOfAlexandriaId = response.getId();
client.admin().indices().prepareRefresh(WONDERS_OF_WORLD).get();
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);
QueryBuilder qb = QueryBuilders.geoDistanceQuery("location").point(29.976, 31.131).distance(10, DistanceUnit.MILES);
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(greatRannOfKutchid));
}
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(lighthouseOfAlexandriaId));
}
@After
public void destroy() {
elasticsearchTemplate.deleteIndex(WONDERS_OF_WORLD);
}
@Test
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, XContentType.JSON)
.get();
String greatRannOfKutchid = response.getId();
client.admin().indices().prepareRefresh(WONDERS_OF_WORLD).get();
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).setQuery(qb).execute()
.actionGet();
List<String> ids = Arrays.stream(searchResponse.getHits().getHits()).map(SearchHit::getId)
.collect(Collectors.toList());
assertTrue(ids.contains(greatRannOfKutchid));
}
@After
public void destroy() {
elasticsearchTemplate.deleteIndex(WONDERS_OF_WORLD);
}
}

View File

@ -29,9 +29,8 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*
* This Manual test requires:
* * Elasticsearch instance running on host
* * with cluster name = elasticsearch
* This Manual test requires: * Elasticsearch instance running on host * with
* cluster name = elasticsearch
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ -88,26 +87,29 @@ public class ElasticSearchManualTest {
@Test
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
final Page<Article> articleByAuthorName = articleService
.findByAuthorName(johnSmith.getName(), PageRequest.of(0, 10));
final Page<Article> articleByAuthorName = articleService.findByAuthorName(johnSmith.getName(),
PageRequest.of(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements());
}
@Test
public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() {
final Page<Article> articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("Smith", PageRequest.of(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", PageRequest.of(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", PageRequest.of(0, 10));
final Page<Article> articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe",
"elasticsearch", PageRequest.of(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements());
}
@ -115,7 +117,7 @@ public class ElasticSearchManualTest {
public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*"))
.build();
.build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
@ -142,7 +144,7 @@ public class ElasticSearchManualTest {
final String articleTitle = "Spring Data Elasticsearch";
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")).build();
.withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")).build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
final long count = articleService.count();
@ -155,7 +157,7 @@ public class ElasticSearchManualTest {
@Test
public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchQuery("title", "Search engines").operator(AND)).build();
.withQuery(matchQuery("title", "Search engines").operator(AND)).build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size());
}

View File

@ -20,8 +20,10 @@ import com.baeldung.spring.data.es.model.Author;
import com.baeldung.spring.data.es.service.ArticleService;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
@ -29,8 +31,9 @@ import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -59,7 +62,7 @@ public class ElasticSearchQueryManualTest {
private ArticleService articleService;
@Autowired
private Client client;
private RestHighLevelClient client;
private final Author johnSmith = new Author("John Smith");
private final Author johnDoe = new Author("John Doe");
@ -141,13 +144,18 @@ public class ElasticSearchQueryManualTest {
}
@Test
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() {
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() throws Exception {
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
.execute().actionGet();
final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation);
final SearchRequest searchRequest = new SearchRequest("blog")
.types("article")
.source(builder);
final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
final Map<String, Aggregation> results = response.getAggregations().asMap();
final StringTerms topTags = (StringTerms) results.get("top_tags");
final ParsedStringTerms topTags = (ParsedStringTerms) results.get("top_tags");
final List<String> keys = topTags.getBuckets().stream()
.map(MultiBucketsAggregation.Bucket::getKeyAsString)
@ -157,14 +165,20 @@ public class ElasticSearchQueryManualTest {
}
@Test
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() throws Exception {
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
.order(BucketOrder.count(false));
final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation)
.execute().actionGet();
final SearchSourceBuilder builder = new SearchSourceBuilder().aggregation(aggregation);
final SearchRequest searchRequest = new SearchRequest()
.indices("blog")
.types("article")
.source(builder);
final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
final Map<String, Aggregation> results = response.getAggregations().asMap();
final StringTerms topTags = (StringTerms) results.get("top_tags");
final ParsedStringTerms topTags = (ParsedStringTerms) results.get("top_tags");
final List<String> keys = topTags.getBuckets().stream()
.map(MultiBucketsAggregation.Bucket::getKeyAsString)