SlideShare a Scribd company logo
1
ElasticON Global
Peter-Josef Meisch
Spring Data Elasticsearch Project Lead
2
This presentation and the accompanying oral presentation contain forward-looking statements, including statements
concerning plans for future offerings; the expected strength, performance or benefits of our offerings; and our future
operations and expected performance. These forward-looking statements are subject to the safe harbor provisions
under the Private Securities Litigation Reform Act of 1995. Our expectations and beliefs in light of currently
available information regarding these matters may not materialize. Actual outcomes and results may differ materially
from those contemplated by these forward-looking statements due to uncertainties, risks, and changes in
circumstances, including, but not limited to those related to: the impact of the COVID-19 pandemic on our business
and our customers and partners; our ability to continue to deliver and improve our offerings and successfully
develop new offerings, including security-related product offerings and SaaS offerings; customer acceptance and
purchase of our existing offerings and new offerings, including the expansion and adoption of our SaaS offerings;
our ability to realize value from investments in the business, including R&D investments; our ability to maintain and
expand our user and customer base; our international expansion strategy; our ability to successfully execute our
go-to-market strategy and expand in our existing markets and into new markets, and our ability to forecast customer
retention and expansion; and general market, political, economic and business conditions.
Additional risks and uncertainties that could cause actual outcomes and results to differ materially are included in
our filings with the Securities and Exchange Commission (the “SEC”), including our Annual Report on Form 10-K for
the most recent fiscal year, our quarterly report on Form 10-Q for the most recent fiscal quarter, and any
subsequent reports filed with the SEC. SEC filings are available on the Investor Relations section of Elastic’s
website at ir.elastic.co and the SEC’s website at www.sec.gov.
Any features or functions of services or products referenced in this presentation, or in any presentations, press
releases or public statements, which are not currently available or not currently available as a general availability
release, may not be delivered on time or at all. The development, release, and timing of any features or functionality
described for our products remains at our sole discretion. Customers who purchase our products and services
should make the purchase decisions based upon services and product features and functions that are currently
available.
All statements are made only as of the date of the presentation, and Elastic assumes no obligation to, and does not
currently intend to, update any forward-looking statements or statements relating to features or functions of services
or products, except as required by law.
Forward-Looking Statements
3
Nothing will stop you being creative more
effectively as the fear of making a mistake.
John Cleese
4
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
50
Thank You!
https://spring.io/projects/spring-data-elasticsearch
https://github.com/spring-projects/spring-data-elasticsearch
@sothawo
pj.meisch@sothawo.com

More Related Content

PDF
RedisConf18 - 2,000 Instances and Beyond
PDF
Prometheus in openstack-helm
PDF
LLM with Java.pdf
PDF
[네전따] 네트워크 엔지니어에게 쿠버네티스는 어떤 의미일까요
PPTX
Introduction à Laravel
PPT
Types of machine translation
PPTX
Introduction à React JS
PDF
ISPF Recent and Coming Enhancements
RedisConf18 - 2,000 Instances and Beyond
Prometheus in openstack-helm
LLM with Java.pdf
[네전따] 네트워크 엔지니어에게 쿠버네티스는 어떤 의미일까요
Introduction à Laravel
Types of machine translation
Introduction à React JS
ISPF Recent and Coming Enhancements

What's hot (18)

PDF
Le Domain Driven Design, comment bien démarrer ?
PDF
Rest api 테스트 수행가이드
PPTX
Building Your Own DSL with Xtext
PPTX
Lip reading Project
PPT
Cycle de vie et méthodes de construction des ontologies
PDF
Chp3 - Architecture Logicielle des Applications Mobiles
PDF
Manuel des TP : Atelier Web 2
PPTX
PHP (Partie II) Par Mahdi Ben Alaya
PPTX
Design pattern
PDF
Atelier1 mise en place d’odoo
PDF
Bbl sur les tests
PPTX
les style d'architecture
PDF
실시간 서비스 플랫폼 개발 사례
PPTX
Natural Language Processing - Unit 1
PPTX
Selenium Tutorial Java
PPT
4 lexical and syntax
PPTX
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUES
PDF
Introduction to jest
Le Domain Driven Design, comment bien démarrer ?
Rest api 테스트 수행가이드
Building Your Own DSL with Xtext
Lip reading Project
Cycle de vie et méthodes de construction des ontologies
Chp3 - Architecture Logicielle des Applications Mobiles
Manuel des TP : Atelier Web 2
PHP (Partie II) Par Mahdi Ben Alaya
Design pattern
Atelier1 mise en place d’odoo
Bbl sur les tests
les style d'architecture
실시간 서비스 플랫폼 개발 사례
Natural Language Processing - Unit 1
Selenium Tutorial Java
4 lexical and syntax
ARCHITECTURE MICROSERVICE : TOUR D’HORIZON DU CONCEPT ET BONNES PRATIQUES
Introduction to jest
Ad

Similar to Next-level integration with Spring Data Elasticsearch (20)

PDF
Eland: A Python client for data analysis and exploration
PDF
The importance of normalizing your security data to ECS
PDF
Public sector keynote
PDF
Finding relevant results faster with Elasticsearch
PDF
Managing the Elastic Stack at Scale
PDF
Breaking silos between DevOps and SecOps with Elastic
PDF
How we built this: Data tiering, snapshots, and asynchronous search
PDF
Automating the Elastic Stack
PDF
From secure VPC links to SSO with Elastic Cloud
PDF
Migrating to Elasticsearch Service on Elastic Cloud
PDF
Introduction to Visualforce for Mobile Devices
PDF
Elasticsearch: From development to production in 15 minutes
PPT
Salesforce1 Platform for programmers
PDF
SIEM, malware protection, deep data visibility — for free
PDF
Autoscaling: From zero to production seamlessly
PDF
Streamline search with Elasticsearch Service on Microsoft Azure
PDF
Streamline search with Elasticsearch Service on Microsoft Azure
PDF
Securing the Elastic Stack for free
PDF
Elastic Cloud keynote
PDF
Creating stellar customer support experiences using search
Eland: A Python client for data analysis and exploration
The importance of normalizing your security data to ECS
Public sector keynote
Finding relevant results faster with Elasticsearch
Managing the Elastic Stack at Scale
Breaking silos between DevOps and SecOps with Elastic
How we built this: Data tiering, snapshots, and asynchronous search
Automating the Elastic Stack
From secure VPC links to SSO with Elastic Cloud
Migrating to Elasticsearch Service on Elastic Cloud
Introduction to Visualforce for Mobile Devices
Elasticsearch: From development to production in 15 minutes
Salesforce1 Platform for programmers
SIEM, malware protection, deep data visibility — for free
Autoscaling: From zero to production seamlessly
Streamline search with Elasticsearch Service on Microsoft Azure
Streamline search with Elasticsearch Service on Microsoft Azure
Securing the Elastic Stack for free
Elastic Cloud keynote
Creating stellar customer support experiences using search
Ad

More from Elasticsearch (20)

PDF
An introduction to Elasticsearch's advanced relevance ranking toolbox
PDF
From MSP to MSSP using Elastic
PDF
Cómo crear excelentes experiencias de búsqueda en sitios web
PDF
Te damos la bienvenida a una nueva forma de realizar búsquedas
PDF
Tirez pleinement parti d'Elastic grâce à Elastic Cloud
PDF
Comment transformer vos données en informations exploitables
PDF
Plongez au cœur de la recherche dans tous ses états.
PDF
Modernising One Legal Se@rch with Elastic Enterprise Search [Customer Story]
PDF
An introduction to Elasticsearch's advanced relevance ranking toolbox
PDF
Welcome to a new state of find
PDF
Building great website search experiences
PDF
Keynote: Harnessing the power of Elasticsearch for simplified search
PDF
Cómo transformar los datos en análisis con los que tomar decisiones
PDF
Explore relève les défis Big Data avec Elastic Cloud
PDF
Comment transformer vos données en informations exploitables
PDF
Transforming data into actionable insights
PDF
Opening Keynote: Why Elastic?
PDF
Empowering agencies using Elastic as a Service inside Government
PDF
The opportunities and challenges of data for public good
PDF
Enterprise search and unstructured data with CGI and Elastic
An introduction to Elasticsearch's advanced relevance ranking toolbox
From MSP to MSSP using Elastic
Cómo crear excelentes experiencias de búsqueda en sitios web
Te damos la bienvenida a una nueva forma de realizar búsquedas
Tirez pleinement parti d'Elastic grâce à Elastic Cloud
Comment transformer vos données en informations exploitables
Plongez au cœur de la recherche dans tous ses états.
Modernising One Legal Se@rch with Elastic Enterprise Search [Customer Story]
An introduction to Elasticsearch's advanced relevance ranking toolbox
Welcome to a new state of find
Building great website search experiences
Keynote: Harnessing the power of Elasticsearch for simplified search
Cómo transformar los datos en análisis con los que tomar decisiones
Explore relève les défis Big Data avec Elastic Cloud
Comment transformer vos données en informations exploitables
Transforming data into actionable insights
Opening Keynote: Why Elastic?
Empowering agencies using Elastic as a Service inside Government
The opportunities and challenges of data for public good
Enterprise search and unstructured data with CGI and Elastic

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Approach and Philosophy of On baking technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Spectroscopy.pptx food analysis technology
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Encapsulation theory and applications.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPT
Teaching material agriculture food technology
PPTX
sap open course for s4hana steps from ECC to s4
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
A comparative analysis of optical character recognition models for extracting...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Diabetes mellitus diagnosis method based random forest with bat algorithm
Approach and Philosophy of On baking technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
NewMind AI Weekly Chronicles - August'25-Week II
Spectroscopy.pptx food analysis technology
MYSQL Presentation for SQL database connectivity
Network Security Unit 5.pdf for BCA BBA.
Building Integrated photovoltaic BIPV_UPV.pdf
Encapsulation theory and applications.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Big Data Technologies - Introduction.pptx
Assigned Numbers - 2025 - Bluetooth® Document
Teaching material agriculture food technology
sap open course for s4hana steps from ECC to s4
gpt5_lecture_notes_comprehensive_20250812015547.pdf
The AUB Centre for AI in Media Proposal.docx
A comparative analysis of optical character recognition models for extracting...
Mobile App Security Testing_ A Comprehensive Guide.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11

Next-level integration with Spring Data Elasticsearch

  • 1. 1 ElasticON Global Peter-Josef Meisch Spring Data Elasticsearch Project Lead
  • 2. 2 This presentation and the accompanying oral presentation contain forward-looking statements, including statements concerning plans for future offerings; the expected strength, performance or benefits of our offerings; and our future operations and expected performance. These forward-looking statements are subject to the safe harbor provisions under the Private Securities Litigation Reform Act of 1995. Our expectations and beliefs in light of currently available information regarding these matters may not materialize. Actual outcomes and results may differ materially from those contemplated by these forward-looking statements due to uncertainties, risks, and changes in circumstances, including, but not limited to those related to: the impact of the COVID-19 pandemic on our business and our customers and partners; our ability to continue to deliver and improve our offerings and successfully develop new offerings, including security-related product offerings and SaaS offerings; customer acceptance and purchase of our existing offerings and new offerings, including the expansion and adoption of our SaaS offerings; our ability to realize value from investments in the business, including R&D investments; our ability to maintain and expand our user and customer base; our international expansion strategy; our ability to successfully execute our go-to-market strategy and expand in our existing markets and into new markets, and our ability to forecast customer retention and expansion; and general market, political, economic and business conditions. Additional risks and uncertainties that could cause actual outcomes and results to differ materially are included in our filings with the Securities and Exchange Commission (the “SEC”), including our Annual Report on Form 10-K for the most recent fiscal year, our quarterly report on Form 10-Q for the most recent fiscal quarter, and any subsequent reports filed with the SEC. SEC filings are available on the Investor Relations section of Elastic’s website at ir.elastic.co and the SEC’s website at www.sec.gov. Any features or functions of services or products referenced in this presentation, or in any presentations, press releases or public statements, which are not currently available or not currently available as a general availability release, may not be delivered on time or at all. The development, release, and timing of any features or functionality described for our products remains at our sole discretion. Customers who purchase our products and services should make the purchase decisions based upon services and product features and functions that are currently available. All statements are made only as of the date of the presentation, and Elastic assumes no obligation to, and does not currently intend to, update any forward-looking statements or statements relating to features or functions of services or products, except as required by law. Forward-Looking Statements
  • 3. 3 Nothing will stop you being creative more effectively as the fear of making a mistake. John Cleese
  • 5. What is Spring Data Elasticsearch?
  • 6. “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.”
  • 8. 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(); } }
  • 9. 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(); } }
  • 10. 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(); } }
  • 11. 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(); } }
  • 12. 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(); } }
  • 13. 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();
  • 15. Entity definition public class Person { @Id private String id; private String lastName; private String firstName; private LocalDate birthDate; }
  • 16. Entity definition @Document(indexName = "person") public class Person { @Id private String id; private String lastName; private String firstName; private LocalDate birthDate; }
  • 17. 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; }
  • 18. 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; }
  • 20. IndexOperations ● index creation and deletion ● index settings ● index mappings ● index templates ● alias management ● refresh operation
  • 21. 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);
  • 22. 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);
  • 23. 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);
  • 24. 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) ;
  • 25. DocumentOperations ● save ● get ● delete ● exists ● update
  • 27. 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);
  • 28. StringQuery Query query = new StringQuery( "{" + " "bool": {" + " "must": [" + " {" + " "match": {" + " "lastName": "Smith"" + " }" + " }" + " ]" + " }" + "}"); SearchHits<Person> searchHits = operations.search(query, Person.class);
  • 29. 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);
  • 31. SearchHit<T ● id ● index name ● the entity of type T ● score ● sort values ● highlight fields ● inner hits
  • 32. SearchHits<T ● number of total hits ● total hits relation (eq, gte) ● list of SearchHit<T> objects ● max score ● aggregations
  • 34. Repository interface PersonRepository extends ElasticsearchRepository< Person, String > { } // ElasticsearchRepository // +PagingAndSortingRepository // + CrudRepository // + Repository
  • 36. Repository methods interface PersonRepository extends ElasticsearchRepository< Person, String > { List<Person> searchByFirstName(String name); List<Person> findByFirstNameOrderByLastNameAsc(String name); List<Person> queryByBirthDateBefore(LocalDate date); }
  • 37. Repository methods interface PersonRepository extends ElasticsearchRepository<Person, String> { @Query(value = "{"fuzzy":{"lastName":"?0"}}") List<Person> findByLastNameFuzzy(String lastName); }
  • 38. Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> { List<Person> searchByFirstName(String name); }
  • 39. Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> { Stream<Person> searchByFirstName(String name); }
  • 40. Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> { List<SearchHit<Person>> searchByFirstName(String name); }
  • 41. Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> { Stream<SearchHit<Person>> searchByFirstName(String name); }
  • 42. Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> { SearchHits<Person> searchByFirstName(String name); }
  • 43. Repository method return types interface PersonRepository extends ElasticsearchRepository<Person, String> { SearchPage<Person> searchByFirstName(String name, Pageable page); }
  • 44. 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) ; } }
  • 45. 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"); // ... });
  • 47. 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; } }
  • 48. 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); } }
  • 49. We need contributors! Spring Data Elasticsearch is a community-driven project