elasticsearch7.4集羣搭建和go查詢es demo

1.   elasticsearch集羣搭建

1.1 下載安裝jdk1.8(es須要jre運行環境)

去oracle官網下載jdk, 上傳到服務器,執行下面命令安裝:html

rpm -ivh jdk-8u231-linux-x64.rpm複製代碼

oracle jdk1.8下載頁面:  www.oracle.com/technetwork…
java

1.2 下載安裝安裝elasticsearch

wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.4.2-x86_64.rpm
rpm -ivh elasticsearch-7.4.2-x86_64.rpm
systemctl daemon-reload                    #reload配置
systemctl enable elasticsearch.service     #設置開機啓動
複製代碼

1.3 配置elasticsearch(以3個節點爲例)

mv  /etc/elasticsearch/elasticsearch.yml /etc/elasticsearch/elasticsearch.yml.baknode

vim /etc/elasticsearch/elasticsearch.yml 建立新配置文件linux

 除node.name 須要更改外,其餘同樣git

cluster.name: elasticsearch
node.name: node1                    #隨機器變化。node2 node3 以此推
network.host: 0.0.0.0
http.port: 9200
transport.tcp.port: 9300
transport.tcp.compress: true
path.data: /var/lib/elasticsearch
path.logs: /var/log/elasticsearch   
action.auto_create_index: true
discovery.zen.minimum_master_nodes: 1
node.max_local_storage_nodes: 3
discovery.seed_hosts: ["ip1","ip2","ip3"]
cluster.initial_master_nodes: ["node1"]複製代碼

配置解釋:github

cluster.name:                          集羣名稱
node.name: node1                       節點名稱
network.host: 0.0.0.0                  監控地址 
http.port: 9200                        數據端口
transport.tcp.port: 9300               java api端口
transport.tcp.compress: true
path.data: /var/lib/elasticsearch      數據目錄
path.logs: /var/log/elasticsearch      日誌目錄
action.auto_create_index: true         自動建立索引
discovery.zen.minimum_master_nodes:    最小通訊點數,(3節點先1,避免腦裂)
node.max_local_storage_nodes:          單機多進程數
discovery.seed_hosts:                  集羣節點ip
cluster.initial_master_nodes:          初始化指定的master節點複製代碼

1.4 啓動elasticsearch

執行啓動命令:golang

systemctl start elasticsearch複製代碼

查看日誌信息:json

tail -f /var/log/elasticsearch/elasticsearch.log複製代碼

2. golang demo(查看某個索引內容)

2.1 輸出該索引總條數,以及顯示最近10條

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/olivere/elastic/v7"
	"log"
)

type Subject struct {
	id            string
	name          string
	age           int
	region        string
}

func main() {

	var client, _ = elastic.NewSimpleClient(elastic.SetURL("http://127.0.0.1:9200/"))
	ctx := context.Background()
	boolQuery := elastic.NewBoolQuery()

	searchResult,err := client.Search().Index("index_name").
		Query(boolQuery).From(0).Size(10).Do(ctx)
	if err != nil {
		log.Println("err:", err)
	}

	if searchResult.TotalHits() > 0 {
		log.Printf("Found a total of %d indice\n", searchResult.TotalHits())
		for _, hit := range searchResult.Hits.Hits {
			var t Subject
			err := json.Unmarshal(hit.Source, &t)
			if err != nil {
				log.Printf("%v", err)
			}
			fmt.Printf("name: %v,age: %v, region: %v\n",t.name,t.age,t.region)
		}
	} else {
		log.Println("沒有查詢到數據")
	}
}
複製代碼
相關文章
相關標籤/搜索