springboot2.2.x整合elasticsearch7.6(01基礎查詢)

0.docker部署es並添加ik分詞器

1.部署elasticsearch
docker pull docker.elastic.co/elasticsearch/elasticsearch:7.6.2
docker run -d --name es -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -d elasticsearch:7.6.2

2.ik
docker cp e:/es/elasticsearch-analysis-ik-6.7.2.zip  containerId:/usr/share/elasticsearch/plugins   拷貝
docker exec -it containerId /bin/bash    進入docker:elasticsearch目錄
unzip elasticsearch-analysis-ik-6.7.2.zip       解壓
rm -rf elasticsearch-analysis-ik-6.7.2.zip    刪除壓縮包-->然後重啓即可

 

1.依賴

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

2.yml設置

spring:
  elasticsearch:
    rest:
      uris: http://192.168.1.102:9200

3.dataObject

@Data
@Accessors(chain = true)
@Document(indexName = "stu")
public class Student {

    @Id
    private Integer id;
    @Field(type = FieldType.Keyword)
    private String firstName;
    @Field(type = FieldType.Keyword)
    private String secondName;
    @Field(type = FieldType.Integer)
    private Integer age;
    @Field(type = FieldType.Text,analyzer = "ik_max_word")
    private String introduce;
}

4.repository

public interface StudentRepository extends ElasticsearchRepository<Student,Long> {
    Page<Student> findByFirstName(String firstName, Pageable pageable);
    Page<Student> findByIntroduceLike(String content,Pageable pageable);
}

5.controller

@RestController
@RequestMapping("/es")
public class ElasticController {

    @Autowired
    private StudentRepository repository;

    @RequestMapping(value = "/init",method = RequestMethod.GET)
    public Map<String,String> init(){
        Map<String,String> map=new HashMap<>();
        repository.save(new Student().setId(0).setAge(27).setFirstName("鄭").setSecondName("先生").setIntroduce("寧波工程學院20xx屆學生"));
        repository.save(new Student().setId(1).setAge(27).setFirstName("張").setSecondName("女士").setIntroduce("台州學院20xx屆學生"));
        map.put("code","200");
        return map;
    }

    @RequestMapping(value = "/stuGet/{name}",method = RequestMethod.GET)
    public Map<String,Object> stuGet(@PathVariable String name){
        Map<String,Object> map=new HashMap<>();
        Pageable pageable= PageRequest.of(0,10);
        Page<Student> stus = repository.findByFirstName(name, pageable);
        List<Student> content = stus.getContent();
        map.put("stus",content);
        map.put("code","200");
        List<Student> content1 = repository.findByIntroduceLike(name, pageable).getContent();
        map.put("stus2",content1);
        return map;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章