Backend Development 9 min read

Integrating Spring Data Elasticsearch with Spring Boot: Configuration, Entity, Repository, and Query Examples

This tutorial demonstrates how to set up Elasticsearch 7.6 with the IK analyzer in a Spring Boot 2.3 project, import the appropriate Spring Data Elasticsearch dependency, configure the client, define indexed entity classes, create repository interfaces, and implement REST controllers for CRUD, pagination, and highlighted search queries, complete with code examples and test results.

Top Architect
Top Architect
Top Architect
Integrating Spring Data Elasticsearch with Spring Boot: Configuration, Entity, Repository, and Query Examples

The article provides a step‑by‑step guide for integrating Elasticsearch 7.6 (with the IK analyzer) into a Spring Boot 2.3 application.

Environment Preparation

Ensure Elasticsearch 7.6 and the IK analyzer are installed before proceeding.

1. Import Spring Data Elasticsearch Dependency

<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-elasticsearch</artifactId>
  <version>${version}.RELEASE</version>
</dependency>

The version must match the Elasticsearch server version and be compatible with your Spring Boot version.

2. Elasticsearch Configuration Class

@Configuration
public class EsConf {
    @Value("${elasticSearch.url}")
    private String edUrl;

    @Bean
    public RestHighLevelClient client() {
        ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo(edUrl) // Elasticsearch address
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

3. Entity Definition

@Data
@Document(indexName = "user") // index name should match the entity
public class User {
    @Id
    private Integer id;

    @Field(type = FieldType.Auto) // automatic type detection
    private Integer age;

    @Field(type = FieldType.Keyword) // not tokenized
    private String name;

    @Field(type = FieldType.Text, analyzer = "ik_smart", searchAnalyzer = "ik_max_word") // tokenized text
    private String info;
}

4. Repository Interface

public interface EsUserService extends ElasticsearchRepository
{
    // Find by name
    List
findByName(String name);

    // Find by name and info
    List
findByNameAndInfo(String name, String info);
}

5. REST Controller with CRUD and Search

@RestController
public class EsController {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;
    @Autowired
    private EsUserService esUserService;

    private String[] names = {"诸葛亮","曹操","李白","韩信","赵云","小乔","狄仁杰","李四","诸小明","王五"};
    private String[] infos = {"我来自中国的一个小乡村,地处湖南省","我来自中国的一个大城市,名叫上海,人们称作魔都","我来自东北,家住大囤里,一口大碴子话"};

    @GetMapping("saveUser")
    public ResultVO saveUser() {
        elasticsearchTemplate.putMapping(User.class);
        Random random = new Random();
        List
users = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            User user = new User();
            user.setId(i);
            user.setName(names[random.nextInt(9)]);
            user.setAge(random.nextInt(40) + i);
            user.setInfo(infos[random.nextInt(2)]);
            users.add(user);
        }
        Iterable
saved = esUserService.saveAll(users);
        return new ResultVO(saved);
    }

    @GetMapping("getDataById")
    public ResultVO getDataById(Integer id) {
        return new ResultVO(esUserService.findById(id));
    }

    @GetMapping("getAllDataByPage")
    public ResultVO getAllDataByPage() {
        Pageable page = PageRequest.of(0, 10, Sort.Direction.ASC, "id");
        Page
all = esUserService.findAll(page);
        return new ResultVO(all.getContent());
    }

    @GetMapping("getDataByName")
    public ResultVO getDataByName(String name) {
        return new ResultVO(esUserService.findByName(name));
    }

    @GetMapping("getDataByNameAndInfo")
    public ResultVO getDataByNameAndInfo(String name, String info) {
        return new ResultVO(esUserService.findByNameAndInfo(name, info));
    }

    @GetMapping("getHightByUser")
    public ResultVO getHightByUser(String value) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .should(QueryBuilders.matchQuery("info", value))
                .should(QueryBuilders.matchQuery("name", value));
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withHighlightFields(new HighlightBuilder.Field("info"), new HighlightBuilder.Field("name"))
                .withHighlightBuilder(new HighlightBuilder().preTags("
").postTags("
"))
                .build();
        SearchHits
search = elasticsearchTemplate.search(searchQuery, User.class);
        List
users = new ArrayList<>();
        for (SearchHit
hit : search.getSearchHits()) {
            Map
> highlights = hit.getHighlightFields();
            hit.getContent().setName(highlights.get("name") == null ? hit.getContent().getName() : highlights.get("name").get(0));
            hit.getContent().setInfo(highlights.get("info") == null ? hit.getContent().getInfo() : highlights.get("info").get(0));
            users.add(hit.getContent());
        }
        return new ResultVO(users);
    }
}

Testing Results

Several screenshots (omitted here) show successful data insertion, pagination, name‑based queries, combined name‑and‑info queries, and highlighted search results.

The article concludes with a call for discussion and provides links to additional resources, but the core technical content remains a practical guide for backend developers working with Elasticsearch in Spring Boot.

BackendJavaElasticsearchSpring BootRESTSearchSpring Data
Top Architect
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.