-
Notifications
You must be signed in to change notification settings - Fork 4
/
elasticSearchCtl.go
95 lines (77 loc) · 2.4 KB
/
elasticSearchCtl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package elasticsearchctl
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"strconv"
"strings"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"
"github.com/remiges-tech/logharbour/logharbour"
)
// Function CreateElasticIndex create an Elasticsearch index with the provided index name and index body.
func CreateElasticIndex(es *elasticsearch.Client, indexName string, indexBody string) error {
// Create the index request
req := esapi.IndicesCreateRequest{
Index: indexName,
Body: strings.NewReader(indexBody),
}
// Perform the request
res, err := req.Do(context.Background(), es)
if err != nil {
return fmt.Errorf("error creating the index: %s", err)
}
defer res.Body.Close()
// Print the response status and body
fmt.Println("Response status:", res.Status())
if res.IsError() {
var errorResponse map[string]interface{}
if err := json.NewDecoder(res.Body).Decode(&errorResponse); err != nil {
return fmt.Errorf("error parsing the error response body: %s", err)
}
log.Fatalf("Error creating the index: %s", errorResponse["error"].(map[string]interface{})["reason"])
} else {
fmt.Println("Index created successfully:")
}
return nil
}
// Function InsertLog bulk insert an array of log entries into an Elasticsearch index using the provided Elasticsearch client.
func InsertLog(es *elasticsearch.Client, logs []logharbour.LogEntry, indexName string) error {
for i, log := range logs {
dataJson, err := json.Marshal(log)
if err != nil {
return fmt.Errorf("error while unmarshaling log: %v", err)
}
js := string(dataJson)
req := esapi.IndexRequest{
Index: indexName,
DocumentID: strconv.Itoa(i + 1),
Body: strings.NewReader(js),
Refresh: "true",
}
res, err := req.Do(context.Background(), es)
if err != nil {
return fmt.Errorf("error while adding data in es :%v", err)
}
defer res.Body.Close()
if res.IsError() {
return fmt.Errorf("error indexing document ID=%s", res)
}
}
return nil
}
// Function ReadLogFromFile read log entries from a file, unmarshal the file data, and return slice of LogEntry
func ReadLogFromFile(filepath string) ([]logharbour.LogEntry, error) {
byteValue, err := os.ReadFile(filepath)
if err != nil {
return nil, err
}
var LogEntries []logharbour.LogEntry
err = json.Unmarshal(byteValue, &LogEntries)
if err != nil {
return nil, err
}
return LogEntries, nil
}