SpringBoot集成ElasticSearch

1、下载安装启动ElasticSearch

https://www.cnblogs.com/hualess/p/11540477.html

 

2、SpringBoot集成ElasticSearch

https://www.cnblogs.com/huanshilang/p/12622356.html

https://segmentfault.com/a/1190000018625101

类似JPA

 

 

实践:

1)实体类

package com.example.demo.elasticsearch;


import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.elasticsearch.annotations.Document;

import javax.persistence.Id;

@Data
@Accessors(chain = true)
@Document(indexName = "blog", type = "java")
public class EsUser {

    @Id
    private String id;
    private String email;
    private String password;
    private String username;
}

2)Repository

package com.example.demo.elasticsearch;

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

import java.util.List;

@Repository
public interface EsUserRepository extends ElasticsearchRepository<EsUser, String> {

    List<EsUser> findByUsernameLike(String username);

}

3)Controller

package com.example.demo.elasticsearch;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/es/user")
public class EsUserController {

    @Autowired
    EsUserRepository esUserRepository;


    @PostMapping(value = "/1")
    public EsUser test2() {
        EsUser esUser = new EsUser();
        esUser.setUsername("vvv");
        esUser.setEmail("fasdvvv");
        esUser.setPassword("ffffffff");
        return esUserRepository.save(esUser);
    }

    @GetMapping(value = "/{id}")
    public EsUser test1(@PathVariable String id) {
        return esUserRepository.findById(id).get();
    }


    @GetMapping(value = "/list")
    public List<EsUser> test3(@RequestParam String username) {
        return esUserRepository.findByUsernameLike(username);
    }


}

4)kibana结果

 

 5)简单说明

id最好为String,会自动生成,查询的时候可以使用findby...like等语句(和JPA一样),这种简单用法和把数据放到mysql好像没啥区别

posted @ 2021-04-13 17:11  袁骞骞  阅读(122)  评论(0编辑  收藏  举报