springboot集成elasticsearch

一、elasticsearch簡介:

  ElasticSearch(ES) 是一個基於 Lucene 的搜索服務器,是一個分佈式、可擴展、實時的搜索與數據分析引擎,它能從項目一開始就賦予你的數據以搜索、分析和探索的能力,基於 RESTful web 接口。ElasticSearch 是用 Java 開發 ,當前流行的企業級搜索引擎。設計用於雲計算中,能夠達到實時搜索,穩定,可靠,快速,安裝使用方便。

二、elasticsearch應用場景
  海量數據分析引擎
  站內搜索引擎
  數據倉庫

三、版本

  elasticsearch-6.6.2-windows-64  //elasticsearch:  Windows版的服務器
  kibana-6.6.2-windows-64            //類似於elasticsearch的圖形化工具,可以方便的操作elasticsearch中的索引內容
  springboot-1.5.9    
  org.elasticsearch 5.6.0               //pom.xml引入的elasticsearch 依賴包
  org.elasticsearch.client 5.6.0     //若elasticsearch-windows-6.6.2,注意:這裏引用的依賴包最低版本是5.6.0,否則報錯。
  jdk1.8
  基於上一節的知識點(springboot集成swagger2開發的)
四、 springboot集成elasticsearch
  1.本機下載安裝elasticsearch
    官網下載地址:https://www.elastic.co/downloads/elasticsearch
    或  elasticsearch-6.6.2-windows-64 下載地址:
    鏈接:https://pan.baidu.com/s/1hjG4gTt3Mtu4FFoqoFN8Sg    提取碼:hmbr

    下載後解壓,即可使用
         進入到bin下,雙擊elasticsearch.bat(打開ES),
    測試是否安裝成功,訪問:http://localhost:9200
 
     

  2.本機下載安裝Kibana

   類似於elasticsearch的圖形化工具,可以方便的操作查看elasticsearch中的索引內容
   鏈接:https://pan.baidu.com/s/17u_70hLeRVKDa15seUYjvA   提取碼:91hu
五、修改pom.xml文件
<!-- elasticsearch -->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>5.6.0</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>transport</artifactId>
    <version>5.6.0</version>       <!-- 修改完這裏需要重啓springboot,否則elasticsearch6.2.2Windows不識別新版本 -->
</dependency>
<!-- elasticsearch 5.x中需要log4j的一些依賴 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version>
        </dependency>

六、application.properties

  可以把下面配置類中的參數ip、端口號和cluster.name 配置在application.properties裏

七、創建配置類
package cn.xdf.springboot.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
@Configuration
public class ESConfig {
    @Bean
    public TransportClient getTransportClient() throws UnknownHostException {
        // ES默認TCP端口是9300
        InetSocketTransportAddress node = new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300);
        TransportClient client = null;
        try {
       //注意:需要修改安裝的elasticsearch的配置文件/config/elasticsearch.yml的第17行的集羣名對應自己這裏“my-es”和第55行的ip對應自己這裏的“127.0.0.1” ,並打開這兩行註釋。 Settings settings
= Settings.builder().put("cluster.name", "my-es").build();//集羣名字:es需要對應elasticsearch.yml中cluster.name client = new PreBuiltTransportClient(settings); // 多個client多次new InetSocketTransportAddress,多次添加就行 client.addTransportAddress(node); } catch (Exception e) { e.printStackTrace(); System.out.println("elasticsearch TransportClient create error!!"); } return client; } }

八、測試類

package cn.xdf.springboot.controller;
import java.io.IOException;
import javax.validation.Valid;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.xdf.springboot.pojo.Category;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
 
@RestController
@RequestMapping("es")
@Api("ElasticsearchDemoController相關的api")
public class ElasticsearchDemoController {
    //操作 Elasticsearch 只需要注入 TransportClient 就可以了
    @Autowired
    private TransportClient client;
 
    private static final Logger logger= LoggerFactory.getLogger(ElasticsearchDemoController.class);
 
    //1.商品添加
    //@PutMapping("add") 添加方法--restful風格
    @PutMapping("add")
    @ApiOperation(value="商品索引新增")
    //@RequestParam 接收頁面中的請求的參數
    public String addCategory(@RequestParam String name) throws IOException{
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .field("name", name)
                .endObject();
        IndexResponse response = client.prepareIndex("test_db", "product")//修改自己對應的“索引庫”和“表”:test_db/product
                .setSource(builder)
                .get();                           
        System.out.println(response.getResult() + ", id=" + response.getId()); //輸出創建結果,成功返回 CREATED
        return "添加索引成功!";
    }
    //2.商品修改
    //@PostMapping("update")  修改方法--restful風格
    @PostMapping("update")  
    @ApiOperation(value = "商品索引修改", notes = "修改數據庫中某個的商品信息")
    //@RequestBody 接收頁面中的請求的參數對象(適用於post請求)
    //當入參爲實體對象時,需要在方法上加@Valid或@Validated或者在參數前加@Valid或@Validated,或者在類上加@Validated
    public String updateCategory(@Valid @RequestBody  Category category) throws Exception {
        UpdateRequest request    = new UpdateRequest("test_db", "product", category.getId()+"");//int 轉String
        XContentBuilder builder = XContentFactory.jsonBuilder()
                .startObject()
                .field("name", category.getName())
                .endObject();
        request.doc(builder);
        UpdateResponse response = client.update(request).get();
        System.out.println(response.getResult()); //輸出修改結果,成功返回 UPDATED
        return "修改索引成功!";
    }
    //3.商品刪除
    //@DeleteMapping("/delete/{id}") 刪除方法--restful風格
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根據id刪除商品索引", notes = "商品索引刪除")
    @ApiImplicitParam(name = "id", value = "商品ID", paramType = "path", required = true, dataType = "Integer")
    public String deleteCategory(@PathVariable int id)throws Exception{  //@PathVariable 獲取/delete/{id}中id
        DeleteResponse response = client.prepareDelete("test_db", "product",  id+"").get();
        System.out.println(response.getResult()); //輸出刪除結果,成功返回 DELETED
        return "刪除索引成功!";
    }
    //4.根據ID查詢商品信息
    //@GetMapping("")  查詢方法--restful風格
    @GetMapping("/get/{id}") 
    @ApiOperation(value = "根據id查詢商品", notes = "查詢數據庫中某個的商品信息")
    @ApiImplicitParam(name = "id", value = "商品ID", paramType = "path", required = true, dataType = "Integer")
    public String getCategory(@PathVariable int id) { //@PathVariable 獲取/get/{id}中id
        System.out.println("根據id查詢:"+id);
        GetResponse response = client.prepareGet("test_db", "product",  id+"").get();
        System.out.println(response.getSource()); //輸出查詢結果
        return "查詢索引成功!";
    }
    //5.分頁查詢
    //@GetMapping("")  查詢方法--restful風格
    @GetMapping("/page")
    @ApiOperation(value="商品查詢(分頁)")        
    public String pageCategory(@RequestParam(value="start",defaultValue="0")int start,@RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
        SearchResponse response = client.prepareSearch("test_db")
                .setTypes("product")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setFrom(0)
                .setSize(10)
                .get();
        System.out.println(response); //輸出複合查詢結果
        return "查詢索引成功!";
    }
    
}

九、根據Swagger測試增刪改查方法

  測試地址:http://localhost:8080/swagger-ui.html

  

  (註釋,我這邊方便測試 ,把實體類的id的 int類型改爲string類型了,默認新增的id爲一個字符串,如:PQYguWoBqFQiH90p4Nj1,方便查詢新增的數據)

  查詢方法:

  後臺打印:

 

十、啓動Kibana

  D:\kibana-6.2.2-windows-x86_64\bin\kibana.bat

       然後通過這個圖形化工具查看剛纔測試的索引數據信息
       查詢test_db所有的命令
GET /test_db/_search
{
"query": { "match_all": {} }
}

 


 注:springboot整合ElasticSearch分爲兩種:

    一種直接使用官方的集成工具(引用spring-boot-starter-data-elasticsearch依賴),然後通過hibernate JPA規範,dao層繼承ElasticsearchRepository,controller依賴注入這個dao接口,就相當於對索引庫操作了。
    另一種是自己寫Client連接。如本知識點
 
 
 
 
 
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章