【Elastic Search 学习】

本文详细介绍了如何在Java环境中搭建Elasticsearch8.11.3集群,包括版本选择、配置文件设置、Logstash配置、Kibana配置以及与SpringBoot项目的集成。还涉及了安全设置、单机测试和Nacos作为配置中心的使用。
摘要由CSDN通过智能技术生成

Elastic search 8.11.3+springboot版本学习

环境搭建

  • 版本(各版本可自行搭配选择)
    • Java版本 jdk17
    • es版本 8.11.3
    • logstash 8.11.3
    • kibana 8.11.3
    • spring cloud 2022.0.3、springboot 3.0.2、cloud alibaba 2022.0.0.0-RC2

环境搭建

  1. elastic、logstash、kibana下载 link
  2. 配置文件修改
# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
cluster.name: platform-es
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
path.data: 更换为你自己的数据文件路径
#
# Path to log files:
#
path.logs: 更换为你自己的日志文件路径
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# By default Elasticsearch is only accessible on localhost. Set a different
# address here to expose this node on the network:
#
network.host: 0.0.0.0
#
# By default Elasticsearch listens for HTTP traffic on the first free port it
# finds starting at 9200. Set a specific HTTP port here:
#
http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when this node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.seed_hosts: ["host1", "host2"]
#
# Bootstrap the cluster using an initial set of master-eligible nodes:
#
#cluster.initial_master_nodes: ["node-1", "node-2"]
#
# For more information, consult the discovery and cluster formation module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Allow wildcard deletion of indices:
#
#action.destructive_requires_name: false

#----------------------- BEGIN SECURITY AUTO CONFIGURATION -----------------------
#
# The following settings, TLS certificates, and keys have been automatically      
# generated to configure Elasticsearch security features on 20-12-2023 09:34:29
#
# --------------------------------------------------------------------------------

# Enable security features
xpack.security.enabled: false

xpack.security.enrollment.enabled: true

# Enable encryption for HTTP API client connections, such as Kibana, Logstash, and Agents
xpack.security.http.ssl:
  enabled: false
  keystore.path: certs/http.p12

# Enable encryption and mutual authentication between cluster nodes
xpack.security.transport.ssl:
  enabled: true
  verification_mode: certificate
  keystore.path: certs/transport.p12
  truststore.path: certs/transport.p12
# Create a new cluster with the current node only
# Additional nodes can still join the cluster later
cluster.initial_master_nodes: ["node-1"]

#----------------------- END SECURITY AUTO CONFIGURATION -------------------------

由于是单机测试使用,所以关闭了身份验证功能
在bin目录直接双击 elasticsearch.bat 文件即可启动

  1. logstash配置

在这里插入图片描述
将logstash-sample.conf文件复制一份改名为logstash.conf
添加如下配置

input {
  stdin { }
}

filter {
  grok {
    match => { "message" => "%{COMBINEDAPACHELOG}" }
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "apache-%{+YYYY.MM.dd}"
  }
}

logstash.ym文件中指定es用户名和密码,es用户名和密码会在第一次启动时生成默认用户名为 elastic

 api.auth.basic.username: "elastic"
 api.auth.basic.password: "****"

启动logstash 需要在bin目录执行命令启动,指定logstash配置文件

logstash -f config/logstash.conf
  1. kinbana配置

防止乱码
i18n.locale: "zh-CN"

环境搭建启动成功之后开始搭建项目
以下是自己搭建的的学习项目结构 已上传 Github
Github项目地址,欢迎学习交流
在这里插入图片描述

  1. bootstrap.yml文件配置
server:
  port: 8914
spring:
  application:
    name: platform-es
  profiles:
    active: dev
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yml
        namespace: ****************************
        group: DEFAULT_GROUP
        data-id: ${spring.application.name}.${spring.cloud.nacos.config.file-extension}
        refresh: true
      discovery:
        server-addr: 127.0.0.1:8848
        namespace: ****************************
        group: DEFAULT_GROUP
  elasticsearch:
    cluster-name: ${spring.application.name}
    cluster-nodes: 127.0.0.1:9200
    connection-timeout: 5000
    uris: 127.0.0.1:9200
    port: 9200
    host: 127.0.0.1
    username: elastic
    password: ******************

自己使用的nacos做配置中心及注册中心,多余配置不在一一贴出
6. pom.xml引入

<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>
    <parent>
        <groupId>com.learn.platform</groupId>
        <artifactId>platform-service</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>platform-es</artifactId>
    <packaging>jar</packaging>

    <name>platform-es</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

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

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



        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.11.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.dubbo</groupId>
            <artifactId>dubbo-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

  1. 编写config配之类
package com.learn.platform.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName ElasticsearchConfig
 * @Description es 配之类
 * @Author xue
 * @Date 2023/12/21 10:58
 */
@Configuration
public class ElasticsearchConfig {


    @Value("${spring.elasticsearch.uris}")
    private String[] uris;
    @Value("${spring.elasticsearch.connection-timeout}")
    private Integer connectionTimeout;
    @Value("${spring.elasticsearch.port}")
    private Integer port;
    @Value("${spring.elasticsearch.host}")
    private String host;
    @Value("${spring.elasticsearch.username}")
    private String userName;
    @Value("${spring.elasticsearch.password}")
    private String password;


    @Bean
    public ElasticsearchClient elasticsearchClient(){
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

        RestClient client = RestClient.builder(new HttpHost(host, port))
                .setHttpClientConfigCallback(httpAsyncClientBuilder ->
                        httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
                .build();
        ElasticsearchTransport transport = new RestClientTransport(client, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}

  1. service业务类
package com.learn.platform.service.Impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.search.Highlight;
import co.elastic.clients.elasticsearch.core.search.HighlightField;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.ExistsRequest;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.alibaba.fastjson2.JSONObject;
import com.learn.platform.entity.IndexReq;
import com.learn.platform.entity.es.SearchReq;
import com.learn.platform.entity.es.dto.EsUser;
import com.learn.platform.service.es.PlatformEsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName PlatformEsServiceImpl
 * @Description es业务类
 * @Author xue
 * @Date 2023/12/21 10:12
 */
@Slf4j
@DubboService
@Service
public class PlatformEsServiceImpl implements PlatformEsService {


    /*  @Autowired
      RestClient restClient;*/
    @Autowired
    ElasticsearchClient elasticsearchClient;

    /**
     * 创建索引
     *
     * @param req 索引名称
     * @return Response 响应结果
     * @throws Exception 异常
     */
    public CreateIndexResponse createIndex(IndexReq req) throws Exception {
        boolean value = elasticsearchClient.indices().exists(ExistsRequest.of(a -> a.index(req.getIndexName()))).value();
        if (value) {
            throw new IllegalArgumentException("当前索引已存在");
        }
        CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(CreateIndexRequest.of(a -> a.index(req.getIndexName())
                .mappings(m -> m.properties(req.getMappings()))
        ));

        return createIndexResponse;
    }

    /**
     * 批量添加数据
     * @param indexName
     * @param list
     */
    public void addDataForIndex(String indexName,List list) {
        List<BulkOperation> bulkOperations = new ArrayList<>();
        try {
            for (Object o : list) {
                bulkOperations.add(new BulkOperation.Builder().create(d->d.document(o).id(UUID.randomUUID().toString().toUpperCase())).build());
            }
        }catch (Exception e) {
           e.printStackTrace();
        }
    }

    /**
     * 获取索引内容
     *
     * @param indexName 索引名称
     * @throws Exception
     */
    public GetIndexResponse getindex(String indexName) throws Exception {
        GetIndexResponse response = elasticsearchClient.indices().get(req -> req.index(indexName));
        log.info("获取索引结果 response={}", JSONObject.toJSONString(response));
        log.info("结果集{}", response.result());
        return response;
    }

    /**
     * 查询
     *
     * @param req 请求参数
     * @return
     * @throws IOException
     */
    public Object search(SearchReq req) throws IOException {
        MatchQuery matchQuery = new MatchQuery.Builder()
                .field(req.getField())
                .query(req.getQuery())
                .build();
        Query query1 = new Query.Builder().match(matchQuery).build();
        SearchRequest searchRequest = new SearchRequest.Builder()
                .index(req.getIndexName())
                .query(query1)
                .highlight(Highlight.of(a -> a.fields(req.getField(), HighlightField.of(b -> b.matchedFields(Collections.singletonList(req.getQuery()))))))
                .build();
        SearchResponse<EsUser> response = elasticsearchClient.search(searchRequest, EsUser.class);
        log.info("查询结果 result={}", response.hits());
        for (Hit<EsUser> hit : response.hits().hits()) {
            EsUser source = hit.source();
            assert source != null;
            Map<String, List<String>> highlight = hit.highlight();
            if (ObjectUtils.isNotEmpty(highlight)) {
                source.setHighLight(highlight.get(req.getField()).get(0));
            }
        }
        return response.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
    }

    public boolean existsIndex(String indexName) throws IOException {
        BooleanResponse exists = elasticsearchClient.indices().exists(a -> a.index(indexName));
        return exists.value();

    }
}

  1. controller层
package com.learn.platform.service.Impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.search.Highlight;
import co.elastic.clients.elasticsearch.core.search.HighlightField;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexRequest;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.ExistsRequest;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.alibaba.fastjson2.JSONObject;
import com.learn.platform.entity.IndexReq;
import com.learn.platform.entity.es.SearchReq;
import com.learn.platform.entity.es.dto.EsUser;
import com.learn.platform.service.es.PlatformEsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName PlatformEsServiceImpl
 * @Description es业务类
 * @Author xue
 * @Date 2023/12/21 10:12
 */
@Slf4j
@DubboService
@Service
public class PlatformEsServiceImpl implements PlatformEsService {


    /*  @Autowired
      RestClient restClient;*/
    @Autowired
    ElasticsearchClient elasticsearchClient;

    /**
     * 创建索引
     *
     * @param req 索引名称
     * @return Response 响应结果
     * @throws Exception 异常
     */
    public CreateIndexResponse createIndex(IndexReq req) throws Exception {
        boolean value = elasticsearchClient.indices().exists(ExistsRequest.of(a -> a.index(req.getIndexName()))).value();
        if (value) {
            throw new IllegalArgumentException("当前索引已存在");
        }
        CreateIndexResponse createIndexResponse = elasticsearchClient.indices().create(CreateIndexRequest.of(a -> a.index(req.getIndexName())
                .mappings(m -> m.properties(req.getMappings()))
        ));

        return createIndexResponse;
    }

    /**
     * 批量添加数据
     * @param indexName
     * @param list
     */
    public void addDataForIndex(String indexName,List list) {
        List<BulkOperation> bulkOperations = new ArrayList<>();
        try {
            for (Object o : list) {
                bulkOperations.add(new BulkOperation.Builder().create(d->d.document(o).id(UUID.randomUUID().toString().toUpperCase())).build());
            }
        }catch (Exception e) {
           e.printStackTrace();
        }
    }

    /**
     * 获取索引内容
     *
     * @param indexName 索引名称
     * @throws Exception
     */
    public GetIndexResponse getindex(String indexName) throws Exception {
        GetIndexResponse response = elasticsearchClient.indices().get(req -> req.index(indexName));
        log.info("获取索引结果 response={}", JSONObject.toJSONString(response));
        log.info("结果集{}", response.result());
        return response;
    }

    /**
     * 查询
     *
     * @param req 请求参数
     * @return
     * @throws IOException
     */
    public Object search(SearchReq req) throws IOException {
        MatchQuery matchQuery = new MatchQuery.Builder()
                .field(req.getField())
                .query(req.getQuery())
                .build();
        Query query1 = new Query.Builder().match(matchQuery).build();
        SearchRequest searchRequest = new SearchRequest.Builder()
                .index(req.getIndexName())
                .query(query1)
                .highlight(Highlight.of(a -> a.fields(req.getField(), HighlightField.of(b -> b.matchedFields(Collections.singletonList(req.getQuery()))))))
                .build();
        SearchResponse<EsUser> response = elasticsearchClient.search(searchRequest, EsUser.class);
        log.info("查询结果 result={}", response.hits());
        for (Hit<EsUser> hit : response.hits().hits()) {
            EsUser source = hit.source();
            assert source != null;
            Map<String, List<String>> highlight = hit.highlight();
            if (ObjectUtils.isNotEmpty(highlight)) {
                source.setHighLight(highlight.get(req.getField()).get(0));
            }
        }
        return response.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
    }

    public boolean existsIndex(String indexName) throws IOException {
        BooleanResponse exists = elasticsearchClient.indices().exists(a -> a.index(indexName));
        return exists.value();

    }
}

你好!关于学习Elasticsearch,我可以给你一些指导。Elasticsearch是一个开源的分布式搜索和分析引擎,主要用于快速、实时地存储、搜索和分析大量数据。下面是一些学习Elasticsearch的步骤: 1. 了解基本概念:开始学习Elasticsearch之前,你需要了解一些基本的概念,比如索引(index)、类型(type)、文档(document)、字段(field)等。这将帮助你更好地理解Elasticsearch的工作原理。 2. 安装和配置:根据你的操作系统,你可以从Elasticsearch官方网站下载并安装合适的版本。安装完成后,你需要进行适当的配置,如设置集群名称、分配内存等。 3. 学习REST API:Elasticsearch提供了丰富的REST API,用于与其进行交互。了解如何使用这些API来索引、搜索和删除数据是学习Elasticsearch的重要一步。 4. 索引和搜索数据:学习如何创建索引、添加文档以及执行搜索操作是使用Elasticsearch的关键。掌握查询语法、过滤器、聚合操作等功能可以帮助你更有效地使用Elasticsearch。 5. 数据建模和分析:学习如何设计合适的数据模型和映射,以及如何使用Elasticsearch进行数据分析和可视化是提高你的技能的重要一步。 6. 扩展和优化:学习如何在生产环境中扩展和优化Elasticsearch集群是非常重要的。了解如何分片、复制、调优性能等将帮助你更好地管理和维护你的数据。 7. 学习资源:除了官方文档,还有很多优秀的学习资源可供参考,如书籍、教程和在线课程等。利用这些资源可以更系统地学习和掌握Elasticsearch。 希望这些步骤能对你学习Elasticsearch有所帮助!如果有任何问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值