1. 程式人生 > >springboot簡易整合ElasticSearch

springboot簡易整合ElasticSearch

寫在前面:本文將搭建的ElasticSearch環境採用單機單節點方式,如果讀者想採用叢集方式請移步至https://blog.csdn.net/belonghuang157405/article/details/83301937

Elasticsearch: 權威指南 : https://www.elastic.co/guide/cn/elasticsearch/guide/current/index.html

程式碼示例地址:https://github.com/Blankwhiter/elasticsearch

一、ElasticSearch環境搭建

1.在centos視窗中,執行如下命令:

docker pull elasticsearch:5.6.8

當前ES映象版本資訊:

 {
  "name" : "WlwFyqU",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "78UDZtviQqiWmzmenGpSrQ",
  "version" : {
    "number" : "5.6.8",
    "build_hash" : "cfe3d9f",
    "build_date" : "2018-09-10T20:12:43.732Z",
    "build_snapshot" : false,
    "lucene_version" : "6.6.1"
  },
  "tagline" : "You Know, for Search"
 }

2.建立資料掛在目錄,以及配置ElasticSearch叢集配置檔案,調高JVM執行緒數限制數量

  • 1.建立資料檔案掛載目錄data
    在centos視窗中,執行如下操作:
[[email protected] soft]# pwd
/home/soft/ES
[[email protected] ES]# mkdir data
[[email protected]st ES]# cd ES/config/
  • 2.在centos視窗中,使用vim命令分別建立es.yml檔案
    es.yml
cluster.name: elasticsearch-single
node.name: es-node
network.bind_host: 0.0.0.0
network.publish_host: 192.168.9.219
http.port: 9204
transport.tcp.port: 9304
http.cors.enabled: true
http.cors.allow-origin: "*"
node.master: true 
node.data: true  

注:讀者根據自身配置修改network.publish_host、http.port、transport.tcp.port

  • 3.調高JVM執行緒數限制數量
    在centos視窗中,修改配置sysctl.conf
vim /etc/sysctl.conf

加入如下內容:

vm.max_map_count=262144 

啟用配置:

sysctl -p

注:這一步是為了防止啟動容器時,報出如下錯誤:
bootstrap checks failed max virtual memory areas vm.max_map_count [65530] likely too low, increase to at least [262144]

3.啟動ElasticSearch容器

docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9204:9204 -p 9304:9304 -v /home/soft/ES/config/es.yml:/usr/share/elasticsearch/config/elasticsearch.yml -v /home/soft/ES/data:/usr/share/elasticsearch/data --name ES-single elasticsearch:5.6.8

三、spring boot整合ElasticSearch

整合文件:https://github.com/spring-projects/spring-data-elasticsearch
由於本文中使用的ElasticSearch是5.6.8 故選擇的spring data elasticsearch 版本是3.0.X,請參考附錄1
1.引入環境所需的jar 以及配置
pom.xml

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.elasticsearch</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--版本3.0.11.RELEASE-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

application.yml

spring:
  data:
    elasticsearch:
      cluster-name: elasticsearch-single
      cluster-nodes: 192.168.9.219:9304

2.編寫實體以及repository類
Book.java

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

@Data
@Document(indexName = "kind",type = "book")
public class Book {

    /**
     * 主鍵
     */
    private Integer id;

    /**
     * 作者
     */
    private String author;

    /**
     * 書名
     */
    private String bookName;

    /**
     * 描述
     */
    private String desc;
}

BookRepository.java

import com.elasticsearch.springboot.po.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

@Component
public interface BookRepository extends ElasticsearchRepository<Book,Integer> {
}

3.測試

import com.elasticsearch.springboot.po.Book;
import com.elasticsearch.springboot.repository.BookRepository;
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.test.context.junit4.SpringRunner;

import java.util.Optional;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {


    @Autowired
    BookRepository bookRepository;

    /**
     * 建立索引
     */
    @Test
    public void createIndex(){
        Book book = new Book();
        book.setId(1);
        book.setAuthor("周志明");
        book.setBookName("深入理解Java虛擬機器_JVM高階特性與最佳實踐");
        book.setDesc("Java虛擬機器,最佳實踐。。。。");
        bookRepository.save(book);
    }

    /**
     * 搜尋索引
     */
    @Test
    public void searchIndex(){
        Optional<Book> optionalBook = bookRepository.findById(1);
        System.out.println(optionalBook.get().toString());
    }


    @Test
    public void contextLoads() {
    }

}

這裡就簡單舉了建立以及搜尋索引,其他請讀者自行看文件學習。

四、額外一種:JestClient操作ElasticSearch

jest文件:https://github.com/searchbox-io/Jest/tree/master/jest

1.引入環境所需的jar 以及配置
pom.xml

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.elasticsearch</groupId>
    <artifactId>jest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jest</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

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

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

        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>5.3.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

application.yml

spring:
  elasticsearch:
    jest:
      uris: http://192.168.9.219:9204

2.編寫實體類
Article.java

import io.searchbox.annotations.JestId;
import lombok.Data;

/**
 * 文章實體類
 */
@Data
public class Article {

    /**
     * 主鍵
     */
    @JestId
    private Integer id;
    /**
     * 作者
     */
    private String author;

    /**
     * 標題
     */
    private String title;

    /**
     * 內容
     */
    private String content;

}

3.測試

import com.elasticsearch.jest.po.Article;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
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.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class JestApplicationTests {

    /**
     * 引入
     */
    @Autowired
    JestClient jestClient;


    /**
     * 建立索引
     */
    @Test
    public void createIndex() {
        Article article = new Article();
        article.setId(1);
        article.setAuthor("海子");
        article.setTitle("面朝大海,春暖花開");
        article.setContent("從明天起,做一個幸福的人。。。。。。");

        Index index = new Index.Builder(article).index("article").type("poetry").build();
        try {
            jestClient.execute(index);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 搜尋索引
     * @throws IOException
     */
    @Test
    public void searchIndex() throws IOException {
        StringBuffer query  = new StringBuffer("{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"content\" : \"明天\"\n" +
                "        }\n" +
                "    }\n" +
                "}");
        Search search = new Search.Builder(query.toString()).addIndex("article").addType("poetry").build();
        SearchResult result = jestClient.execute(search);
        System.out.println(result+" : "+result.getJsonString());
    }


    @Test
    public void contextLoads() {
    }

}

更多內容,請移步至文件學習。

附錄:

1.spring data elasticsearch 對應ElasticSearch版本

spring data elasticsearch Elasticsearch Version
3.1.x 6.2.2
3.0.x 5.5.0
2.1.x 2.4.0
2.0.x 2.2.0
1.3.x 1.5.2
2.jest對應ElasticSearch版本
Jest Version Elasticsearch Version
>= 6.0.0 6
>= 5.0.0 5
>= 2.0.0 2
0.1.0 - 1.0.0 1
<= 0.0.6 < 1