Integrating Elasticsearch with Spring Boot for Full CRUD Operations
This guide walks through integrating Spring Data Elasticsearch into a Spring Boot application, covering entity mapping annotations, repository creation, service layer implementation, and unit tests to perform create, read, update, delete, and fuzzy search operations on Elasticsearch indices.
Scenario : Quickly set up Spring Boot with Elasticsearch and record integration pitfalls.
1. Elasticsearch Object Mapping : Use Spring Data Elasticsearch annotations to map Java entities to JSON documents stored in Elasticsearch. Key annotations include @Document (indexName, createIndex, shards, replicas, etc.), @Id, @Field (type, name, store, analyzer, etc.), @Transient, and @PersistenceConstructor. Example entity:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
@Document(indexName="books", createIndex=true)
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ElasticBook {
@Id
private Integer id;
@Field(type = FieldType.Text)
private String name;
@Field(type = FieldType.Text)
private String summary;
@Field(type = FieldType.Integer)
private Integer price;
}2. CRUD Repository : Create an interface extending ElasticsearchRepository<ElasticBook,Integer>. Custom query methods follow Spring Data naming conventions, e.g., List<ElasticBook> findByName(String name);. No implementation needed; Spring generates it.
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ElasticSearchRepository extends ElasticsearchRepository<ElasticBook,Integer> {
List<ElasticBook> findByName(String name);
}3. Service Layer : Define an interface with CRUD methods and a concrete implementation that delegates to the repository.
public interface IElasticSearchService {
void save(ElasticBook book);
ElasticBook findById(Integer id);
void update(ElasticBook book);
void deleteById(Integer id);
List<ElasticBook> findByName(String name);
}
@Service
public class ElasticSearchServiceImpl implements IElasticSearchService {
@Autowired
private ElasticSearchRepository repository;
@Override public void save(ElasticBook book) { repository.save(book); }
@Override public ElasticBook findById(Integer id) { return repository.findById(id).get(); }
@Override public void update(ElasticBook book) { repository.save(book); }
@Override public void deleteById(Integer id) { repository.deleteById(id); }
@Override public List<ElasticBook> findByName(String name) { return repository.findByName(name); }
}4. Unit Tests : Use SpringRunner and SpringBootTest to verify index creation, save, find, update, delete, and fuzzy search. Example test snippets:
@Test
public void connecTest() throws IOException {
CreateIndexRequest request = new CreateIndexRequest("test");
CreateIndexResponse response = highLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
highLevelClient.close();
}
@Test
public void saveTest() throws IOException {
ElasticBook book = ElasticBook.builder().id(1).name("书名1").summary("霸道的程序猿").price(100).build();
iElasticSearchService.save(book);
System.out.println("保存成功");
}
// similar tests for find, update, delete, findByNameTest execution screenshots show successful index creation, saved documents, retrieved records, updated fields, and fuzzy search results.
After the basic tutorial, advanced query features such as counting, sorting, pagination, and conditional filters can be explored in the official Spring Data Elasticsearch documentation.
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.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
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.
