Elasticsearch學習(1) Spring boot整合Elasticsearch


本文的Spring Boot版本為1.5.9,Elasticsearch版本為2.4.4,話不多說,直接上代碼。

一、啟動Elasticsearch

  在官網上下載Elasticsearch后,打開bin目錄下的elasticsearch.bat,出現下面的圖,就證明成功啟動了。

 

二、新建項目,添加依賴

  在創建spring boot項目中,可以在nosql中選擇添加Elasticsearch的依賴,完整的依賴如下:

<?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>cmo.jf.cloud</groupId>
    <artifactId>resourceCente</artifactId>
    <version>1.0.0</version>
    <packaging>war</packaging>

    <name>Elasticsearch</name>
    <description>搜索引擎</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.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-data-elasticsearch</artifactId>
        </dependency>

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

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

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


</project>
View Code

  需要注意的是:

  1.spring boot2.X版本必須使用Elasticsearch 5.X版本

  2.Elasticsearch 2.X的版本必須使用spring boot1.5版本

  3.目前spring-boot-starter-data-elasticsearch還不支持Elasticsearch 6.X版本

  如果出現版本不兼容,這會出現下面的錯誤:

NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{729dgKKVSF-ti27v2_w68g}{127.0.0.1}{127.0.0.7:9300}]]

三、Elasticsearch的配置文件

  和操作數據庫一樣,我們需要配置好配置文件,才能訪問Elasticsearch,配置文件如下:

##端口號
server.port=8888
##es地址
spring.data.elasticsearch.cluster-nodes =127.0.0.1:9300

四、Elasticsearch的實體類

  在Elasticsearch中,我們需要創建一個實體類作為索引,簡單的理解就是在Elasticsearch中創建數據庫和表。

   利用@Document注解可以創建數據庫和表。其中Document中的參數意義為:

   indexName:索引名稱 可以理解為數據庫名 必須為小寫不然會報org.elasticsearch.indices.InvalidIndexNameException異常

        type:類型 可以理解為表名

    代碼如下:  

import java.io.Serializable;

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

//indexName索引名稱 可以理解為數據庫名 必須為小寫 不然會報org.elasticsearch.indices.InvalidIndexNameException異常
//type類型 可以理解為表名
@Document(indexName = "class",type = "user")
public class User implements Serializable {
        //定義成員屬性
          private Integer id;
          private String name;
        private  Integer age;
        private String sex;
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public String getSex() {
            return sex;
        }
        public void setSex(String sex) {
            this.sex = sex;
        }
        public User(Integer id, String name, Integer age, String sex) {
            super();
            this.id = id;
            this.name = name;
            this.age = age;
            this.sex = sex;
        }
        public User() {
            super();
        }
    
}
View Code

五、創建一個數據訪問層

  同樣,和其他的數據庫訪問操作一樣,我們需要創建一個dao層來操作Elasticsearch,這個dao層類似於mongodb的操作,只需要繼承ElasticsearchRepository接口就能實現。

import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import cmo.jf.cloud.bean.User;

@Configuration
public interface  UserMapper extends  ElasticsearchRepository<User,Long>{

}
View Code

六、創建controller層測試

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import cmo.jf.cloud.bean.User;
import cmo.jf.cloud.dao.UserMapper;

@RestController
public class UserController {
    @Autowired
    UserMapper userMapper;
    
     // 訪問接口地址:localhost:8888/save
    //存儲數據
    @GetMapping("save")
    public String save(){
        User user = new User(1,"張三",15,"男");
        userMapper.save(user);
        return "success";
    }
    
     //訪問接口地址:localhost:8888/delete?id=1
    //根據ID刪除數據
    @GetMapping("delete")
    public String delete(long id){
        userMapper.delete(id);
        return "success";
    }
    
    //訪問接口地址:localhost:8888/getOne?id=1
    //根據ID查詢數據
    @GetMapping("getOne")
    public User getOne(long id){
        User user = userMapper.findOne(id);
        return user;
    }
}
View Code

在添加幾條數據后我們訪問head插件---ES管理界面可以看到我們添加的數據庫在頁面上

在數據瀏覽界面中可以看到我們添加的數據

在基本查詢中可以根據表名和條件,查詢我們剛才插入的數據

七、項目中出現的錯誤

   直接上錯誤代碼:

Description:

Cannot determine embedded database driver class for database type NONE

Action:

If you want an embedded database please put a supported one on the classpath. 
If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

          這個錯誤是由於打開了spring boot的自動配置數據,但是沒有配置數據源,所以報錯,解決的方案是直接關閉數據源自動配置,

   只需要在啟動類上加入:@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})即可

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class ElasticsearchApplication {

    public static void main(String[] args) {
        SpringApplication.run(ElasticsearchApplication.class, args);
    }
}

八、小結 

  這就是spring boot1.5整合ElasticSearch 2.X的操作,本文作為初級學習起來還是有幫助,但是ElasticSearch 中的一些高級操作如:同步數據庫,分詞器,高亮等都將在后面的文章中進行書寫。ElasticSearch 6.X、ElasticSearch 5.X的API方式也和ElasticSearch 2.X不同,我也會放在后面進行講解。

 

 

 


免責聲明!

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



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