Springboot整合ElasticSearch進行簡單的測試及用Kibana進行查看

一、前言

搜索引擎還是在電商項目、百度、還有技術博客中廣泛應用,使用最多的還是ElasticSearch,Solr在大數據量下檢索性能不如ElasticSearch。今天和大家一起搭建一下,小編是看完雷神的視頻,自己來整理一遍,增加一下自己的記憶。所有版本就以ElasticSearch7.4.2來進行測試,如果ElasticSearch還沒有安裝的同學可以看一下我的這篇文章,搭建一下哦!!

使用Docker安裝ElasticSearch和可視化界面Kibana

二、創建SpringBoot項目

1. 使用默認構建

在這裡插入圖片描述
2. 配置項目基本信息

在這裡插入圖片描述
3. 引入基本依賴

在這裡插入圖片描述
4. 指定保存位置

在這裡插入圖片描述

三、配置ElasticSearch

1. 打開官方文檔

ElasticSearch官網文檔

2. 根據官方文檔進行配置
在這裡插入圖片描述
3. 新建配置類

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {

    @Bean
    public RestHighLevelClient elasticSearchClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        //我們不是集群,所有隻配置一個,地址填你ES的運行在的主機地址
                        new HttpHost("192.168.17.130", 9200, "http")));

        return client;
    }
}

4. 根據官網進行自己擴展

在這裡插入圖片描述

四、新建索引測試

1. 官方文檔例子很多,我們挑選一個最簡單的進行測試
在這裡插入圖片描述
在這裡插入圖片描述

2. 測試類書寫

import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.Date;

@SpringBootTest
class DemoApplicationTests {

    //引入ESclient
    @Autowired
    private RestHighLevelClient client;

    @Test
    void contextLoads() throws IOException {
        //構建
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        {
            builder.field("user", "kimchy");
            builder.timeField("postDate", new Date());
            builder.field("message", "trying out Elasticsearch");
        }
        builder.endObject();
        IndexRequest indexRequest = new IndexRequest("posts")//索引名字
                .id("1")//數據存儲的id,不行默認隨機生成
                .source(builder);//存放數據

        //執行操作
        IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);

        System.out.println(indexRequest);
    }

}

3. 控制台打印正常
在這裡插入圖片描述

五、使用kibana查看

登錄kibana並查看(//192.168.17.130:5601/)

在這裡插入圖片描述

六、總結

這樣我們就完整了Springboot整合ElasticSearch進行簡單的測試及用Kibana進行查看,內容不多,一切以官網為準,我們安裝官網是不會有問題的。除非有版本問題,目前小編的ElasticSearch是7.4.2,但是SpringBoot是最新的2.6.3,也沒有出現版本衝突的問題!!


推廣自己網站時間到了!!!

點擊訪問!歡迎訪問,裏面也是有很多好的文章哦!