Springboot 操作Elasticsearch 方式一 【spring-data-elasticsearch】


  博主的環境是windows+elasticsearch6.7.1+kibana 6.7.1

{
  "name" : "TDo83fR",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "4-RI-qcBR46U9FtwxgEJ8g",
  "version" : {
    "number" : "6.7.1",
    "build_flavor" : "oss",
    "build_type" : "zip",
    "build_hash" : "2f32220",
    "build_date" : "2019-04-02T15:59:27.961366Z",
    "build_snapshot" : false,
    "lucene_version" : "7.7.0",
    "minimum_wire_compatibility_version" : "5.6.0",
    "minimum_index_compatibility_version" : "5.0.0"
  },
  "tagline" : "You Know, for Search"
}
  • 添加ES依賴,不同版本springboot與ES環境依賴版本不同
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>elasticsearch</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/>
    </parent>
    <dependencies>
        <!--引入ES-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
<!--            <version>3.1.21.RELEASE</version>-->
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


        <!-- SLf4j 日志記錄-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
            <version>1.18.12</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.54</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  • 定義Article類
package com.example.elasticsearch.model;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import java.io.Serializable;
import java.util.Date;

//通過這個注解,可以不用寫gettersetter方法,有時不好用
@Data
@Document(indexName = "article",type = "_doc")
public class Article implements Serializable {

    // 必須指定一個id
    @Id
    private String id;

    private String title;

    private String content;

    private Integer userId;

    private Date createTime;


}
  • 創建連接配置類ElasticsearchConfig
package com.example.elasticsearch.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.TransportClientFactoryBean;

@Configuration
public class ElasticsearchConfig {
    @Bean
    TransportClientFactoryBean client() {
        TransportClientFactoryBean bean=new TransportClientFactoryBean();
        bean.setClusterName("elasticsearch");//默認為:elasticsearch
        bean.setClusterNodes("127.0.0.1:9300");//http連接9200,客戶端方式9300
        return bean;
    }
}
  • 創建ArticleRepository接口,實現ElasticsearchRepository接口
package com.example.elasticsearch.service;

import com.example.elasticsearch.model.Article;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ArticleRepository extends ElasticsearchRepository<Article,String> {

}
  • 測試接口ArticleController類
package com.example.elasticsearch.controller;

import com.example.elasticsearch.model.Article;
import com.example.elasticsearch.response.Result;
import com.example.elasticsearch.service.ArticleRepository;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleController {

    private final static Logger logger = LoggerFactory.getLogger(ArticleController.class);

    @Autowired
    private ArticleRepository articleRepository;

//    @Autowired
//    private ElasticsearchRestTemplate elasticsearchRestTemplate; //查詢

//    @Autowired
//    private ElasticsearchOperations elasticsearchOperations;

    //查詢數據
    @GetMapping("{id}")
    public Result findById(@PathVariable String id) {
        Optional<Article> article = articleRepository.findById(id);
        return Result.SUCCESS(article);
    }

    //刪除數據
    @DeleteMapping("{id}")
    public Result delete(@PathVariable String id) {
       // articleRepository.deleteAll();
        articleRepository.deleteById(id);
        return Result.SUCCESS("刪除成功");
    }

    //保存數據
    @PostMapping("save")
    public Result save(@RequestBody Article article) {
        if (article == null || StringUtils.isEmpty(article.getTitle())) {
            return Result.FAIL("標題不能為空");
        } else if (StringUtils.isEmpty(article.getContent())) {
            return Result.FAIL("內容不能為空");
        }
        article.setCreateTime(new Date());
        Article a = articleRepository.save(article);
        if (a.getId() != null)
            return Result.SUCCESS("保存成功");
        else
            return Result.FAIL("保存失敗");
    }

    @GetMapping("list")
    public Result list(@RequestParam(name = "pageLimit", defaultValue = "10") Integer pageLimit, @RequestParam(name = "pageCurrent", defaultValue = "1") Integer pageCurrent) {
        try {
            // 分頁參數
            Pageable pageable = PageRequest.of(pageCurrent-1,pageLimit);
//            QueryStringQueryBuilder builder = new QueryStringQueryBuilder("");
//            SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(builder).build();
//            System.out.println("查詢的語句:" + searchQuery.getQuery().toString());
            Iterable<Article> articles = articleRepository.findAll(pageable);//(searchQuery);
            return Result.SUCCESS(articles);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
        return Result.FAIL();
    }

}
  • 通過postman測試結果如圖:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM