SpringBoot 整合 elasticsearch 實例

1、下載 並啓動 elasticsearch

下載地址:https://www.elastic.co/downloads/past-releasesphp

選擇一個版本,下載html

博主這裏測試使用的是 2.4.4java

下載方式能夠選擇 ZIP 包node

 

啓動的話,windows 和 mac 有些細微區別mysql

windows :進入文件目錄下的 bin,而後點擊 elasticsearch.bat 便可git

mac:在終端執行命令 bin/elasticsearchgithub

 

 

2、配置 Maven

<!-- Spring Boot Elasticsearch 依賴 -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>


<properties>
   <elasticsearch.version>2.4.4</elasticsearch.version>
</properties>

 

添加 spring-boot-starter-data-elasticsearch 依賴,並設置 elasticsearch 版本爲 2.4.4web

 

ES 和 SpirngBoot 版本參考:spring

https://github.com/spring-projects/spring-data-elasticsearch/wiki/Spring-Data-Elasticsearch---Spring-Boot---version-matrixsql

 

3、修改 application.properties

#Project
server.port=8080
debug=true
server.context-path=/chuyun
# DataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/chuyun?characterEncodeing=utf-8&useSSL=false
# JPA
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
#Thymeleaf
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
spring.thymeleaf.cache-period=0
spring.template.cache=false
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:templates/
spring.thymeleaf.suffix=.html
#Elasticsearch
spring.data.elasticsearch.cluster-nodes=localhost:9300
spring.data.elasticsearch.properties.transport.tcp.connect_timeout=120s

主要是添加最後面兩條

 

4、建立 ES Bean 和 Repository

Article.java

package com.liuyanzhao.chuyun.domain.es;
import org.springframework.data.elasticsearch.annotations.Document;
import javax.persistence.Id;
import java.util.Date;
/**
 * @author 言曌
 * @date 2018/1/22 下午4:45
 */
@Document(indexName="chuyun",type="article",indexStoreType="fs",shards=5,replicas=1,refreshInterval="-1")
public class Article {
    //文章ID,這裏必須爲 id
    @Id
    private Long id;
    //標題
    private String title;
    //內容
    private String content;
    //瀏覽量
    private Integer viewCount;
    //發佈時間
    private Date createTime;
    //更新時間
    private Date updateTime;
    public Article() {
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public Integer getViewCount() {
        return viewCount;
    }
    public void setViewCount(Integer viewCount) {
        this.viewCount = viewCount;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", viewCount=" + viewCount +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                '}';
    }
}

 

ArticleRepository.java

package com.liuyanzhao.chuyun.repository.es;
import com.liuyanzhao.chuyun.domain.es.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
 * @author 言曌
 * @date 2018/1/22 下午5:05
 */
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
    Page<Article> findDistinctByTitleContainingOrContentContaining(String title, String content, Pageable pageable);
}

 

5、建立測試類

ArticleRepositoryTest.java

package com.liuyanzhao.chuyun.repository.es;
import com.liuyanzhao.chuyun.domain.es.Article;
import com.liuyanzhao.chuyun.entity.User;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Date;
/**
 * @author 言曌
 * @date 2018/1/21 下午5:03
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ArticleRepositoryTest {
    @Autowired
    private ArticleRepository articleRepository;
    @Before
    public void initRepositoryData() {
        //清除全部數據
        articleRepository.deleteAll();
        Article article = new Article();
        article.setId((long) 1);
        article.setTitle("《蝶戀花》");
        article.setContent("檻菊愁煙蘭泣露,羅幕輕寒,燕子雙飛去。明月不諳離恨苦,斜光到曉穿朱戶。昨夜西風凋碧樹,獨上高樓,望盡天涯路。欲寄彩箋兼尺素,山長水闊知何處?");
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setViewCount(678);
        articleRepository.save(article);
        Article article2 = new Article();
        article2.setId((long) 2);
        article2.setTitle("《蝶戀花》");
        article2.setContent("佇倚危樓風細細,望極春愁,黯黯生天際。草色煙光殘照裏,無言誰會憑闌意。擬把疏狂圖一醉,對酒當歌,強樂還無味。衣帶漸寬終不悔,爲伊消得人憔悴。");
        article2.setCreateTime(new Date());
        article2.setUpdateTime(new Date());
        article.setViewCount(367);
        articleRepository.save(article2);
        Article article3 = new Article();
        article3.setId((long) 3);
        article3.setTitle("《青玉案·元夕》");
        article3.setContent("東風夜放花千樹,更吹落,星如雨。寶馬雕車香滿路。鳳簫聲動,玉壺光轉,一晚上魚龍舞。蛾兒雪柳黃金縷,笑語盈盈暗香去。衆裏尋他千百度,驀然回首,那人卻在,燈火闌珊處。");
        article3.setCreateTime(new Date());
        article3.setUpdateTime(new Date());
        article3.setViewCount(786);
        articleRepository.save(article3);
    }
    @Test
    public void findDistinctByTitleContainingOrContentContainingTest() throws Exception {
        Pageable pageable = new PageRequest(0,20);
        String title = "我愛羅琪";
        String content = "花千樹";
        Page<Article> page = articleRepository.findDistinctByTitleContainingOrContentContaining(title, content, pageable);
        System.out.println(page);
        System.out.println("---start---");
        for(Article article : page.getContent()) {
            System.out.println(article.toString());
        }
        System.out.println("---end---");
    }
}

 

運行 @Test 註解的方法

根據 title 和 content 內容查到一條數據

SpringBoot 整合 elasticsearch 實例

 

修改 title 和 content

String title = "蝶戀";
String content = "東風";

查到三條數據

SpringBoot 整合 elasticsearch 實例

 

6、訪問 http://localhost:9200/_plugin/head/

由於上一篇文章中,咱們講了裝一個 head 插件,如今咱們就能看到裏面的數據了(多餘的數據是以前測試的)

SpringBoot 整合 elasticsearch 實例

 

7、新建 Controller 類

ArticleController.java

package com.liuyanzhao.chuyun.controller;
import com.liuyanzhao.chuyun.domain.es.Article;
import com.liuyanzhao.chuyun.repository.es.ArticleRepository;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * @author 言曌
 * @date 2018/1/22 下午9:07
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleRepository ArticleRepository;
    @RequestMapping("")
    public List<Article> list(@RequestParam(value = "title", required = false) String title,
                                @RequestParam(value = "content", required = false) String content,
                                @RequestParam(value = "pageIndex", defaultValue = "0") int pageIndex,
                                @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        Pageable pageable = new PageRequest(pageIndex, pageSize);
        Page<Article> page = ArticleRepository.findDistinctByTitleContainingOrContentContaining(title, content, pageable);
        return page.getContent();
    }
}

由於以前在 測試類 裏已經給 elasticsearch 添加了數據

全部如今能夠在瀏覽器上訪問:

http://localhost:8080/chuyun/article?title=浪淘沙&content=伊人

SpringBoot 整合 elasticsearch 實例

相關文章
相關標籤/搜索