zl程序教程

您现在的位置是:首页 >  IT要闻

当前栏目

Springboot整合ElasticSearch进行简单的测试及用Kibana进行查看

2023-02-18 16:42:10 时间

一、前言

搜索引擎还是在电商项目、百度、还有技术博客中广泛应用,使用最多的还是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并查看(http://192.168.17.130:5601/)

在这里插入图片描述

六、总结

这样我们就完整了Springboot整合ElasticSearch进行简单的测试及用Kibana进行查看,内容不多,一切以官网为准,我们安装官网是不会有问题的。除非有版本问题,目前小编的ElasticSearch是7.4.2,但是SpringBoot是最新的2.6.3,也没有出现版本冲突的问题!!


推广自己网站时间到了!!!

点击访问!欢迎访问,里面也是有很多好的文章哦!