elasticsearch 8.2.3 安装及springboot简单使用

news2024/12/28 18:29:25

一、下载安装

  • 官网下载地址
    https://www.elastic.co/cn/downloads/elasticsearch

     

  • 解压
    elasticsearch-8.2.3-windows-x86_64

     

  • 修改配置
    elasticsearch-8.2.3\config\elasticsearch.yml
# ======================== 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: my-application
#
# ------------------------------------ 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/data
#
# Path to log files:
#
#path.logs: /path/to/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: 192.168.0.1
#
# 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.
#
# --------------------------------- Readiness ----------------------------------
#
# Enable an unauthenticated TCP readiness endpoint on localhost
#
#readiness.port: 9399
#
# ---------------------------------- 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 21-06-2022 06:14:38
#
# --------------------------------------------------------------------------------

# Enable security features
#xpack.security.enabled: true

#xpack.security.enrollment.enabled: true

# Enable encryption for HTTP API client connections, such as Kibana, Logstash, and Agents
#xpack.security.http.ssl:
#  enabled: true
#  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: ["DESKTOP-22BJ4SG"]

# Allow HTTP API connections from anywhere
# Connections are encrypted and require user authentication
http.host: 0.0.0.0

# Allow other nodes to join the cluster from anywhere
# Connections are encrypted and mutually authenticated
#transport.host: 0.0.0.0


# 集群的名字
cluster.name: es-cluster

# 节点名字
node.name: es_node1

# ES的监听地址
network.host: 0.0.0.0

#设置对外服务的http端口,默认为9200
http.port: 9200

#设置索引数据的存储路径
path.data: D:/99-tools/elasticsearch-8.2.3-windows-x86_64/elasticsearch-8.2.3/data    
#设置日志文件的存储路径
path.logs: D:/99-tools/elasticsearch-8.2.3-windows-x86_64/elasticsearch-8.2.3/logs    

# 关闭http访问限制
xpack.security.enabled: false

# 增加新的参数,head插件可以访问es
http.cors.enabled: true
http.cors.allow-origin: "*"

# 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: ["es_node1"]  #注意,这个要与node.name填写一致

#屏蔽自动下载geopip
ingest.geoip.downloader.enabled: false

  • 启动服务
    双击elasticsearch-8.2.3\bin\elasticsearch.bat 运行
    9300:Java程序访问的端口
    9200:浏览器、HTTP访问的端口
http://localhost:9200/

 

二、客户端elasticsearch-head安装

  • elasticsearch-head是一款专门针对于Elasticsearch的客户端工具

  • 下载源码
    https://github.com/mobz/elasticsearch-head](https://github.com/mobz/elasticsearch-head

  • 加压后,在elasticsearch-head目录下执行命令
    需要先安装nodejs,下载地址:http://nodejs.cn/download/

npm install
npm run start
  • 安装成功
    http://localhost:9100/

 

三、springboot 集成

  • 依赖
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>jakarta.json</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/co.elastic.clients/elasticsearch-java -->
        <dependency>
            <groupId>co.elastic.clients</groupId>
            <artifactId>elasticsearch-java</artifactId>
            <version>8.2.3</version>
        </dependency>
  • 配置
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.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {

    @Value("${elasticsearch.host-name}")
    private String hostName;

    @Value("${elasticsearch.port}")
    private int port;


    @Bean
    public ElasticsearchClient elasticsearchClient(){
        RestClient client = RestClient.builder(new HttpHost(hostName, port,"http")).build();
        ElasticsearchTransport transport = new RestClientTransport(client,new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }

}

  • index操作类
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class EsGpsIndexService {

    @Autowired
    private ElasticsearchClient client;

    public final static String INDEX_NAME = "gps";

    /**
     * 增加index
     * @throws IOException
     */
    public boolean create() throws IOException {
        CreateIndexResponse indexResponse = client.indices().create(c -> c.index(INDEX_NAME));
        System.out.println(indexResponse.toString());
        return indexResponse.acknowledged();
    }


    /**
     * 查询Index
     * @throws IOException
     */
    public void query() throws IOException {
        GetIndexResponse getIndexResponse = client.indices().get(i -> i.index(INDEX_NAME));
        System.out.println(getIndexResponse.toString());
    }

    /**
     * 判断index是否存在
     * @throws IOException
     */
    public boolean exists() throws IOException {
        BooleanResponse booleanResponse = client.indices().exists(e -> e.index(INDEX_NAME));
        System.out.println(booleanResponse.value());
        return booleanResponse.value();
    }


    /**
     * 删除index
     * @throws IOException
     */
    public void delete() throws IOException {
        DeleteIndexResponse deleteIndexResponse = client.indices().delete(d -> d.index(INDEX_NAME));
        System.out.println(deleteIndexResponse.toString());
    }

}
  • document 操作类

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.QueryBuilders;
import co.elastic.clients.elasticsearch._types.query_dsl.RangeQuery;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonData;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class EsGpsDocumentService {

    @Autowired
    private ElasticsearchClient client;


    /**
     * 插入document
     * @throws IOException
     */
    public void add(GpsInfo gps) throws IOException {
        IndexResponse indexResponse = client.index(i -> i
                .index(EsGpsIndexService.INDEX_NAME)
                //设置id
                .id(gps.getId())
                //
                .document(gps));

    }

    /**
     * 更新Document
     * @throws IOException
     */
    public void update(GpsInfo gps) throws IOException {
        UpdateResponse<GpsInfo> updateResponse = client.update(u -> u
                        .index(EsGpsIndexService.INDEX_NAME)
                        .id(gps.getId())
                        .doc(gps)
                , GpsInfo.class);
    }

    /**
     * 判断Document是否存在
     * @throws IOException
     */
    public void exist(String id) throws IOException {
        BooleanResponse indexResponse = client.exists(e -> e.index(EsGpsIndexService.INDEX_NAME).id(id));
        System.out.println(indexResponse.value());
    }

    /**
     * 查询Document
     * @throws IOException
     */
    public void get(String id) throws IOException {
        GetResponse<GpsInfo> getResponse = client.get(g -> g
                        .index(EsGpsIndexService.INDEX_NAME)
                        .id("1")
                , GpsInfo.class
        );
        System.out.println(getResponse.source());


    }

    /**
     * 删除Document
     * @throws IOException
     */
    public void delete(String id) throws IOException {
        DeleteResponse deleteResponse = client.delete(d -> d
                .index(EsGpsIndexService.INDEX_NAME)
                .id("1")
        );
        System.out.println(deleteResponse.id());
    }

    /**
     * 批量插入Document
     * @throws IOException
     */
    public void bulk(List<GpsInfo> gpsList) throws IOException {

        List<BulkOperation> bulkOperationArrayList = new ArrayList<>();
        //遍历添加到bulk中
        for(GpsInfo gps : gpsList){
            bulkOperationArrayList.add(BulkOperation.of(o->o.index(i->i.document(gps).id(gps.getId()))));
            //bulkOperationArrayList.add(BulkOperation.of(x->x.create(d->d.document(gps).id(gps.getId()).index(EsGpsIndexService.INDEX_NAME))));
        }

        BulkResponse bulkResponse = client.bulk(b -> b.index(EsGpsIndexService.INDEX_NAME).operations(bulkOperationArrayList));

    }

    /**
     * 查询
     * @throws IOException
     * https://wenku.baidu.com/view/a8954a68862458fb770bf78a6529647d27283439.html
     */
    public void search(String vehicleId,long startTime,long endTime,int page,int pageSize) throws IOException {

        SearchResponse<GpsInfo> search = client.search(s -> s
                .index(EsGpsIndexService.INDEX_NAME)
                .query(q -> q
                        .bool(b -> b
                                .filter(m -> m.term(t -> t.field("vehicleId").value(vehicleId)))
                                .filter(f -> f.range(x-> x.field("gpsTime").gte(JsonData.of(startTime)).lte(JsonData.of(endTime))))
                         ))

                //分页查询,从第0页开始查询20个document
                .from(page)
                .size(pageSize)
                //按时间降序排序
                //.sort(f->f.field(o->o.field("gpsTime").order(SortOrder.Desc)))
                , GpsInfo.class
        );
        for (Hit<GpsInfo> hit : search.hits().hits()) {
            System.out.println(hit.source());
        }
    }
}
  • 实体
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class GpsInfo {

    private String id;
    private String vehicleId;
    private String deviceId;
    private String location;
    private Long gpsTime;
    private Long createTime;

}
  • 测试例子
@RestController
@RequestMapping("/gps")
public class GpsController {

    @Autowired
    EsGpsIndexService esGpsIndexService;

    @Autowired
    EsGpsDocumentService esGpsDocumentService;

    @GetMapping("/test")
    public String test() throws IOException {

        boolean exist = esGpsIndexService.exists();
        if(!exist){
            esGpsIndexService.create();
        }

        esGpsIndexService.query();

        //
        /*GpsInfo gps = new GpsInfo();
        gps.setId("1");
        gps.setDeviceId("1111");
        gps.setVehicleId("123");
        gps.setLocation("12,33");
        gps.setCreateTime(System.currentTimeMillis());
        gps.setGpsTime(System.currentTimeMillis());
        esGpsDocumentService.add(gps);*/

        /*List<GpsInfo> gpsList =  new ArrayList<>();
        int i= 0;
        GpsInfo gps = null;
        long time = 1656041715000L;
        while (i < 10000){
            gps = new GpsInfo();
            gps.setId(String.valueOf(i*10000));
            gps.setDeviceId("1111");
            gps.setVehicleId("123456");
            gps.setLocation("12233.2232,33.2512235");
            gps.setCreateTime(time);
            gps.setGpsTime(time);
            gpsList.add(gps);
            //
            time += 1000;
            i += 1;
        }
        esGpsDocumentService.bulk(gpsList);*/


        long start = 1656041715000L;
        long end   = 1656041725000L;
        String v = "123456";
        esGpsDocumentService.search(v,start,end,0,20);


        return "elasticSearch test!!!!";
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/622431.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

自学大语言模型之GPT

GPT火爆的发展史 2017年6月OpenAI联合DeepMind首次正式提出的&#xff1a;Deep Reinforcement Learning from Human Preferences&#xff0c;即基于人类偏好的深度强化学习&#xff0c;简称RLHF 2017年7月的OpenAI团队提出的对TRPO算法的改进&#xff1a;PPO算法 GPT-1&#…

【笔记】算法简单题

题解&#xff1a; import java.util.HashMap; import java.util.Map;public class Test {//暴力解决法public static int[] twoSum(int[] nums, int target) {for(int i0;i<nums.length;i){for(int ji1;j<nums.length;j){if(nums[i]nums[j]target){int[] indexs{0,0};i…

澳大利亚道路安全的AiRAP自动化审核(英)(附下载)

项目概况 该项目由新南威尔士州交通局&#xff08;TfNSW&#xff09;领导&#xff0c;悉尼科技大学&#xff0c;国际道路评估计划&#xff08;iRAP&#xff09;和澳大利亚地理空间数据专家Anditi的研究和协助。 该项目开展的工作是全球首创&#xff0c;其活动和成果是澳大利亚和…

15、库函数开发小结

目录 0x01、初始化 0x02、数据输入输出 0x03、状态位、标志位 0x0001、事件 0x0002、标志位的检查与清除 0x04、外设函数分类 本节我们来总结一下ST库开发的步骤和共同点&#xff0c;在总结之前&#xff0c;我们来看一下基本所有外设都有的以下几类寄存器&#xff1a; 1…

chatgpt赋能python:Python就业指南:市场现状、薪资情况及就业前景

Python就业指南&#xff1a;市场现状、薪资情况及就业前景 Python作为一门既新颖又多用的编程语言&#xff0c;已经引起了越来越多的关注。据统计&#xff0c;在2019年&#xff0c;全球Python使用者数已经达到了960万人。而在中国&#xff0c;Python的应用也越来越普及&#x…

PolyFormer:将图像分割称为顺序多边形生成

文章目录 PolyFormer: Referring Image Segmentation as Sequential Polygon Generation\摘要本文方法Multi-modal Transformer EncoderRegression-based Transformer Decoder 实验结果 PolyFormer: Referring Image Segmentation as Sequential Polygon Generation\ 摘要 在…

为什么会有分布式锁?分布式锁实现方案

分布式锁是控制分布式系统之间同步访问共享资源的一种方式。分布式环境下会出现资源竞争的地方都需要分布式锁的协调。 分布式锁的作用&#xff1a;在整个系统提供一个全局、唯一的锁&#xff0c;在分布式系统中每个系统在进行相关操作的时候需要获取到该锁&#xff0c;才能执…

Calibre 6.18.1 正式发布,功能强大的开源电子书工具

导读Calibre 开源项目是 Calibre 官方出的电子书管理工具。它可以查看&#xff0c;转换&#xff0c;编辑和分类所有主流格式的电子书。Calibre 是个跨平台软件&#xff0c;可以在 Linux、Windows 和 macOS 上运行。 Calibre 6.18.1 正式发布&#xff0c;此次更新内容如下&#…

数据挖掘(6.1)--神经网络

目录 神经网络简介 BP算法 Delta学习规则的基本原理 BP神经网络的结构 BP神经网络的算法描述 神经网络训练一般步骤 后向传播算法的主要步骤 优缺点 BP算法简单举例 神经网络简介 神经网络是一种计算模型&#xff0c;它受到人脑处理信息的生物神经网络过程的启发。人…

围绕工业 APT 攻击的主要问题

高级持续威胁 (APT) 行动在受害者网络内取得成功的关键因素包括人为因素、安全措施不足、网络安全解决方案更新和配置方面的挑战以及其他因素。 虽然其中一些原因可能看起来微不足道&#xff0c;但卡巴斯基专家在事件响应活动中经常遇到这些问题。 为帮助公司减轻相关威胁并确…

win系统将脚手架的软链接指向本地脚手架

先了解一下脚手架研发、发布、安装、调试发大致流程&#xff1a; 本地研发&#xff0c;具体研发过程略当前目录下登录npm npm login发布脚手架 npm publish安装脚手架 npm i -g xxxx&#xff08;win系统会在系统盘的nodejs文件夹下自动添加脚手架执行命令和执行文件&#xff0…

94.构建样品餐部分第二节

上节课完成的页面是这样的 ● 之后我们设置一下图标 .meal-attribute {font-size: 1.8rem;font-weight: 500;display: flex;align-items: center;gap: 1.6rem; }.meal-img {width: 100%; }.meal-icon {height: 2.4rem;width: 2.4rem;color: #e67e22; }● 为了突出这些参数的…

Go1.21 速览:新内置函数 clear、min、max 和新标准库包 cmp!

大家好&#xff0c;我是煎鱼。 前面给大家分享了 Go1.21 正式不支持 macOS 10.13 和 10.14 的支持。吓得我赶紧把我的 2017 款的老爷机从 10.14 升成 13.4。感觉 mbp 已经变成了暖宝宝。&#x1f605; 今天给大家分享的是 Go 1.21 中的两个双新增项&#xff0c;分别是新的 3 个…

QTYX量化系统实战案例分享|涨停股池中寻找反弹机会-202306

前言 “实战案例分享系列”是和大家分享一些股票量化分析工具QTYX在实战中的应用案例&#xff08;包括失败的案例&#xff09;&#xff0c;这样能够帮助大家更好地去理解QTYX中的功能设计&#xff0c;也能更好地帮助大家搭建出属于自己的量化交易系统。 关于QTYX的使用攻略可以…

Clion开发STM32之链接文件进行模块的一个解耦(编程方式)

问题的引入 在单片机的开发过程中&#xff0c;往往涉及到驱动的移植&#xff0c;但是移植的过程中又会去添加和修改主逻辑的驱动引脚初始化或时钟初始化&#xff0c;这里面就会存在一个问题就是&#xff1a;改动的地方太多了&#xff0c;容易影响到其它功能模块。所以能不能做…

200SMART CPU输入/输出接线的几个关键点

总结来看&#xff0c;S7-200系列PLC提供4个不同的基本型号的8种CPU&#xff0c;其接线方式也可大致分为6种&#xff1a; 1.CPU SR20接线 2.CPU SR40接线 3.CPU CR40接线 4.CPU ST40接线 5. CPU SR60接线 6. CPU ST60接线 除了CPU外&#xff0c;我们还需要了解200smart PLC的数…

Rocketmq面试(二)Rocketmq如何保证消息不丢失

如果想要保证消息不丢失就要知道&#xff0c;消息可能出现丢失得地方。 1.producer发送消息 2.Broker存储消息 3.Consumer消费消息 4.Broker主从切换 下面一共有9个维度可以保证消息不丢失。 目录 维度一&#xff1a;同步发送 维度二.异步发送 维度三.刷盘策略 维度四…

后端——平台登录功能实战

这里写目录标题 一、登录接口设计示意图二、后端设计三、创建用户表四、后端鉴权逻辑五、登录接口实现六、使用 JWT 生成 token七、路由鉴权八、登录与测试用例服务结合九、跨域一、登录接口设计示意图 二、后端设计 三、创建用户表 db=SQLAlchemy(app

华尔街新风向:多基金失英伟达机会

在过去一年多的美联储暴力加息周期中&#xff0c;科技成长股一直不怎么受到主流投资者待见&#xff0c;但面对今年美股“人工智能涨个不停”的局面后&#xff0c;过去两周里大量的知名基金都在撒开脚丫子狂追高速狂飙的“英伟达列车”。 根据监管文件显示&#xff0c;包括道富…

视频与AI,与进程交互(一)

目的 正在写一个视频与AI的工具&#xff0c;从接入&#xff0c;算法处理&#xff0c;转发&#xff0c;存储&#xff0c; 到调用AI进程&#xff0c;并且与AI进程进行交互&#xff0c;插件化&#xff0c;脚本化&#xff0c;做得比较辛苦&#xff0c;期间的进程和线程交互以及结果…