Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Next Level Elasticsearch Integration with Sprin...
Search
Peter-Josef Meisch
October 15, 2020
Programming
140
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Next Level Elasticsearch Integration with Spring Data Elasticsearch
The slides for my session at ElasticON Global on October 14th and 15th 2020
Peter-Josef Meisch
October 15, 2020
Other Decks in Programming
See All in Programming
C#の現在地 進化の歴史と、AI時代の.NET Everywhere
neuecc
5
5.2k
パズルゲームの作り方 / how to make puzzle games
kaityo256
PRO
2
290
Optunaを作ったときにやりたかったこと、その後 (2026/10/16, Optuna Meetup #3)
iwiwi
1
430
見えないものを探る要求要件定義に必要な基本的思考 / invisible-requirement-thinking
minodriven
15
8.5k
コードレビューのボトルネックを"する側"と"される側"の両面から解消する
yub0n
2
1.6k
個人開発者よ、Honoを使え(おじさんver)
tanahiro2010
2
260
AI時代のコードレビューは人に向けるな、仕組みに向けろ
texmeijin
5
3.7k
R8 の設定見直しでアプリサイズ削減
andpad
0
220
S3 TablesのIcebergデータに、AIエージェントからアクセスしてみた / 20261016developersio2026joetsu-accessing-iceberg-in-s3tables-via-agent
kasacchiful
PRO
0
150
自サークルのIdPからログアウトできるようになるまで
taiseiue
1
140
Railsのためのパスキー実践入門 〜マルチテナントSaaSでの意思決定〜
utakaha
2
560
SalesForceを内製化!? ~ HR事業を支える顧客管理基盤のインフラを大公開 ~
oku053
0
180
Featured
See All Featured
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
1.1k
Agile Leadership in an Agile Organization
kimpetersen
PRO
0
280
What’s in a name? Adding method to the madness
productmarketing
PRO
24
4.2k
Jamie Indigo - Trashchat’s Guide to Black Boxes: Technical SEO Tactics for LLMs
techseoconnect
PRO
0
710
A brief & incomplete history of UX Design for the World Wide Web: 1989–2019
jct
2
530
The browser strikes back
jonoalderson
0
1.8k
How to optimise 3,500 product descriptions for ecommerce in one day using ChatGPT
katarinadahlin
PRO
3
3.9k
Scaling GitHub
holman
464
140k
Information Architects: The Missing Link in Design Systems
soysaucechin
1
1.2k
Mobile First: as difficult as doing things right
swwweet
225
10k
Why You Should Never Use an ORM
jnunemaker
PRO
61
10k
So, you think you're a good person
axbom
PRO
2
2.2k
Transcript
1 ElasticON Global Peter-Josef Meisch Spring Data Elasticsearch Project Lead
2 Nothing will stop you being creative more effectively as
the fear of making a mistake. John Cleese
3 Next Level Elasticsearch Integration with Spring Data Elasticsearch
What is Spring Data Elasticsearch?
“Spring Data’s mission is to provide a familiar and consistent,
Spring-based programming model for data access while still retaining the special traits of the underlying data store.”
Configure the connection to Elasticsearch
Configure the connection to Elasticsearch @Configuration public class RestClientConfig extends
AbstractElasticsearchConfiguration { @Override @Bean public RestHighLevelClient elasticsearchClient() { ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo("localhost:9200") .build(); return RestClients.create(clientConfiguration).rest(); } }
Configure the connection to Elasticsearch @Configuration public class RestClientConfig extends
AbstractElasticsearchConfiguration { @Override @Bean public RestHighLevelClient elasticsearchClient() { ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo("localhost:9200") .withProxy("localhost:8080") .build(); return RestClients.create(clientConfiguration).rest(); } }
Configure the connection to Elasticsearch @Configuration public class RestClientConfig extends
AbstractElasticsearchConfiguration { @Override @Bean public RestHighLevelClient elasticsearchClient() { ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo("localhost:9200") .usingSsl() .build(); return RestClients.create(clientConfiguration).rest(); } }
Configure the connection to Elasticsearch @Configuration public class RestClientConfig extends
AbstractElasticsearchConfiguration { @Override @Bean public RestHighLevelClient elasticsearchClient() { ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo("localhost:9200") .withBasicAuth("myuser", "mypassword") .build(); return RestClients.create(clientConfiguration).rest(); } }
Configure the connection to Elasticsearch @Configuration public class RestClientConfig extends
AbstractElasticsearchConfiguration { @Override @Bean public RestHighLevelClient elasticsearchClient() { ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo("localhost:9200") .withPathPrefix("customer1") .build(); return RestClients.create(clientConfiguration).rest(); } }
Configure the connection to Elasticsearch Supplier<HttpHeaders> currentTimeHeaders = () ->
{ HttpHeaders headers = new HttpHeaders(); headers.add("currentTime", LocalDateTime.now() .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); return headers; }; ClientConfiguration clientConfiguration = ClientConfiguration.builder() .connectedTo("localhost:9200") .withHeaders(currentTimeHeaders) .build();
Entity definition
Entity definition public class Person { @Id private String id;
private String lastName; private String firstName; private LocalDate birthDate; }
Entity definition @Document(indexName = "person") public class Person { @Id
private String id; private String lastName; private String firstName; private LocalDate birthDate; }
Entity definition @Document(indexName = "person") public class Person { @Id
private String id; @Field(type = FieldType.Text) private String lastName; @Field(type = FieldType.Text) private String firstName; private LocalDate birthDate; }
Entity definition @Document(indexName = "person") public class Person { @Id
private String id; @Field(type = FieldType.Text) private String lastName; @Field(type = FieldType.Text) private String firstName; @Field(type = FieldType.Date, format = DateFormat.basic_date) private LocalDate birthDate; }
ElasticsearchOperations
IndexOperations • index creation and deletion • index settings •
index mappings • index templates • alias management • refresh operation
IndexOperations private ElasticsearchOperations operations ; // injected by Spring IndexOperations
indexOps = operations.indexOps(Person.class); indexOps.create(); indexOps.putMapping(); PutTemplateRequest putTemplateRequest = PutTemplateRequest.builder("template-name", "log-*") .withSettings(settings) .withMappings(mapping) .withAliasActions(aliasActions) .build(); indexOps.putTemplate(putTemplateRequest);
IndexOperations private ElasticsearchOperations operations; // injected by Spring IndexOperations indexOps
= operations.indexOps(Person.class) ; indexOps.create(); indexOps.putMapping(); PutTemplateRequest putTemplateRequest = PutTemplateRequest.builder("template-name", "log-*") .withSettings(settings) .withMappings(mapping) .withAliasActions(aliasActions) .build(); indexOps.putTemplate(putTemplateRequest);
IndexOperations private ElasticsearchOperations operations; // injected by Spring IndexOperations indexOps
= operations.indexOps(Person.class); indexOps.create(); indexOps.putMapping(); PutTemplateRequest putTemplateRequest = PutTemplateRequest.builder("template-name", "log-*") .withSettings(settings) .withMappings(mapping) .withAliasActions(aliasActions) .build(); indexOps.putTemplate(putTemplateRequest);
IndexOperations private ElasticsearchOperations operations; // injected by Spring IndexOperations indexOps
= operations.indexOps(Person.class); indexOps.create(); indexOps.putMapping(); PutTemplateRequest putTemplateRequest = PutTemplateRequest.builder("template-name", "log-*") .withSettings(settings) .withMappings(mapping) .withAliasActions(aliasActions) .build(); indexOps.putTemplate(putTemplateRequest) ;
DocumentOperations • save • get • delete • exists •
update
SearchOperations • count • search Query based operations
NativeSearchQuery import static org.elasticsearch.index.query.QueryBuilders.*; import static org.elasticsearch.search.aggregations.AggregationBuilders.*; Query query =
new NativeSearchQueryBuilder() .addAggregation( terms("lastNames").field("lastName").size(10) ) .withQuery( matchQuery("firstName", firstName) ) .build(); SearchHits<Person> searchHits = operations.search(query, Person.class);
StringQuery Query query = new StringQuery( "{" + " \"bool\":
{" + " \"must\": [" + " {" + " \"match\": {" + " \"lastName\": \"Smith\"" + " }" + " }" + " ]" + " }" + "}"); SearchHits<Person> searchHits = operations.search(query, Person.class);
CriteriaQuery Criteria criteria = new Criteria("lastName").is("Smith") .and("firstName").is("James"); Query query =
new CriteriaQuery(criteria); SearchHits<Person> searchHits = operations.search(query, Person.class);
Return types
SearchHit<T • id • index name • the entity of
type T • score • sort values • highlight fields • inner hits
SearchHits<T • number of total hits • total hits relation
(eq, gte) • list of SearchHit<T> objects • max score • aggregations
ElasticsearchRepository
Repository interface PersonRepository extends ElasticsearchRepository< Person, String > { }
// ElasticsearchRepository // +PagingAndSortingRepository // + CrudRepository // + Repository
Repository count() delete(T) deleteAll() deleteAll(Iterable<? extends T) deleteById(ID) existsById(ID) findAll()
findAll(Pageable) findAll(Sort) findAllById(Iterable<ID>) findById(ID) save(T) saveAll(Iterable<T>) searchSimilar(T entity, String[] fields, Pageable pageable)
Repository methods interface PersonRepository extends ElasticsearchRepository< Person, String > {
List<Person> searchByFirstName(String name); List<Person> findByFirstNameOrderByLastNameAsc(String name); List<Person> queryByBirthDateBefore(LocalDate date); }
Repository methods interface PersonRepository extends ElasticsearchRepository<Person, String> { @Query(value =
"{\"fuzzy\":{\"lastName\":\"?0\"}}") List<Person> findByLastNameFuzzy(String lastName); }
Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> {
List<Person> searchByFirstName(String name); }
Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> {
Stream<Person> searchByFirstName(String name); }
Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> {
List<SearchHit<Person>> searchByFirstName(String name); }
Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> {
Stream<SearchHit<Person>> searchByFirstName(String name); }
Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> {
SearchHits<Person> searchByFirstName(String name); }
Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> {
SearchPage<Person> searchByFirstName(String name, Pageable page); }
Repository usage @RestController @RequestMapping(”/persons”) public class PersonController { private PersonRepository
repository; public PersonController(PersonRepository repository) { this.repository = repository; } @GetMapping(”/firstName/{name}”) List<Person> byFirstName( @PathVariable(”name”) String name) { return repository.searchByFirstName(name) ; } }
Repository method with highlight definition interface PersonRepository extends ElasticsearchRepository<Person, String>
{ @Highlight(fields = { @HighlightField(name = "firstName") }) SearchHits<Person> searchByFirstName(String name); } repository.searchByFirstName(”James”) .forEach(searchHit -> { List<String> highlights = searchHit.getHighlightField("firstName"); // ... });
What else?
Lifecycle events @Component public class PersonBeforeConvertCallback implements BeforeConvertCallback<Person> { @Override
public Person onBeforeConvert(Person person, IndexCoordinates indexCoordinates) { if (person.getId() == null) { person.setId(UUID.randomUUID().toString()); } return person; } }
Auditable Entity @Document(indexName = "person") public class Person implements Persistable<String>
{ @Id private String id; @CreatedDate @Field(type = FieldType.Date, format = DateFormat.basic_date_time) private Instant created; @CreatedBy private String createdBy; @Override public boolean isNew() { return id == null || (createdBy == null && created == null); } }
We need contributors! Spring Data Elasticsearch is a community-driven project
49 Thank You! https://spring.io/projects/spring-data-elasticsearch https://github.com/spring-projects/spring-data-elasticsearch @sothawo
[email protected]