Spring Data Elasticsearch operates ES in a simpler way than MP

springDataES:

Spring Data Elasticsearch is part of the Spring Data project, which provides data access support integrated with Elasticsearch. It simplifies the development process of using the Elasticsearch data store in Spring applications, making it easier for developers to perform data indexing, searching, and querying operations.

Key Features and Functions:

  1. Repository abstraction layer: Spring Data Elasticsearch provides a Repository abstraction layer, similar to JPA. By inheriting ElasticsearchRepositorythe interface, you can easily define and use various query methods without explicitly writing Elasticsearch query statements.
  2. Automatically map entities: Spring Data Elasticsearch will automatically map entity classes to Index (index) and Type (type) in Elasticsearch, and you can also specify mapping rules, such as field data types, tokenizers, etc.
  3. Support for advanced queries: Spring Data Elasticsearch supports building complex queries, including full-text search, range query, filter query, aggregation operations, etc. You can use the query builder to generate Elasticsearch queries.
  4. Support for highlighting: You can use the highlighting function to mark keywords that match your query in the search results, thereby improving the visualization of the search results.
  5. Support for asynchronous operations: Spring Data Elasticsearch supports asynchronous operations, which is very useful for processing large amounts of data or time-consuming query operations.
  6. Support paging and sorting: Spring Data Elasticsearch supports paging and sorting functions, allowing you to perform paging and sorting operations on search results.
  7. Integration with Spring Ecosystem: Spring Data Elasticsearch seamlessly integrates with other components of the Spring framework, such as Spring Boot, Spring MVC, Spring Security, etc.
  8. Multi-version support: Spring Data Elasticsearch supports multiple Elasticsearch versions, and you can choose the corresponding Spring Data Elasticsearch version according to your Elasticsearch cluster version.

After all, it is an orm framework. You only need to create the entity class and the corresponding index will be created in the corresponding NoSql (a start-up project) so it is very nice. I think you can operate it as long as you have used MP, and it is simpler than MP.

helloworld CRUD:

Without further ado, go directly to the demo:

1. yaml configuration file:

elasticsearch:
  host: 10.14.0.77
  port: 9200
logging:
  level:
    com:
      es: debug

2. config configuration class:

package com.example.springdataes.config;


import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

/**
 * @project springdataES
 * @author capture or new
 */
@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
@Data
public class ElasticsearchConfig  extends AbstractElasticsearchConfiguration {
    
    

    private String host ;
    private Integer port ;

    @Override
    public RestHighLevelClient elasticsearchClient() {
    
    
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
        RestHighLevelClient restHighLevelClient = new
                RestHighLevelClient(builder);
        return restHighLevelClient;
    }
}

3. For the meaning of pojo class annotations, please refer to Spring official website .

package com.example.springdataes.pojo;

import lombok.Data;
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;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * @project springdataES
 * @author capture or new
 */
@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)
    private String orderDesc;

    @Field(type = FieldType.Keyword)
    private String username;

    @Field(type = FieldType.Keyword)
    private String userPhone;

    private Map<String, List<String>> highlights;
}

4. Repository interface class:

package com.example.springdataes.repository;

import com.example.springdataes.pojo.Order;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/**
 * @project springdataES
 * @author capture or new
 */
public interface OrderRepository extends ElasticsearchRepository<Order, Integer> {
    
    
}

5. Service interface class:

package com.example.springdataes.service;

import com.example.springdataes.pojo.Order;
import org.springframework.data.domain.Page;

import java.util.List;

/**
 * @project springdataES
 * @author capture or new
 */
public interface OrderService {
    
    
    void saveAll(List<Order> orders);

    Order findById(Integer id);

    void deleteById(Integer id);

    void updateById(Order order);

    List<Order> findList(Order order, Integer pageIndex, Integer pageSize);

    Page<Order> findAll(Integer pageIndex, Integer pageSize);

}

6. Service implementation class:

package com.example.springdataes.service;

import com.example.springdataes.pojo.Order;
import com.example.springdataes.repository.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.HighlightQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @project springdataES
 * @author capture or new
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    
    
    @Autowired
    OrderRepository orderRepository;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public void saveAll(List<Order> orders) {
    
    
        orderRepository.saveAll(orders);
    }

    @Override
    public void deleteById(Integer id) {
    
    
        orderRepository.deleteById(id);
    }

    @Override
    public void updateById(Order order) {
    
    
        orderRepository.save(order);
    }

    @Override
    public List<Order> findList(Order order, Integer pageIndex, Integer pageSize) {
    
    
        CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()
                .and(new Criteria("orderDesc").contains(order.getOrderDesc()))
                .and(new Criteria("orderNo").is(order.getOrderNo())))
                .setPageable(PageRequest.of(pageIndex, pageSize));

        SearchHits<Order> searchHits = elasticsearchRestTemplate.search(criteriaQuery, Order.class);
        List<Order> result = searchHits.get().map(item -> item.getContent()).collect(Collectors.toList());
        System.out.println(result);
        return result;
    }

    @Override
    public Page<Order> findAll(Integer pageIndex, Integer pageSize) {
    
    
        Page<Order> page = orderRepository.findAll(PageRequest.of(pageIndex, pageSize));
        System.out.println(page.getTotalElements());
        System.out.println(page.getContent());

        return page;
    }

    @Override
    public Order findById(Integer id) {
    
    
        return orderRepository.findById(id).orElse(null);
    }


}


7. Controller class:

package com.example.springdataes.controller;

import com.example.springdataes.pojo.Order;
import com.example.springdataes.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @project springdataES
 * @author capture or new
 */
@RequestMapping("/doc/")
@RestController
public class DocController {
    
    

    @Autowired
    OrderService orderService;

    /**
     * 批量创建
     */
    @PostMapping("saveBatch")
    public String saveBatch(@RequestBody List<Order> orders) {
    
    
        if (CollectionUtils.isEmpty(orders)) {
    
    
            return "文档不能为空";
        }
        orderService.saveAll(orders);
        return "保存成功";
    }

    /**
     * 根据id删除
     */
    @GetMapping("deleteById")
    public String deleteById(@RequestParam Integer id) {
    
    
        orderService.deleteById(id);
        return "删除成功";
    }

    /**
     * 根据id更新
     */
    @PostMapping("updateById")
    public String updateById(@RequestBody Order order) {
    
    
        orderService.updateById(order);
        return "更新成功";
    }

    /**
     * 根据id搜索
     */
    @GetMapping("findById")
    public String findById(@RequestParam Integer id) {
    
    
        return orderService.findById(id).toString();
    }

    /**
     * 分页搜索所有
     */
    @GetMapping("findAll")
    public String findAll(@RequestParam Integer pageIndex, @RequestParam Integer pageSize) {
    
    
        return orderService.findAll(pageIndex, pageSize).toString();
    }

    /**
     * 条件分页搜索
     */
    @GetMapping("findList")
    public String findList(@RequestBody Order order, @RequestParam Integer pageIndex, @RequestParam Integer pageSize) {
    
    
        return orderService.findList(order, pageIndex, pageSize).toString();
    }

}

interface:

Write the tests for the two interfaces below. Easy for you to operate

1. Increase:

Interface Type:POST

address:http://localhost:8080/doc/saveBatch

Request body:

[
    {
    
    
        "id":2,
        "orderNo":78,
        "orderType":2,
        "orderAmount":77,
        "orderDesc":"demo",
        "username":"zhangsan",
        "userPhone":"17828493848"
    }
]

2. Conditional page search

Interface Type:GET

address:http://localhost:8080/doc/findList?pageIndex=0&pageSize=5

Request body:


    {
    
    
        "orderNo":78,
        "orderDesc":"demo"
    }

Guess you like

Origin blog.csdn.net/qq_63946922/article/details/132035713