elasticsearch 8.2.3 安裝及springboot簡(jiǎn)單使用

一陈惰、下載安裝

# ======================== 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

# 節(jié)點(diǎn)名字
node.name: es_node1

# ES的監(jiān)聽地址
network.host: 0.0.0.0

#設(shè)置對(duì)外服務(wù)的http端口,默認(rèn)為9200
http.port: 9200

#設(shè)置索引數(shù)據(jù)的存儲(chǔ)路徑
path.data: D:/99-tools/elasticsearch-8.2.3-windows-x86_64/elasticsearch-8.2.3/data    
#設(shè)置日志文件的存儲(chǔ)路徑
path.logs: D:/99-tools/elasticsearch-8.2.3-windows-x86_64/elasticsearch-8.2.3/logs    

# 關(guān)閉http訪問限制
xpack.security.enabled: false

# 增加新的參數(shù),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"]  #注意废境,這個(gè)要與node.name填寫一致

#屏蔽自動(dòng)下載geopip
ingest.geoip.downloader.enabled: false

  • 啟動(dòng)服務(wù)
    雙擊elasticsearch-8.2.3\bin\elasticsearch.bat 運(yùn)行
    9300:Java程序訪問的端口
    9200:瀏覽器疾掰、HTTP訪問的端口
http://localhost:9200/
image.png

二靖诗、客戶端elasticsearch-head安裝

npm install
npm run start
image.png

三、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)
                //設(shè)置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))))
                         ))

                //分頁(yè)查詢讲岁,從第0頁(yè)開始查詢20個(gè)document
                .from(page)
                .size(pageSize)
                //按時(shí)間降序排序
                //.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());
        }
    }
}
  • 實(shí)體
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;

}
  • 測(cè)試?yán)?/li>
@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!!!!";
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末我擂,一起剝皮案震驚了整個(gè)濱河市衬以,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌校摩,老刑警劉巖看峻,帶你破解...
    沈念sama閱讀 212,029評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異衙吩,居然都是意外死亡互妓,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,395評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門坤塞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來冯勉,“玉大人,你說我怎么就攤上這事摹芙∽普” “怎么了?”我有些...
    開封第一講書人閱讀 157,570評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵浮禾,是天一觀的道長(zhǎng)交胚。 經(jīng)常有香客問我,道長(zhǎng)伐厌,這世上最難降的妖魔是什么承绸? 我笑而不...
    開封第一講書人閱讀 56,535評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮挣轨,結(jié)果婚禮上军熏,老公的妹妹穿的比我還像新娘。我一直安慰自己卷扮,他們只是感情好荡澎,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,650評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著晤锹,像睡著了一般摩幔。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上鞭铆,一...
    開封第一講書人閱讀 49,850評(píng)論 1 290
  • 那天或衡,我揣著相機(jī)與錄音,去河邊找鬼车遂。 笑死封断,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的舶担。 我是一名探鬼主播坡疼,決...
    沈念sama閱讀 39,006評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼衣陶!你這毒婦竟也來了柄瑰?” 一聲冷哼從身側(cè)響起闸氮,我...
    開封第一講書人閱讀 37,747評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎教沾,沒想到半個(gè)月后蒲跨,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,207評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡授翻,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,536評(píng)論 2 327
  • 正文 我和宋清朗相戀三年财骨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片藏姐。...
    茶點(diǎn)故事閱讀 38,683評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡隆箩,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出羔杨,到底是詐尸還是另有隱情捌臊,我是刑警寧澤,帶...
    沈念sama閱讀 34,342評(píng)論 4 330
  • 正文 年R本政府宣布兜材,位于F島的核電站理澎,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏曙寡。R本人自食惡果不足惜糠爬,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,964評(píng)論 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦筛婉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,772評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)蕊唐。三九已至屋摔,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間替梨,已是汗流浹背钓试。 一陣腳步聲響...
    開封第一講書人閱讀 32,004評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留副瀑,地道東北人弓熏。 一個(gè)月前我還...
    沈念sama閱讀 46,401評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像俗扇,于是被迫代替她去往敵國(guó)和親硝烂。 傳聞我的和親對(duì)象是個(gè)殘疾皇子箕别,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,566評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容