Springboot集成ES。分页、排序

  • Post author:
  • Post category:其他

首先需要创建一个springboot项目这里就不做演示啦,自己Google吧~~https://start.spring.io/ 地址放这里

还需要安装ES,自己Google,没看到标题是springboot集成ES。当然安装很简单啦,个人感觉比安装MySQL还简单

这里附上中文文档https://es.xiaoleilu.com/     还有陌生人大哥写的安装教程 https://www.cnblogs.com/yanketao/p/10983556.html

好啦就这样啦!(哦~~还有JDK1.8感觉这是废话)

 

下面我们进入正题开搞。

导包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

yml文件

spring:
  data:
    elasticsearch:
      cluster-name: elasticsearch
      cluster-nodes: localhost:9300
      repositories:
        enabled: true

自己安装的时候可以自己配置cluster-name,cluster-nodes记住用9300别用9200,我就踩坑了

 

下面开始操作了把好自己的小眼神。

 

实体类

注意这个indexName必须小写(小坑)

package com.mcadmin.server.thirdparty.es;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "testuser",type = "testusertype" ,shards = 1,replicas = 0, refreshInterval = "-1")
public class User {

    @Id
    private Integer id;

    private String name;

    private Integer age;

    private long time;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }
}

 

接口继承ElasticsearchRepository<自己的实体类,Integer>

package com.mcadmin.server.thirdparty.es;

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface UserRepository extends ElasticsearchRepository<User,Integer> {

    /**
     * 查询用户信息
     * @param id
     * @return
     */
    User queryUserById (int id);



}

 

简单的带条件查询可以直接拼接提示出来方法名查询(很多方法根据你实体类的名字生成的,具体自己去试),此处不能随意命名

 

 

 

Controller层(简单的增删改查)

package com.mcadmin.server.thirdparty.es;

import com.mcadmin.server.util.UnixUtil;
import org.elasticsearch.common.Strings;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.FieldSortBuilder;
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.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/mcapi/pub/esUser")
public class UserController {

    @Autowired
    private UserRepository userRepository;


    @RequestMapping("/addUser")
    public User addUser(@RequestParam int id,
                        @RequestParam String name,
                        @RequestParam int age) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setAge(age);
        user.setTime(UnixUtil.getNowTimeStamp()); //当前时间戳
        userRepository.save(user);
        return user;
    }

    @RequestMapping("/delUser")
    public String delUser(@RequestParam int id) {
        User user = userRepository.queryUserById(id);
        userRepository.delete(user);
        return "success";
    }

    @RequestMapping("/updateUser")
    public String updateUser(@RequestParam int id,
                             @RequestParam String name) {
        User user = userRepository.queryUserById(id);
        user.setName(name);
        userRepository.save(user);
        return "success";
    }

    @RequestMapping("/getUser")
    public User getUser(@RequestParam int id) {
        User user = userRepository.queryUserById(id);
        return user;
    }


}

 

下面又有大料来咯!

上面都是简单查询,我们在实际开发过程中随便写个列表都要分页、排序、多条件查询。eeeee··········

直接上代码吧!!!!

/**
     * 模糊、分页、排序查询
     *
     * @param id
     * @param name
     * @param pageindex 页码
     * @param pageSize  每页多少条
     * @return
     */
    @RequestMapping("getLikeUser")
    public List<User> getLikeUser(@RequestParam int id,
                                  @RequestParam String name,
                                  @RequestParam int pageindex,
                                  @RequestParam int pageSize) {
        //检索条件
        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        if (id != 0)
            bqb.must(QueryBuilders.matchPhraseQuery("id", id));
        if (!Strings.isEmpty(name))
            bqb.must(QueryBuilders.matchPhraseQuery("name", name));
        //排序条件
        FieldSortBuilder fsb = SortBuilders.fieldSort("time").order(SortOrder.DESC);
        //分页条件
        pageindex = pageindex == 0 ? 1 : pageindex;
        pageSize = pageSize == 0 ? 10 : pageSize;
        Pageable pageable = PageRequest.of(pageindex - 1, pageSize);
        //构建查询
        SearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(bqb)
                .withSort(fsb)
                .withPageable(pageable)
                .build();
        Page<User> searchResponse = userRepository.search(query);

        return searchResponse.getContent();
    }

 

——————————————————————————————————————————————

各位大神们,还有啥坑或者哪里需要补充的欢迎评论!,我及时更新~~~~


版权声明:本文为weixin_42619846原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。