Parcourir la source

添加索引 创建、删除、添加别名、删除别名函数

wcc il y a 1 an
Parent
commit
0a80eb1ae4
2 fichiers modifiés avec 87 ajouts et 1 suppressions
  1. 45 0
      elastic/elasticSim.go
  2. 42 1
      elastic/elastic_test.go

+ 45 - 0
elastic/elasticSim.go

@@ -466,3 +466,48 @@ func (e *Elastic) InsertOrUpdate(index string, docs []map[string]interface{}) er
 	}
 	return nil
 }
+
+//ExistsIndex 判断索引是否存在
+func (e *Elastic) ExistsIndex(index string) (exists bool, err error) {
+	client := e.GetEsConn()
+	defer e.DestoryEsConn(client)
+	exists, err = client.IndexExists(index).Do(context.Background())
+
+	return
+}
+
+//CreateIndex 创建索引
+func (e *Elastic) CreateIndex(index string, mapping string) (err error) {
+	client := e.GetEsConn()
+	defer e.DestoryEsConn(client)
+
+	_, err = client.CreateIndex(index).BodyString(mapping).Do(context.Background())
+	return
+}
+
+//DeleteIndex 删除索引
+func (e *Elastic) DeleteIndex(index string) (err error) {
+	client := e.GetEsConn()
+	defer e.DestoryEsConn(client)
+	_, err = client.DeleteIndex(index).Do(context.Background())
+
+	return
+}
+
+//RemoveAlias 移除别名
+func (e *Elastic) RemoveAlias(index, aliasName string) (err error) {
+	client := e.GetEsConn()
+	defer e.DestoryEsConn(client)
+	_, err = client.Alias().Remove(index, aliasName).Do(context.Background())
+
+	return
+}
+
+//SetAlias 添加别名
+func (e *Elastic) SetAlias(index, aliasName string) (err error) {
+	client := e.GetEsConn()
+	defer e.DestoryEsConn(client)
+	_, err = client.Alias().Add(index, aliasName).Do(context.Background())
+
+	return
+}

+ 42 - 1
elastic/elastic_test.go

@@ -4,6 +4,7 @@ import (
 	"encoding/json"
 	"fmt"
 	es "github.com/olivere/elastic/v7"
+	"github.com/stretchr/testify/assert"
 	"testing"
 )
 
@@ -40,7 +41,7 @@ func TestCount(t *testing.T) {
 	}
 
 	fmt.Println("qqq", string(bytes))
-	count1 := esClinet.Count("bidding", "", boolQuery)
+	count1 := esClinet.Count("bidding", boolQuery)
 	fmt.Println(count1)
 }
 
@@ -70,3 +71,43 @@ func TestBulkSave(t *testing.T) {
 	esClinet.UpdateBulk("bidding", arru...)
 	fmt.Println(arru)
 }
+
+func TestElastic_ExistsIndex(t *testing.T) {
+	esClinet = Elastic{
+		S_esurl:  "http://127.0.0.1:19805",
+		I_size:   2,
+		Username: "es_all",
+		Password: "TopJkO2E_d1x",
+	}
+	esClinet.InitElasticSize()
+
+	res, err := esClinet.ExistsIndex("bidding_20231118")
+	assert.Equal(t, nil, err)
+	assert.Equal(t, true, res)
+}
+
+func TestElastic_SetAlias(t *testing.T) {
+	esClinet = Elastic{
+		S_esurl:  "http://127.0.0.1:19805",
+		I_size:   2,
+		Username: "es_all",
+		Password: "TopJkO2E_d1x",
+	}
+	esClinet.InitElasticSize()
+
+	err := esClinet.SetAlias("bidding_20231118", "bidding_pre")
+	assert.Equal(t, nil, err)
+}
+
+func TestElastic_RemoveAlias(t *testing.T) {
+	esClinet = Elastic{
+		S_esurl:  "http://127.0.0.1:19805",
+		I_size:   2,
+		Username: "es_all",
+		Password: "TopJkO2E_d1x",
+	}
+	esClinet.InitElasticSize()
+	err := esClinet.RemoveAlias("bidding_20231118", "bidding_pre")
+	assert.Equal(t, nil, err)
+
+}