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> <version>${spring-data-elasticsearch.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId> <artifactId>fastjson</artifactId>

View File

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

View File

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

View File

@ -33,155 +33,110 @@ import com.baeldung.spring.data.es.config.Config;
/** /**
* *
* This Manual test requires: * This Manual test requires: * Elasticsearch instance running on host * with
* * Elasticsearch instance running on host * cluster name = elasticsearch * and further configurations
* * with cluster name = elasticsearch
* * and further configurations
* *
*/ */
@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";
private static final String WONDERS = "Wonders"; private static final String WONDERS = "Wonders";
@Autowired @Autowired
private ElasticsearchTemplate elasticsearchTemplate; private ElasticsearchTemplate elasticsearchTemplate;
@Autowired @Autowired
private Client client; private Client client;
@Before @Before
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, XContentType.JSON); req.mapping(WONDERS, jsonObject, XContentType.JSON);
client.admin() client.admin().indices().create(req).actionGet();
.indices() }
.create(req)
.actionGet();
}
@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]]}}";
IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS) IndexResponse response = client.prepareIndex(WONDERS_OF_WORLD, WONDERS).setSource(jsonObject, XContentType.JSON)
.setSource(jsonObject, XContentType.JSON) .get();
.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));
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD) String tajMahalId = response.getId();
.setTypes(WONDERS) client.admin().indices().prepareRefresh(WONDERS_OF_WORLD).get();
.setQuery(qb)
.execute()
.actionGet();
List<String> ids = Arrays.stream(searchResponse.getHits() Coordinate topLeft = new Coordinate(74, 31.2);
.getHits()) Coordinate bottomRight = new Coordinate(81.1, 24);
.map(SearchHit::getId) QueryBuilder qb = QueryBuilders.geoShapeQuery("region", new EnvelopeBuilder(topLeft, bottomRight));
.collect(Collectors.toList());
assertTrue(ids.contains(tajMahalId)); SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD).setTypes(WONDERS).setQuery(qb).execute()
} .actionGet();
@Test List<String> ids = Arrays.stream(searchResponse.getHits().getHits()).map(SearchHit::getId)
public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() { .collect(Collectors.toList());
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.geoBoundingBoxQuery("location") assertTrue(ids.contains(tajMahalId));
.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));
}
@Test @Test
public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() { public void givenGeoPointData_whenExecutedGeoBoundingBoxQuery_thenResultNonEmpty() {
String jsonObject = "{\"name\":\"Lighthouse of alexandria\",\"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, XContentType.JSON)
.setSource(jsonObject, XContentType.JSON) .get();
.get(); String pyramidsOfGizaId = response.getId();
String lighthouseOfAlexandriaId = response.getId(); client.admin().indices().prepareRefresh(WONDERS_OF_WORLD).get();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
QueryBuilder qb = QueryBuilders.geoDistanceQuery("location") QueryBuilder qb = QueryBuilders.geoBoundingBoxQuery("location").setCorners(31, 30, 28, 32);
.point(29.976, 31.131)
.distance(10, DistanceUnit.MILES);
SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD) SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD).setTypes(WONDERS).setQuery(qb).execute()
.setTypes(WONDERS) .actionGet();
.setQuery(qb) List<String> ids = Arrays.stream(searchResponse.getHits().getHits()).map(SearchHit::getId)
.execute() .collect(Collectors.toList());
.actionGet(); assertTrue(ids.contains(pyramidsOfGizaId));
List<String> ids = Arrays.stream(searchResponse.getHits() }
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
assertTrue(ids.contains(lighthouseOfAlexandriaId));
}
@Test @Test
public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() { public void givenGeoPointData_whenExecutedGeoDistanceQuery_thenResultNonEmpty() {
String jsonObject = "{\"name\":\"The Great Rann of Kutch\",\"location\":[69.859741,23.733732]}"; 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, XContentType.JSON)
.setSource(jsonObject, XContentType.JSON) .get();
.get(); String lighthouseOfAlexandriaId = response.getId();
String greatRannOfKutchid = response.getId(); client.admin().indices().prepareRefresh(WONDERS_OF_WORLD).get();
client.admin()
.indices()
.prepareRefresh(WONDERS_OF_WORLD)
.get();
List<GeoPoint> allPoints = new ArrayList<GeoPoint>(); QueryBuilder qb = QueryBuilders.geoDistanceQuery("location").point(29.976, 31.131).distance(10, DistanceUnit.MILES);
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) SearchResponse searchResponse = client.prepareSearch(WONDERS_OF_WORLD).setTypes(WONDERS).setQuery(qb).execute()
.setTypes(WONDERS) .actionGet();
.setQuery(qb) List<String> ids = Arrays.stream(searchResponse.getHits().getHits()).map(SearchHit::getId)
.execute() .collect(Collectors.toList());
.actionGet(); assertTrue(ids.contains(lighthouseOfAlexandriaId));
List<String> ids = Arrays.stream(searchResponse.getHits() }
.getHits())
.map(SearchHit::getId)
.collect(Collectors.toList());
assertTrue(ids.contains(greatRannOfKutchid));
}
@After @Test
public void destroy() { public void givenGeoPointData_whenExecutedGeoPolygonQuery_thenResultNonEmpty() {
elasticsearchTemplate.deleteIndex(WONDERS_OF_WORLD); 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: * This Manual test requires: * Elasticsearch instance running on host * with
* * Elasticsearch instance running on host * cluster name = elasticsearch
* * with cluster name = elasticsearch
* *
*/ */
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ -88,26 +87,29 @@ public class ElasticSearchManualTest {
@Test @Test
public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() { public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() {
final Page<Article> articleByAuthorName = articleService final Page<Article> articleByAuthorName = articleService.findByAuthorName(johnSmith.getName(),
.findByAuthorName(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 = articleService.findByAuthorNameUsingCustomQuery("Smith", PageRequest.of(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", PageRequest.of(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", PageRequest.of(0, 10)); final Page<Article> articleByAuthorName = articleService.findByAuthorsNameAndFilteredTagQuery("Doe",
"elasticsearch", PageRequest.of(0, 10));
assertEquals(2L, articleByAuthorName.getTotalElements()); assertEquals(2L, articleByAuthorName.getTotalElements());
} }
@ -115,7 +117,7 @@ public class ElasticSearchManualTest {
public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() { public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*")) final SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*"))
.build(); .build();
final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size()); assertEquals(1, articles.size());
@ -142,7 +144,7 @@ public class ElasticSearchManualTest {
final String articleTitle = "Spring Data Elasticsearch"; final String articleTitle = "Spring Data Elasticsearch";
final SearchQuery searchQuery = new NativeSearchQueryBuilder() 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); final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size()); assertEquals(1, articles.size());
final long count = articleService.count(); final long count = articleService.count();
@ -155,7 +157,7 @@ public class ElasticSearchManualTest {
@Test @Test
public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() { public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() {
final SearchQuery searchQuery = new NativeSearchQueryBuilder() 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); final List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
assertEquals(1, articles.size()); 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 com.baeldung.spring.data.es.service.ArticleService;
import org.apache.lucene.search.join.ScoreMode; import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse; 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.common.unit.Fuzziness;
import org.elasticsearch.index.query.MultiMatchQueryBuilder; import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder; 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.AggregationBuilders;
import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.BucketOrder;
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.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
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;
@ -59,7 +62,7 @@ public class ElasticSearchQueryManualTest {
private ArticleService articleService; private ArticleService articleService;
@Autowired @Autowired
private Client 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");
@ -141,13 +144,18 @@ public class ElasticSearchQueryManualTest {
} }
@Test @Test
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() { 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 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 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() final List<String> keys = topTags.getBuckets().stream()
.map(MultiBucketsAggregation.Bucket::getKeyAsString) .map(MultiBucketsAggregation.Bucket::getKeyAsString)
@ -157,14 +165,20 @@ public class ElasticSearchQueryManualTest {
} }
@Test @Test
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() { public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() throws Exception {
final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags") final TermsAggregationBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
.order(BucketOrder.count(false)); .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 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() final List<String> keys = topTags.getBuckets().stream()
.map(MultiBucketsAggregation.Bucket::getKeyAsString) .map(MultiBucketsAggregation.Bucket::getKeyAsString)