淘先锋技术网

首页 1 2 3 4 5 6 7

1、安装依赖

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

2、配置地址

spring:
  elasticsearch:
    uris: http://localhost:9200

3、新建测试实体类

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

@Data
@Document(indexName = "article") //索引名称
public class ElasticEntity {
    @Id
    private String id;

    private String name;

    private String address;

    private Integer age;
}

4、新建DAO层接口,用于交互数据

import com.example.springboot3test.entity.ElasticEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ElasticRepository extends ElasticsearchRepository<ElasticEntity,String> {
    //查询全部
    List<ElasticEntity> findByNameLike(String name);
    //分页条件查询
    Page<ElasticEntity> findByAddressLike(String name, Pageable pageable);

}

5、测试代码

import com.example.springboot3test.dao.ElasticRepository;
import com.example.springboot3test.entity.ElasticEntity;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/elastic")
public class ElasticController {
    @Resource
    private ElasticRepository elasticRepository;

    //新增和插入
    @PostMapping("/add")
    public String insert(@RequestBody ElasticEntity elasticEntity){
        elasticRepository.save(elasticEntity);
        return "OK";
    }

    //获取所有
    @GetMapping("/getAll")
    public Iterable<ElasticEntity> getAll(){
        return elasticRepository.findAll();
    }

    //分页查询
    @GetMapping("/getAllByPage/{page}/{pageSize}")
    public Page<ElasticEntity> getAllByPage(@PathVariable("page") Integer page,
                                            @PathVariable("pageSize") Integer pageSize){
        PageRequest pageRequest = PageRequest.of(page-1,pageSize);
        return elasticRepository.findAll(pageRequest);
    }

    @GetMapping("/findByNameLike/{name}")
    public List<ElasticEntity> findByNameLike(@PathVariable("name") String name){
        return elasticRepository.findByNameLike(name);
    }
    //分页查询
    @PostMapping("/findByAddressLikePage")
    public Page<ElasticEntity> findByAddressLikePage(@RequestBody Map<String,String> params){
        Integer page=Integer.valueOf(params.get("page"));
        Integer pageSize=Integer.valueOf(params.get("pageSize"));
        PageRequest pageRequest = PageRequest.of(page-1,pageSize);
        return elasticRepository.findByAddressLike(params.get("name"),pageRequest);
    }
}