0


springBoot整合ElasticSearch【代码直接复制可用】(超级详细)

前期准备工作

安装Elasticsearch+Kibana

需要先安装好jdk(这个自行下载安装,就不过多说了)

官方下载地址点击下载https://www.elastic.co/cn/downloads/elasticsearch
建议不要下载过高版本的,也不要下载过低版本的,博主6、7、8版本都下载过,为别再出错,建议下载和我同一个版本,博主使用的是7.8.1。具体操作如下:

第一步:
在这里插入图片描述
第二步:
在这里插入图片描述

下载指定安装包后,选择合适的位置保存压缩包,并解压好,打开bin目录,在bin里打开cmd输入elasticsearch或者直接点击bin目录下面的slasticsearch.bat文件:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
成功启动后,由于内部的elasticsearch.yml配置并没有改动,因此可以直接浏览器访问http://localhost:9200/如果有一下信息则证明成功启动:
在这里插入图片描述
由于安装kibana步骤几乎和elasticsearch一样,所以就不多说了。
kibana下载地址点击下载https://www.elastic.co/cn/downloads/past-releases#kibana
经过同样的步骤操作后就可以浏览器访问点击访问http://localhost:5601/app/kibana#/dev_tools/console
在这里插入图片描述
在这里就可以向我们的es中进行数据操作(相当可视化界面)。
最终我们完成了全部的安装操作。

springboot整合Elasticsearch

配置本地连接es文件

#配置ElaticSearch
spring.elasticsearch.hostname=127.0.0.1
spring.elasticsearch.port=9200

连接配置es

@ConfigurationpublicclassEsConfig{//配置本机地址以及端口@Value("${spring.elasticsearch.hostname}")private String hostname;@Value("${spring.elasticsearch.port}")privateint port;/**
     * LowLevelRestConfig
     */@Beanpublic RestClient restClient(){// 如果有多个从节点可以持续在内部new多个HttpHost,参数1是IP,参数2是端口,参数3是通信协议
        RestClientBuilder clientBuilder = RestClient.builder(newHttpHost(hostname, port,"http"));// 设置Header编码
        Header[] defaultHeaders ={newBasicHeader("content-type","application/json")};
        clientBuilder.setDefaultHeaders(defaultHeaders);return clientBuilder.build();}/**
     * HighLevelRestConfig
     */@Beanpublic RestHighLevelClient restHighLevelClient(){// 如果有多个从节点可以持续在内部new多个HttpHost,参数1是IP,参数2是端口,参数3是通信协议returnnewRestHighLevelClient(RestClient.builder(newHttpHost(hostname, port,"http")));}}

下面就可以开始我们的crud操作了,由于单个模块发太过于繁琐,因此我就把我自己简化的每个层业务代码都发出来吧!

controller层

@Api(tags ={"es"})@RestController@RequestMapping("/es")@Slf4jpublicclassEsController{@Autowiredpublic RestHighLevelClient restHighLevelClient;@Autowiredprivate IRestHighLevelClientService restHighLevelClientService;@Autowiredprivate QueryDataService queryDataService;@Autowiredprivate UserService userService;/**
     * 创建索引
     * @return
     * @throws IOException
     */@RequestMapping("/createIndex")@ApiOperation(value ="创建索引", notes ="创建索引")public String createIndex(@RequestBody Index index)throws IOException {//String indexName = "user";
        restHighLevelClientService.createIndex(index.getIndexName());
        log.info("创建 {} 成功",index.getIndexName());return"create "+index.getIndexName()+" success";}/**
     * 查询索引
     * @return
     * @throws IOException
     */@GetMapping("/queryIndex")@ApiOperation(value ="查询索引", notes ="查询索引")public GetResponse contextLoads()throws IOException {
        GetRequest request =newGetRequest().index("mcy").id("1");
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        log.info("查询索引数据:{}",response);return  response;}/**
     * 查询数据
     * @return
     * @throws IOException
     */@GetMapping("/query")@ApiOperation(value ="查询数据", notes ="查询数据")public JSONArray getData()throws IOException {
        List<Mcy> result =newArrayList<Mcy>();
        result = queryDataService.queryAll();
        JSONArray json =newJSONArray();for(Mcy m : result){
            JSONObject jo =newJSONObject();
            jo.put("id", m.getId());
            jo.put("name", m.getName());
            jo.put("creator",m.getCreator());
            jo.put("desc",m.getDesc());
            jo.put("price",m.getPrice());
            jo.put("tags",m.getTags());
            json.add(jo);}
        log.info("查询mcyFindAll数据为:{}",result);return json;}/**
     * 删除索引
     * @return
     * @throws IOException
     */@GetMapping("/deleteIndex")@ApiOperation(value ="删除索引", notes ="删除索引")public String deleteIndex(@RequestBody String indexName)throws IOException {//String indexName="user";
        AcknowledgedResponse acknowledgedResponse = restHighLevelClientService.deleteIndex(indexName);
        log.info("删除 {} 成功",indexName);return"DeleteIndex "+indexName+" success";}/**
     * 插入数据
     * @return
     * @throws IOException
     */@RequestMapping("/saveDate")@ApiOperation(value ="插入数据", notes ="插入数据")publicvoidsaveDate(@RequestBody User user){
        log.info("user: {}",user);
        userService.save(user);
        log.info("插入 {} 成功",user.getName());}/**
     * 通过name字段删除数据
     * @return
     * @throws IOException
     */@RequestMapping("/deleteUser")@ApiOperation(value ="删除数据", notes ="删除数据")public String deleteUserByName(@RequestBody User user)throws IOException {
        User delUser =getUserByName(user);
        userService.deleteUserById(delUser);return"delete:"+user.getName()+"success!";}/**
     * 从第一条数据开始查询,每页显示2条
     * @return
     * @throws IOException
     */publicvoidDocQueryfy()throws IOException {
        SearchRequest request =newSearchRequest("user");
        SearchSourceBuilder builder =newSearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        builder.from(0);
        builder.size(2);
        request.source(builder);
        SearchResponse response = restHighLevelClient.search(request,RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();//        System.out.println(hits.getTotalHits());//        System.out.println(response.getTook());//        for (SearchHit hit : hits) {//            System.out.println(hit.getSourceAsString());//        }
        restHighLevelClient.close();}//私有方法,根据user的name字段值查询user所有数据(目前主要查询user的Id)private User getUserByName(User user)throws IOException{
        User resultUser =newUser();
        SearchRequest request =newSearchRequest("user");//由于目前trem还不支持中文,因此需要在查询的字段字段值后加上.keyword,或者下载安装ik分词器插件
        request.source(newSearchSourceBuilder().query(QueryBuilders.termQuery("name.keyword",user.getName())));
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits hit = response.getHits();
        log.info("hit:{}",hit);
        String id = hit.getHits()[0].getId();
        log.info("id:{}",id);
        resultUser.setId(id);
        resultUser.setName(user.getName());return resultUser;}/**
     * 通过name字段修改数据
     * @return
     * @throws IOException
     */@RequestMapping("/updateUser")@ApiOperation(value ="修改数据", notes ="修改数据")public String updateUserByName(@RequestBody User user)throws IOException {
        User updUser =getUserByName(user);
        updUser.setName(user.getNewName());
        userService.save(updUser);return"update:"+user.getName()+"success!";}}

service层

publicinterfaceQueryDataService{

    List<Mcy>queryAll();}//以及其实现@Repository@ServicepublicclassQueryDataServiceImpimplementsQueryDataService{@Autowiredprivate QueryDataRepository queryDataRepository;@Overridepublic List<Mcy>queryAll(){

        Iterable<Mcy> result = queryDataRepository.findAll();
        List<Mcy> list = Lists.newArrayList(result);return list;}}
publicinterfaceUserService{voidsave(User user);voiddeleteUserById(User delUser);}//以及其实现@Repository@ServicepublicclassUserServiceImplimplementsUserService{@Autowiredprivate UserRepository userRepository;@Overridepublicvoidsave(User user){
        userRepository.save(user);}@OverridepublicvoiddeleteUserById(User delUser){
        userRepository.delete(delUser);}}

repository层

@RepositorypublicinterfaceQueryDataRepositoryextendsElasticsearchRepository<Mcy,String>{}//publicinterfaceUserRepositoryextendsElasticsearchRepository<User,String>{}

domain层

@Data@Document(indexName ="user")publicclassUserimplementsSerializable{@Idprivate String Id;private String name;private String newName;}
@Data@Document(indexName ="mcy")publicclassMcyimplementsSerializable{@Idprivate String id;private String name;private String creator;private String desc;privatelong price;private List<String> tags;}
@DatapublicclassIndeximplementsSerializable{private String indexName;}
以上便是整个增删改查操作的所有代码了,如果您看到了这里说明代码还是有点用处的,既然如此就顺手来一个点赞、
关注、收藏、评论呗!感谢支持!!!

本文转载自: https://blog.csdn.net/qq_45039852/article/details/123556096
版权归原作者 低调小马(mcy) 所有, 如有侵权,请联系我们删除。

“springBoot整合ElasticSearch【代码直接复制可用】(超级详细)”的评论:

还没有评论