Integrating SpringBoot with Spring Data Elasticsearch: Complete Guide and Sample Code
This article provides a step‑by‑step tutorial on integrating SpringBoot with Spring Data Elasticsearch, covering required dependencies, configuration classes, entity mapping, repository interfaces, service implementations, controller endpoints, and testing instructions, complete with runnable code examples.
This tutorial demonstrates how to integrate SpringBoot with Spring Data Elasticsearch to perform index and document CRUD operations using Java APIs such as ElasticsearchRestTemplate and ElasticsearchRepository.
Prerequisites : Elasticsearch 7.9.3 and SpringBoot 2.4.x are used. The appropriate Maven dependencies are added to pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.71</version>
</dependency>
</dependencies>The application.properties file enables Elasticsearch repositories and sets the REST endpoint:
spring.data.elasticsearch.repositories.enabled = true
spring.elasticsearch.rest.uris=localhost:9200ElasticsearchRestTemplate Configuration :
@Configuration
public class ElasticsearchRestTemplateConfig extends AbstractElasticsearchConfiguration {
@Value("${spring.elasticsearch.rest.uris}")
private String uris;
@Override
public RestHighLevelClient elasticsearchClient() {
ClientConfiguration configuration = ClientConfiguration.builder()
.connectedTo(uris)
.build();
return RestClients.create(configuration).rest();
}
}Domain Model (mapped to an Elasticsearch index):
@Data
@Document(indexName = "order", shards = 1, replicas = 1)
public class Order implements Serializable {
@Id
private Integer id;
@Field(type = FieldType.Keyword)
private Long orderNo;
@Field(type = FieldType.Integer)
private Integer orderType;
@Field(type = FieldType.Long)
private Long orderAmount;
@Field(type = FieldType.Text, analyzer = "ik_smart", searchAnalyzer = "ik_max_word")
private String orderDesc;
@Field(type = FieldType.Keyword, analyzer = "ik_smart", searchAnalyzer = "ik_max_word")
private String username;
@Field(type = FieldType.Keyword, analyzer = "ik_smart", searchAnalyzer = "ik_max_word")
private String userPhone;
private Map<String, List<String>> highlights;
}Repository :
public interface OrderRepository extends ElasticsearchRepository<Order, Integer> {}Service Interface and Implementation provide methods for batch save, delete, update, pagination, conditional search, and highlighted search. The implementation uses ElasticsearchRestTemplate and CriteriaQuery to build queries and process SearchHits.
public interface OrderService {
void saveAll(List<Order> orders);
Order findById(Integer id);
void deleteById(Integer id);
void updateById(Order order);
PageResponse<Order> findList(Order order, Integer pageIndex, Integer pageSize);
PageResponse<Order> findAll(Integer pageIndex, Integer pageSize);
PageResponse<Order> findHighlight(Order order, Integer pageIndex, Integer pageSize);
}
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
@Autowired
OrderRepository orderRepository;
@Autowired
ElasticsearchRestTemplate elasticsearchRestTemplate;
// method implementations omitted for brevity
}Controller exposes REST endpoints for index creation/deletion and document operations (saveBatch, deleteById, updateById, findById, findAll, findList, findHighlight). Example of index creation:
@RequestMapping("/index/")
@RestController
public class IndexController {
@Autowired
ElasticsearchRestTemplate elasticsearchRestTemplate;
@GetMapping("create")
public String create(@RequestParam String indexName) {
IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName));
if (indexOperations.exists()) {
return "索引已存在";
}
indexOperations.create();
return "索引创建成功";
}
@GetMapping("delete")
public String delete(@RequestParam String indexName) {
IndexOperations indexOperations = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName));
indexOperations.delete();
return "索引删除成功";
}
}Testing : Use Postman or any HTTP client to call the controller endpoints. The full source code is available at https://github.com/jackson-zb/es-client .
The article also includes promotional sections (e.g., interview question packs, community links) which are not part of the technical guide.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
