Spring Data Elasticsearch比MP都要简单的方式 操作ES

springDataES:

Spring Data Elasticsearch 是 Spring Data 项目中的一部分,它提供了与 Elasticsearch 集成的数据访问支持。它简化了在 Spring 应用程序中使用 Elasticsearch 数据存储的开发过程,使开发人员能够更轻松地执行数据的索引、搜索和查询操作。

主要特点和功能:

  1. Repository 抽象层: Spring Data Elasticsearch 提供了 Repository 抽象层,类似于 JPA。通过继承 ElasticsearchRepository 接口,你可以轻松地定义和使用各种查询方法,而无需显式编写 Elasticsearch 查询语句。
  2. 自动映射实体: Spring Data Elasticsearch 会自动映射实体类到 Elasticsearch 中的 Index(索引)和 Type(类型),同时也可以指定映射规则,例如字段的数据类型、分词器等。
  3. 支持高级查询: Spring Data Elasticsearch 支持构建复杂的查询,包括全文搜索、范围查询、过滤查询、聚合操作等。你可以使用查询构建器来生成 Elasticsearch 查询语句。
  4. 支持高亮显示: 你可以使用高亮功能来标记搜索结果中与查询匹配的关键字,从而提高搜索结果的可视化效果。
  5. 支持异步操作: Spring Data Elasticsearch 支持异步操作,这对于处理大量数据或耗时的查询操作非常有用。
  6. 支持分页和排序: Spring Data Elasticsearch 支持分页和排序功能,允许你对搜索结果进行分页显示和排序操作。
  7. 与 Spring 生态系统整合: Spring Data Elasticsearch 与 Spring 框架的其他组件无缝整合,如 Spring Boot、Spring MVC、Spring Security 等。
  8. 多版本支持: Spring Data Elasticsearch 支持多个 Elasticsearch 版本,你可以根据你的 Elasticsearch 集群版本选择相应的 Spring Data Elasticsearch 版本。

说到底就是一款orm框架。你只需要创建好实体类就会在对应的NoSql中创建对应的索引(一起动项目)所以说十分的nice,我认为你只要用过MP 就会操作,而且比MP更为简单。

helloworld CRUD:

话不多说 直接上demo:

1、yaml配置文件:

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

2、config 配置类:

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、 pojo类 注解含义可查看Spring官网

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 接口类:

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 接口类:

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实现类:

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 类:

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();
    }

}

接口:

下面写两个接口的测试。便于你们操作哦

1、增加:

接口类型:POST

地址: http://localhost:8080/doc/saveBatch

请求体:

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

2、条件分页搜索

接口类型:GET

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

请求体:


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

猜你喜欢

转载自blog.csdn.net/qq_63946922/article/details/132035713