elasticsearch学习1—springboot整合:基本使用,分页

1、创建springboot项目,pom依赖如下:


        org.springframework.boot
        spring-boot-starter-web
    

    
        org.projectlombok
        lombok
        true
    

    
    
        org.springframework.boot
        spring-boot-starter-data-elasticsearch
    

    
        org.springframework.boot
        spring-boot-starter-test
        test
        
            
                org.junit.vintage
                junit-vintage-engine
            
        
    



    
        
            org.springframework.cloud
            spring-cloud-dependencies
            ${spring-cloud.version}
            pom
            import
        
    



    
        
            org.springframework.boot
            spring-boot-maven-plugin
        
    



    
        aliyun-repos
        http://maven.aliyun.com/nexus/content/groups/public/
        
            false
        
    



    
        aliyun-plugin
        http://maven.aliyun.com/nexus/content/groups/public/
        
            false
        
    

二、接口:UserDao

/**
 * @author: windy
 * @create: 2019-11-30 15:51
 */
public interface UserDao extends ElasticsearchRepository {
}

三、实体类

/**
 * @author: windy
 * @create: 2019-11-30 15:47
 */
@Document(indexName = "info",type = "user")
@Data
public class User {

    @Id
    private String id;

    private String name;

    private Integer age;

    private Integer sex;
}

四、controller

@Controller
public class EsController {

    @Autowired
    private UserDao userDao;

    @ResponseBody
    @RequestMapping("add")
    public User addUser(@RequestBody User user){
       return userDao.save(user);
    }

    @ResponseBody
    @RequestMapping("findById")
    public Optional findById(String id){
        return userDao.findById(id);
    }

    /**
     * 分页
     */
    @ResponseBody
    @RequestMapping("/search")
    public Page search(String keyWord, @PageableDefault(page = 0, value = 3) Pageable pageable) {
        // 查询所有的
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(keyWord)) {
            // 模糊查询 一定要ik中文
            MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", keyWord);
            boolQuery.must(matchQuery);
        }
        Page page = userDao.search(boolQuery, pageable);
        return page;
    }
}

五、启动类:

@SpringBootApplication
@EnableElasticsearchRepositories(basePackages = "com.windy.springbootes.repository")
public class SpringbootEsApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootEsApplication.class, args);
    }

}

六、利用postman测试

1、添加数据

elasticsearch学习1—springboot整合:基本使用,分页_第1张图片

2、分页查询,size=3

elasticsearch学习1—springboot整合:基本使用,分页_第2张图片

 

你可能感兴趣的:(elasticsearch)