Skip to content

Commit 2e9e6c1

Browse files
committed
Merge pull request eugenp#370 from zinch84/elasticsearch_queries
Add Spring Data Elasticsearch test cases with different query types
2 parents 9822ff3 + 8c90c74 commit 2e9e6c1

3 files changed

Lines changed: 247 additions & 15 deletions

File tree

‎spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.baeldung.spring.data.es.config;
22

3+
import org.elasticsearch.client.Client;
34
import org.elasticsearch.common.settings.ImmutableSettings;
45
import org.elasticsearch.node.NodeBuilder;
56
import org.slf4j.Logger;
@@ -24,13 +25,7 @@ public class Config {
2425
private static Logger logger = LoggerFactory.getLogger(Config.class);
2526

2627
@Bean
27-
public NodeBuilder nodeBuilder() {
28-
return new NodeBuilder();
29-
}
30-
31-
@Bean
32-
public ElasticsearchOperations elasticsearchTemplate() {
33-
28+
public Client client() {
3429
try {
3530
Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data");
3631

@@ -40,14 +35,19 @@ public ElasticsearchOperations elasticsearchTemplate() {
4035

4136
logger.debug(tmpDir.toAbsolutePath().toString());
4237

43-
return new ElasticsearchTemplate(nodeBuilder()
38+
return new NodeBuilder()
4439
.local(true)
4540
.settings(elasticsearchSettings.build())
4641
.node()
47-
.client());
42+
.client();
4843
} catch (IOException ioex) {
4944
logger.error("Cannot create temp dir", ioex);
5045
throw new RuntimeException();
5146
}
5247
}
48+
49+
@Bean
50+
public ElasticsearchOperations elasticsearchTemplate() {
51+
return new ElasticsearchTemplate(client());
52+
}
5353
}

‎spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java‎

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,35 @@
11
package com.baeldung.spring.data.es.model;
22

33
import org.springframework.data.annotation.Id;
4-
import org.springframework.data.elasticsearch.annotations.Document;
5-
import org.springframework.data.elasticsearch.annotations.Field;
6-
import org.springframework.data.elasticsearch.annotations.FieldIndex;
7-
import org.springframework.data.elasticsearch.annotations.FieldType;
4+
import org.springframework.data.elasticsearch.annotations.*;
85

6+
import java.util.Arrays;
97
import java.util.List;
108

9+
import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed;
10+
import static org.springframework.data.elasticsearch.annotations.FieldType.Nested;
11+
import static org.springframework.data.elasticsearch.annotations.FieldType.String;
12+
1113
@Document(indexName = "blog", type = "article")
1214
public class Article {
1315

1416
@Id
1517
private String id;
16-
@Field(type = FieldType.String, index = FieldIndex.not_analyzed)
18+
19+
@MultiField(
20+
mainField = @Field(type = String),
21+
otherFields = {
22+
@NestedField(index = not_analyzed, dotSuffix = "verbatim", type = String)
23+
}
24+
)
1725
private String title;
18-
@Field(type = FieldType.Nested)
26+
27+
@Field(type = Nested)
1928
private List<Author> authors;
2029

30+
@Field(type = String, index = not_analyzed)
31+
private String[] tags;
32+
2133
public Article() {
2234
}
2335

@@ -49,12 +61,21 @@ public void setAuthors(List<Author> authors) {
4961
this.authors = authors;
5062
}
5163

64+
public String[] getTags() {
65+
return tags;
66+
}
67+
68+
public void setTags(String... tags) {
69+
this.tags = tags;
70+
}
71+
5272
@Override
5373
public String toString() {
5474
return "Article{" +
5575
"id='" + id + '\'' +
5676
", title='" + title + '\'' +
5777
", authors=" + authors +
78+
", tags=" + Arrays.toString(tags) +
5879
'}';
5980
}
6081
}
Lines changed: 211 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
package com.baeldung.spring.data.es;
2+
3+
import com.baeldung.spring.data.es.config.Config;
4+
import com.baeldung.spring.data.es.model.Article;
5+
import com.baeldung.spring.data.es.model.Author;
6+
import com.baeldung.spring.data.es.service.ArticleService;
7+
import org.elasticsearch.action.ActionFuture;
8+
import org.elasticsearch.action.index.IndexRequest;
9+
import org.elasticsearch.action.index.IndexResponse;
10+
import org.elasticsearch.action.search.SearchResponse;
11+
import org.elasticsearch.client.Client;
12+
import org.elasticsearch.common.unit.Fuzziness;
13+
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
14+
import org.elasticsearch.index.query.QueryBuilder;
15+
import org.elasticsearch.search.aggregations.Aggregation;
16+
import org.elasticsearch.search.aggregations.AggregationBuilders;
17+
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
18+
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
19+
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
20+
import org.junit.Before;
21+
import org.junit.Test;
22+
import org.junit.runner.RunWith;
23+
import org.springframework.beans.factory.annotation.Autowired;
24+
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
25+
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
26+
import org.springframework.data.elasticsearch.core.query.SearchQuery;
27+
import org.springframework.test.context.ContextConfiguration;
28+
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
29+
import org.springframework.test.context.support.AnnotationConfigContextLoader;
30+
31+
import java.util.Collections;
32+
import java.util.List;
33+
import java.util.Map;
34+
import java.util.concurrent.TimeUnit;
35+
36+
import static java.util.Arrays.asList;
37+
import static java.util.stream.Collectors.toList;
38+
import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND;
39+
import static org.elasticsearch.index.query.QueryBuilders.*;
40+
import static org.junit.Assert.assertEquals;
41+
42+
@RunWith(SpringJUnit4ClassRunner.class)
43+
@ContextConfiguration(classes = {Config.class}, loader = AnnotationConfigContextLoader.class)
44+
public class ElasticSearchQueryTest {
45+
46+
@Autowired
47+
private ElasticsearchTemplate elasticsearchTemplate;
48+
49+
@Autowired
50+
private ArticleService articleService;
51+
52+
@Autowired
53+
private Client client;
54+
55+
private final Author johnSmith = new Author("John Smith");
56+
private final Author johnDoe = new Author("John Doe");
57+
58+
@Before
59+
public void before() {
60+
elasticsearchTemplate.deleteIndex(Article.class);
61+
elasticsearchTemplate.createIndex(Article.class);
62+
elasticsearchTemplate.putMapping(Article.class);
63+
elasticsearchTemplate.refresh(Article.class, true);
64+
65+
Article article = new Article("Spring Data Elasticsearch");
66+
article.setAuthors(asList(johnSmith, johnDoe));
67+
article.setTags("elasticsearch", "spring data");
68+
articleService.save(article);
69+
70+
article = new Article("Search engines");
71+
article.setAuthors(asList(johnDoe));
72+
article.setTags("search engines", "tutorial");
73+
articleService.save(article);
74+
75+
article = new Article("Second Article About Elasticsearch");
76+
article.setAuthors(asList(johnSmith));
77+
article.setTags("elasticsearch", "spring data");
78+
articleService.save(article);
79+
80+
article = new Article("Elasticsearch Tutorial");
81+
article.setAuthors(asList(johnDoe));
82+
article.setTags("elasticsearch");
83+
articleService.save(article);
84+
}
85+
86+
@Test
87+
public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() {
88+
SearchQuery searchQuery = new NativeSearchQueryBuilder()
89+
.withQuery(matchQuery("title", "Search engines").operator(AND))
90+
.build();
91+
List<Article> articles = elasticsearchTemplate
92+
.queryForList(searchQuery, Article.class);
93+
assertEquals(1, articles.size());
94+
}
95+
96+
@Test
97+
public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() {
98+
SearchQuery searchQuery = new NativeSearchQueryBuilder()
99+
.withQuery(matchQuery("title", "Engines Solutions"))
100+
.build();
101+
List<Article> articles = elasticsearchTemplate
102+
.queryForList(searchQuery, Article.class);
103+
assertEquals(1, articles.size());
104+
assertEquals("Search engines", articles.get(0).getTitle());
105+
}
106+
107+
@Test
108+
public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() {
109+
SearchQuery searchQuery = new NativeSearchQueryBuilder()
110+
.withQuery(matchQuery("title", "elasticsearch data"))
111+
.build();
112+
List<Article> articles = elasticsearchTemplate
113+
.queryForList(searchQuery, Article.class);
114+
assertEquals(3, articles.size());
115+
}
116+
117+
@Test
118+
public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() {
119+
SearchQuery searchQuery = new NativeSearchQueryBuilder()
120+
.withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch"))
121+
.build();
122+
List<Article> articles = elasticsearchTemplate
123+
.queryForList(searchQuery, Article.class);
124+
assertEquals(1, articles.size());
125+
126+
searchQuery = new NativeSearchQueryBuilder()
127+
.withQuery(matchQuery("title.verbatim", "Second Article About"))
128+
.build();
129+
articles = elasticsearchTemplate
130+
.queryForList(searchQuery, Article.class);
131+
assertEquals(0, articles.size());
132+
}
133+
134+
@Test
135+
public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() {
136+
QueryBuilder builder = nestedQuery("authors",
137+
boolQuery().must(termQuery("authors.name", "smith")));
138+
139+
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
140+
List<Article> articles = elasticsearchTemplate.queryForList(searchQuery, Article.class);
141+
142+
assertEquals(2, articles.size());
143+
}
144+
145+
@Test
146+
public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() {
147+
TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title");
148+
SearchResponse response = client.prepareSearch("blog").setTypes("article")
149+
.addAggregation(aggregation).execute().actionGet();
150+
151+
Map<String, Aggregation> results = response.getAggregations().asMap();
152+
StringTerms topTags = (StringTerms) results.get("top_tags");
153+
154+
List<String> keys = topTags.getBuckets().stream().map(b -> b.getKey()).collect(toList());
155+
Collections.sort(keys);
156+
assertEquals(asList("about", "article", "data", "elasticsearch",
157+
"engines", "search", "second", "spring", "tutorial"), keys);
158+
}
159+
160+
@Test
161+
public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() {
162+
TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags")
163+
.order(Terms.Order.aggregation("_count", false));
164+
SearchResponse response = client.prepareSearch("blog").setTypes("article")
165+
.addAggregation(aggregation).execute().actionGet();
166+
167+
Map<String, Aggregation> results = response.getAggregations().asMap();
168+
StringTerms topTags = (StringTerms) results.get("top_tags");
169+
170+
List<String> keys = topTags.getBuckets().stream().map(b -> b.getKey()).collect(toList());
171+
assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys);
172+
}
173+
174+
@Test
175+
public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() {
176+
SearchQuery searchQuery = new NativeSearchQueryBuilder()
177+
.withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1))
178+
.build();
179+
List<Article> articles = elasticsearchTemplate
180+
.queryForList(searchQuery, Article.class);
181+
assertEquals(1, articles.size());
182+
}
183+
184+
@Test
185+
public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() {
186+
SearchQuery searchQuery = new NativeSearchQueryBuilder()
187+
.withQuery(matchQuery("title", "spring date elasticserch")
188+
.operator(AND)
189+
.fuzziness(Fuzziness.ONE)
190+
.prefixLength(3))
191+
.build();
192+
193+
List<Article> articles = elasticsearchTemplate
194+
.queryForList(searchQuery, Article.class);
195+
assertEquals(1, articles.size());
196+
}
197+
198+
@Test
199+
public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() {
200+
SearchQuery searchQuery = new NativeSearchQueryBuilder()
201+
.withQuery(multiMatchQuery("tutorial")
202+
.field("title")
203+
.field("tags")
204+
.type(MultiMatchQueryBuilder.Type.BEST_FIELDS))
205+
.build();
206+
207+
List<Article> articles = elasticsearchTemplate
208+
.queryForList(searchQuery, Article.class);
209+
assertEquals(2, articles.size());
210+
}
211+
}

0 commit comments

Comments
 (0)