Compare commits

..
4 Commits
Author SHA1 Message Date
loveuer d3524d0f05 wip: mapping,setting import 2024-03-25 20:22:18 +08:00
loveuer b0b0ec2b58 wip: mapping type 2024-03-24 20:47:54 +08:00
loveuer f1af294ced feat: dump from es with query, limit 2024-03-23 21:25:19 +08:00
loveuer 983533237f wip: basic feat 2024-03-22 18:05:47 +08:00
13 changed files with 145 additions and 527 deletions
-56
View File
@@ -1,56 +0,0 @@
name: Auto Build
on:
push:
tags:
- 'v*'
jobs:
build-job:
runs-on: ubuntu-latest
permissions:
id-token: write
contents: write
pull-requests: write
repository-projects: write
steps:
- name: checkout repository
uses: actions/checkout@v4
- name: install golang
uses: actions/setup-go@v4
with:
go-version: '1.18'
- name: build linux amd64
run: CGO_ENABLE=0 GOOS=linux GOARCH=amd64 go build -ldflags='-s -w' -o dist/esgo2dump_${{ github.ref_name }}_linux_amd64 .
- name: build linux arm64
run: CGO_ENABLE=0 GOOS=linux GOARCH=arm64 go build -ldflags='-s -w' -o dist/esgo2dump_${{ github.ref_name }}_linux_arm64 .
- name: build windows amd64
run: CGO_ENABLE=0 GOOS=windows GOARCH=amd64 go build -ldflags='-s -w' -o dist/esgo2dump_${{ github.ref_name }}_windows_amd64.exe .
- name: build windows arm64
run: CGO_ENABLE=0 GOOS=windows GOARCH=arm64 go build -ldflags='-s -w' -o dist/esgo2dump_${{ github.ref_name }}_windows_arm64.exe .
- name: build darwin amd64
run: CGO_ENABLE=0 GOOS=darwin GOARCH=amd64 go build -ldflags='-s -w' -o dist/esgo2dump_${{ github.ref_name }}_darwin_amd64 .
- name: build darwin arm64
run: CGO_ENABLE=0 GOOS=darwin GOARCH=arm64 go build -ldflags='-s -w' -o dist/esgo2dump_${{ github.ref_name }}_darwin_arm64 .
- name: create releases
id: create_releases
uses: "marvinpinto/action-automatic-releases@latest"
with:
repo_token: "${{ secrets.GITHUB_TOKEN }}"
title: "Release_${{ github.ref_name }}"
prerelease: false
files: |
dist/esgo2dump_${{ github.ref_name }}_linux_amd64
dist/esgo2dump_${{ github.ref_name }}_linux_arm64
dist/esgo2dump_${{ github.ref_name }}_windows_amd64.exe
dist/esgo2dump_${{ github.ref_name }}_windows_arm64.exe
dist/esgo2dump_${{ github.ref_name }}_darwin_amd64
dist/esgo2dump_${{ github.ref_name }}_darwin_amd64
dist/esgo2dump_${{ github.ref_name }}_darwin_arm64
+1 -2
View File
@@ -5,5 +5,4 @@ data.json
mapping.json mapping.json
setting.json setting.json
output.json output.json
*.txt *.txt
dist
+2 -2
View File
@@ -1,6 +1,6 @@
module github.com/loveuer/esgo2dump module esgo2dump
go 1.18 go 1.20
require ( require (
github.com/elastic/go-elasticsearch/v7 v7.17.10 github.com/elastic/go-elasticsearch/v7 v7.17.10
+3 -11
View File
@@ -2,8 +2,7 @@ package cmd
import ( import (
"context" "context"
"esgo2dump/internal/opt"
"github.com/loveuer/esgo2dump/internal/opt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -17,13 +16,9 @@ var (
Example: ` Example: `
esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json
esgo2dump --input=http://127.0.0.1:9200/some_index --output=http://192.168.1.1:9200/some_index --limit=5000
esgo2dump --input=https://username:password@127.0.0.1:9200/some_index --output=./data.json esgo2dump --input=https://username:password@127.0.0.1:9200/some_index --output=./data.json
esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query='{"match": {"name": "some_name"}}' esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query='{"match": {"name": "some_name"}}'`,
esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query_file=my_queries.json`,
} }
f_input string f_input string
@@ -31,19 +26,16 @@ esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query_
f_limit int f_limit int
f_type string f_type string
f_query string f_query string
f_query_file string
) )
func init() { func init() {
rootCommand.Flags().BoolVar(&opt.Debug, "debug", false, "") rootCommand.Flags().BoolVar(&opt.Debug, "debug", false, "")
rootCommand.Flags().IntVar(&opt.Timeout, "timeout", 30, "max timeout seconds per operation with limit") rootCommand.Flags().IntVar(&opt.Timeout, "timeout", 30, "max timeout seconds per operation with limit")
rootCommand.Flags().StringVarP(&f_input, "input", "i", "", "*required: input file or es url (example :data.json / http://127.0.0.1:9200/my_index)") rootCommand.Flags().StringVarP(&f_input, "input", "i", "http://127.0.0.1:9200/my_index", "")
rootCommand.Flags().StringVarP(&f_output, "output", "o", "output.json", "") rootCommand.Flags().StringVarP(&f_output, "output", "o", "output.json", "")
rootCommand.Flags().StringVarP(&f_type, "type", "t", "data", "data/mapping/setting") rootCommand.Flags().StringVarP(&f_type, "type", "t", "data", "data/mapping/setting")
rootCommand.Flags().StringVarP(&f_query, "query", "q", "", `query dsl, example: {"bool":{"must":[{"term":{"name":{"value":"some_name"}}}],"must_not":[{"range":{"age":{"gte":18,"lt":60}}}]}}`) rootCommand.Flags().StringVarP(&f_query, "query", "q", "", `query dsl, example: {"bool":{"must":[{"term":{"name":{"value":"some_name"}}}],"must_not":[{"range":{"age":{"gte":18,"lt":60}}}]}}`)
rootCommand.Flags().StringVar(&f_query_file, "query_file", "", `query json file (will execute line by line)`)
rootCommand.Flags().IntVarP(&f_limit, "limit", "l", 100, "") rootCommand.Flags().IntVarP(&f_limit, "limit", "l", 100, "")
} }
+32 -156
View File
@@ -1,44 +1,21 @@
package cmd package cmd
import ( import (
"bufio"
"context" "context"
"encoding/json" "encoding/json"
"errors"
"esgo2dump/internal/interfaces"
"esgo2dump/internal/opt"
"esgo2dump/internal/xes"
"esgo2dump/internal/xfile"
"fmt" "fmt"
"net/url"
"os"
"github.com/loveuer/esgo2dump/internal/interfaces"
"github.com/loveuer/esgo2dump/internal/opt"
"github.com/loveuer/esgo2dump/internal/xes"
"github.com/loveuer/esgo2dump/internal/xfile"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"io"
"net/url"
"os"
) )
func check(cmd *cobra.Command) error {
if f_input == "" {
return cmd.Help()
//return fmt.Errorf("must specify input(example: data.json/http://127.0.0.1:9200/my_index)")
}
if f_limit == 0 || f_limit > 10000 {
return fmt.Errorf("invalid limit(1 - 10000)")
}
if f_query != "" && f_query_file != "" {
return fmt.Errorf("cannot specify both query and query_file at the same time")
}
switch f_type {
case "data", "mapping", "setting":
default:
return fmt.Errorf("unknown type=%s", f_type)
}
return nil
}
func run(cmd *cobra.Command, args []string) error { func run(cmd *cobra.Command, args []string) error {
var ( var (
err error err error
@@ -50,8 +27,10 @@ func run(cmd *cobra.Command, args []string) error {
logrus.SetLevel(logrus.DebugLevel) logrus.SetLevel(logrus.DebugLevel)
} }
if err = check(cmd); err != nil { switch f_type {
return err case "data", "mapping", "setting":
default:
return fmt.Errorf("unknown type=%s", f_type)
} }
if ioi, err = newIO(f_input, interfaces.IOInput); err != nil { if ioi, err = newIO(f_input, interfaces.IOInput); err != nil {
@@ -67,45 +46,23 @@ func run(cmd *cobra.Command, args []string) error {
_ = ioo.Close() _ = ioo.Close()
}() }()
if (f_query_file != "" || f_query != "") && ioi.IsFile() {
return fmt.Errorf("with file input, query or query_file can't be supported")
}
switch f_type { switch f_type {
case "data": case "data":
if err = executeData(cmd.Context(), ioi, ioo); err != nil { return executeData(cmd.Context(), ioi, ioo)
return err
}
logrus.Info("Dump: write data succeed!!!")
return nil
case "mapping": case "mapping":
var mapping map[string]any var mapping map[string]any
if mapping, err = ioi.ReadMapping(cmd.Context()); err != nil { if mapping, err = ioi.ReadMapping(); err != nil {
return err return err
} }
if err = ioo.WriteMapping(cmd.Context(), mapping); err != nil { return ioo.WriteMapping(mapping)
return err
}
logrus.Info("Dump: write mapping succeed!!!")
return nil
case "setting": case "setting":
var setting map[string]any var setting map[string]any
if setting, err = ioi.ReadSetting(cmd.Context()); err != nil { if setting, err = ioi.ReadSetting(); err != nil {
return err return err
} }
if err = ioo.WriteSetting(cmd.Context(), setting); err != nil { return ioo.WriteSetting(setting)
return err
}
logrus.Info("Dump: write setting succeed!!!")
return nil
default: default:
return fmt.Errorf("unknown type=%s", f_type) return fmt.Errorf("unknown type=%s", f_type)
} }
@@ -114,119 +71,38 @@ func run(cmd *cobra.Command, args []string) error {
func executeData(ctx context.Context, input, output interfaces.DumpIO) error { func executeData(ctx context.Context, input, output interfaces.DumpIO) error {
var ( var (
err error err error
ch = make(chan []*interfaces.ESSource, 1) lines []*interfaces.ESSource
errCh = make(chan error)
queries = make([]map[string]any, 0)
)
if f_query != "" {
query := make(map[string]any)
if err = json.Unmarshal([]byte(f_query), &query); err != nil {
return fmt.Errorf("invalid query err=%v", err)
}
queries = append(queries, query)
}
if f_query_file != "" {
var (
qf *os.File
)
if qf, err = os.Open(f_query_file); err != nil {
return fmt.Errorf("open query_file err=%v", err)
}
defer func() {
_ = qf.Close()
}()
scanner := bufio.NewScanner(qf)
lineCount := 1
for scanner.Scan() {
line := scanner.Text()
oq := make(map[string]any)
if err = json.Unmarshal([]byte(line), &oq); err != nil {
return fmt.Errorf("query file line=%d invalid err=%v", lineCount, err)
}
queries = append(queries, oq)
if len(queries) > 10000 {
return fmt.Errorf("query_file support max lines=%d", 10000)
}
lineCount++
}
}
if len(queries) == 0 {
queries = append(queries, nil)
}
go func(c context.Context) {
var (
lines []*interfaces.ESSource
)
defer func() {
close(ch)
}()
for _, query := range queries {
select {
case <-c.Done():
return
default:
if lines, err = input.ReadData(c, f_limit, query); err != nil {
errCh <- err
return
}
if len(lines) == 0 {
input.ResetOffset()
continue
}
ch <- lines
}
}
}(ctx)
var (
succeed int succeed int
total int
docs []*interfaces.ESSource
ok bool
) )
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
case err = <-errCh: default:
return err
case docs, ok = <-ch: if lines, err = input.ReadData(f_limit); err != nil {
if !ok { if errors.Is(err, io.EOF) {
return nil
}
return err return err
} }
if len(docs) == 0 { if len(lines) == 0 {
return nil return nil
} }
if succeed, err = output.WriteData(ctx, docs); err != nil { if succeed, err = output.WriteData(lines); err != nil {
return err return err
} }
if succeed != len(docs) { if succeed != len(lines) {
return fmt.Errorf("cmd.run: got lines=%d, only succeed=%d", len(docs), succeed) return fmt.Errorf("cmd.run: got lines=%d, only succeed=%d", len(lines), succeed)
} }
total += succeed logrus.Infof("Dump: %d docs succeed!!!", succeed)
logrus.Infof("Dump: succeed=%d total=%d docs succeed!!!", succeed, total)
} }
} }
} }
@@ -264,7 +140,7 @@ func newIO(source string, ioType interfaces.IO) (interfaces.DumpIO, error) {
logrus.Debugf("newIO.%s: source as url=%+v", ioType.Code(), *iurl) logrus.Debugf("newIO.%s: source as url=%+v", ioType.Code(), *iurl)
return xes.NewClient(iurl, ioType) return xes.NewClient(iurl, qm)
ClientByFile: ClientByFile:
if ioType == interfaces.IOOutput { if ioType == interfaces.IOOutput {
+7 -14
View File
@@ -1,21 +1,14 @@
package interfaces package interfaces
import "context"
type DumpIO interface { type DumpIO interface {
ReadData(context.Context, int, map[string]any) ([]*ESSource, error) ReadData(int) ([]*ESSource, error)
WriteData(ctx context.Context, docs []*ESSource) (int, error) ReadMapping() (map[string]any, error)
ReadSetting() (map[string]any, error)
ResetOffset() WriteData(docs []*ESSource) (int, error)
WriteMapping(map[string]any) error
ReadMapping(context.Context) (map[string]any, error) WriteSetting(map[string]any) error
WriteMapping(context.Context, map[string]any) error
ReadSetting(ctx context.Context) (map[string]any, error)
WriteSetting(context.Context, map[string]any) error
Close() error Close() error
IOType() IO IsInput() bool
IsFile() bool IsFile() bool
} }
-6
View File
@@ -25,9 +25,3 @@ type ESResponse struct {
Hits []*ESSource `json:"hits"` Hits []*ESSource `json:"hits"`
} `json:"hits"` } `json:"hits"`
} }
type ESMapping map[string]struct {
Mappings struct {
Properties map[string]any `json:"properties"`
} `json:"mappings"`
}
-11
View File
@@ -15,14 +15,3 @@ func Timeout(seconds ...int) context.Context {
return ctx return ctx
} }
func TimeoutCtx(ctx context.Context, seconds ...int) context.Context {
second := 30
if len(seconds) > 0 && seconds[0] > 0 {
second = seconds[0]
}
timeout, _ := context.WithTimeout(ctx, time.Duration(second)*time.Second)
return timeout
}
+81 -164
View File
@@ -5,118 +5,112 @@ import (
"context" "context"
"crypto/tls" "crypto/tls"
"encoding/json" "encoding/json"
"esgo2dump/internal/interfaces"
"esgo2dump/internal/opt"
"esgo2dump/internal/util"
"fmt" "fmt"
"net" elastic "github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
"github.com/elastic/go-elasticsearch/v7/esutil"
"github.com/sirupsen/logrus"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"time" "time"
elastic "github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
"github.com/elastic/go-elasticsearch/v7/esutil"
"github.com/loveuer/esgo2dump/internal/interfaces"
"github.com/loveuer/esgo2dump/internal/opt"
"github.com/loveuer/esgo2dump/internal/util"
"github.com/sirupsen/logrus"
) )
func NewClient(url *url.URL, iot interfaces.IO) (interfaces.DumpIO, error) { func NewClient(url *url.URL, qm map[string]any) (interfaces.DumpIO, error) {
var ( var (
address = fmt.Sprintf("%s://%s", url.Scheme, url.Host) err error
urlIndex = strings.TrimPrefix(url.Path, "/") endpoint = fmt.Sprintf("%s://%s", url.Scheme, url.Host)
urlUsername string c *elastic.Client
urlPassword string infoResp *esapi.Response
errCh = make(chan error) index = strings.TrimPrefix(url.Path, "/")
cliCh = make(chan *elastic.Client) username string
password string
) )
if url.User != nil { if url.User != nil {
urlUsername = url.User.Username() username = url.User.Username()
if p, ok := url.User.Password(); ok { if p, ok := url.User.Password(); ok {
urlPassword = p password = p
} }
} }
logrus.Debugf("xes.NewClient: endpoint=%s index=%s (username=%s password=%s)", address, urlIndex, urlUsername, urlPassword) logrus.Debugf("xes.NewClient: endpoint=%s index=%s (username=%s password=%s)", endpoint, index, username, password)
if urlIndex == "" { if index == "" {
return nil, fmt.Errorf("please specify index name: (like => http://127.0.0.1:9200/my_index)") return nil, fmt.Errorf("please specify index name: (like => http://127.0.0.1:9200/my_index)")
} }
ncFunc := func(endpoints []string, username, password, index string) { if c, err = elastic.NewClient(
var ( elastic.Config{
err error Addresses: []string{endpoint},
cli *elastic.Client Username: username,
infoResp *esapi.Response Password: password,
) CACert: nil,
RetryOnStatus: []int{429},
if cli, err = elastic.NewClient( MaxRetries: 3,
elastic.Config{ RetryBackoff: nil,
Addresses: endpoints, Transport: &http.Transport{
Username: username, TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
Password: password,
CACert: nil,
RetryOnStatus: []int{429},
MaxRetries: 3,
RetryBackoff: nil,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DialContext: (&net.Dialer{Timeout: 10 * time.Second}).DialContext,
},
}, },
); err != nil { },
logrus.Debugf("xes.NewClient: elastic new client with endpont=%s err=%v", endpoints, err) ); err != nil {
errCh <- err logrus.Debugf("xes.NewClient: elastic new client with endpont=%s err=%v", endpoint, err)
return return nil, err
}
if infoResp, err = cli.Info(); err != nil {
logrus.Debugf("xes.NewClient: ping err=%v", err)
errCh <- err
return
}
if infoResp.StatusCode != 200 {
err = fmt.Errorf("info xes status=%d", infoResp.StatusCode)
logrus.Debugf("xes.NewClient: status err=%v", err)
errCh <- err
return
}
cliCh <- cli
} }
go ncFunc([]string{address}, urlUsername, urlPassword, urlIndex) if infoResp, err = c.Info(); err != nil {
logrus.Debugf("xes.NewClient: ping err=%v", err)
select { return nil, err
case <-util.Timeout(10).Done():
return nil, fmt.Errorf("dial es=%s err=%v", address, context.DeadlineExceeded)
case c := <-cliCh:
return &client{c: c, index: urlIndex, iot: iot}, nil
case e := <-errCh:
return nil, e
} }
if infoResp.StatusCode != 200 {
return nil, fmt.Errorf("info xes status=%d", infoResp.StatusCode)
}
return &client{c: c, index: index, queryMap: qm}, nil
} }
type client struct { type client struct {
c *elastic.Client c *elastic.Client
iot interfaces.IO
index string index string
from int
scrollId string scrollId string
queryMap map[string]any
} }
func (c *client) checkResponse(r *esapi.Response) error { func (c *client) ReadSetting() (map[string]any, error) {
if r.StatusCode == 200 { r, err := c.c.Indices.GetSettings(
return nil c.c.Indices.GetSettings.WithIndex(c.index),
)
if err != nil {
return nil, err
} }
return fmt.Errorf("status=%d msg=%s", r.StatusCode, r.String()) if r.StatusCode != 200 {
return nil, fmt.Errorf("status=%d, msg=%s", r.StatusCode, r.String())
}
m := make(map[string]any)
decoder := json.NewDecoder(r.Body)
if err = decoder.Decode(&m); err != nil {
return nil, err
}
return m, nil
} }
func (c *client) IOType() interfaces.IO { func (c *client) WriteSetting(m map[string]any) error {
return c.iot //TODO implement me
panic("implement me")
}
func (c *client) IsInput() bool {
//TODO implement me
panic("implement me")
} }
func (c *client) IsFile() bool { func (c *client) IsFile() bool {
@@ -127,15 +121,11 @@ func (c *client) Close() error {
return nil return nil
} }
func (c *client) ResetOffset() { func (c *client) WriteData(docs []*interfaces.ESSource) (int, error) {
c.scrollId = ""
}
func (c *client) WriteData(ctx context.Context, docs []*interfaces.ESSource) (int, error) {
var ( var (
err error err error
indexer esutil.BulkIndexer indexer esutil.BulkIndexer
count int count int
be error
) )
if indexer, err = esutil.NewBulkIndexer(esutil.BulkIndexerConfig{ if indexer, err = esutil.NewBulkIndexer(esutil.BulkIndexerConfig{
Client: c.c, Client: c.c,
@@ -159,32 +149,25 @@ func (c *client) WriteData(ctx context.Context, docs []*interfaces.ESSource) (in
Index: c.index, Index: c.index,
DocumentID: doc.DocId, DocumentID: doc.DocId,
Body: bytes.NewReader(bs), Body: bytes.NewReader(bs),
OnFailure: func(ctx context.Context, item esutil.BulkIndexerItem, item2 esutil.BulkIndexerResponseItem, bulkErr error) {
be = bulkErr
},
}); err != nil { }); err != nil {
return 0, err return 0, err
} }
count++ count++
} }
if err = indexer.Close(util.TimeoutCtx(ctx, opt.Timeout)); err != nil { if err = indexer.Close(util.Timeout(opt.Timeout)); err != nil {
return 0, err return 0, err
} }
if be != nil {
return 0, be
}
stats := indexer.Stats() stats := indexer.Stats()
if stats.NumFailed > 0 { if stats.NumFailed > 0 {
return count, fmt.Errorf("write to xes failed_count=%d bulk_count=%d", stats.NumFailed, count) return count, fmt.Errorf("write to xes failed=%d", stats.NumFailed)
} }
return count, nil return count, nil
} }
func (c *client) ReadData(ctx context.Context, i int, query map[string]any) ([]*interfaces.ESSource, error) { func (c *client) ReadData(i int) ([]*interfaces.ESSource, error) {
var ( var (
err error err error
resp *esapi.Response resp *esapi.Response
@@ -193,15 +176,15 @@ func (c *client) ReadData(ctx context.Context, i int, query map[string]any) ([]*
if c.scrollId == "" { if c.scrollId == "" {
qs := []func(*esapi.SearchRequest){ qs := []func(*esapi.SearchRequest){
c.c.Search.WithContext(util.TimeoutCtx(ctx, opt.Timeout)), c.c.Search.WithContext(util.Timeout(opt.Timeout)),
c.c.Search.WithIndex(c.index), c.c.Search.WithIndex(c.index),
c.c.Search.WithSize(i), c.c.Search.WithSize(i),
c.c.Search.WithFrom(0), c.c.Search.WithFrom(0),
c.c.Search.WithScroll(time.Duration(opt.ScrollDurationSeconds) * time.Second), c.c.Search.WithScroll(time.Duration(opt.ScrollDurationSeconds) * time.Second),
} }
if query != nil && len(query) > 0 { if len(c.queryMap) > 0 {
queryBs, _ := json.Marshal(map[string]any{"query": query}) queryBs, _ := json.Marshal(map[string]any{"query": c.queryMap})
qs = append(qs, c.c.Search.WithBody(bytes.NewReader(queryBs))) qs = append(qs, c.c.Search.WithBody(bytes.NewReader(queryBs)))
} }
@@ -238,7 +221,7 @@ func (c *client) ReadData(ctx context.Context, i int, query map[string]any) ([]*
return result.Hits.Hits, nil return result.Hits.Hits, nil
} }
func (c *client) ReadMapping(ctx context.Context) (map[string]any, error) { func (c *client) ReadMapping() (map[string]any, error) {
r, err := c.c.Indices.GetMapping( r, err := c.c.Indices.GetMapping(
c.c.Indices.GetMapping.WithIndex(c.index), c.c.Indices.GetMapping.WithIndex(c.index),
) )
@@ -258,73 +241,7 @@ func (c *client) ReadMapping(ctx context.Context) (map[string]any, error) {
return m, nil return m, nil
} }
func (c *client) WriteMapping(ctx context.Context, m map[string]any) error { func (c *client) WriteMapping(m map[string]any) error {
var ( //TODO implement me
err error panic("implement me")
bs []byte
result *esapi.Response
)
for idxKey := range m {
if bs, err = json.Marshal(m[idxKey]); err != nil {
return err
}
if result, err = c.c.Indices.Create(
c.index,
c.c.Indices.Create.WithContext(util.TimeoutCtx(ctx, opt.Timeout)),
c.c.Indices.Create.WithBody(bytes.NewReader(bs)),
); err != nil {
return err
}
if err = c.checkResponse(result); err != nil {
return err
}
}
return nil
}
func (c *client) ReadSetting(ctx context.Context) (map[string]any, error) {
r, err := c.c.Indices.GetSettings(
c.c.Indices.GetSettings.WithContext(util.TimeoutCtx(ctx, opt.Timeout)),
c.c.Indices.GetSettings.WithIndex(c.index),
)
if err != nil {
return nil, err
}
if r.StatusCode != 200 {
return nil, fmt.Errorf("status=%d, msg=%s", r.StatusCode, r.String())
}
m := make(map[string]any)
decoder := json.NewDecoder(r.Body)
if err = decoder.Decode(&m); err != nil {
return nil, err
}
return m, nil
}
func (c *client) WriteSetting(ctx context.Context, m map[string]any) error {
var (
err error
bs []byte
result *esapi.Response
)
if bs, err = json.Marshal(m); err != nil {
return err
}
if result, err = c.c.Indices.PutSettings(
bytes.NewReader(bs),
c.c.Indices.PutSettings.WithContext(util.TimeoutCtx(ctx, opt.Timeout)),
); err != nil {
return err
}
return c.checkResponse(result)
} }
+2 -3
View File
@@ -1,10 +1,9 @@
package xes package xes
import ( import (
"testing" "esgo2dump/internal/util"
elastic "github.com/elastic/go-elasticsearch/v7" elastic "github.com/elastic/go-elasticsearch/v7"
"github.com/loveuer/esgo2dump/internal/util" "testing"
) )
func TestGetESMapping(t *testing.T) { func TestGetESMapping(t *testing.T) {
+16 -49
View File
@@ -2,60 +2,28 @@ package xfile
import ( import (
"bufio" "bufio"
"context"
"encoding/json" "encoding/json"
"io" "esgo2dump/internal/interfaces"
"os"
"github.com/loveuer/esgo2dump/internal/interfaces"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"os"
) )
type client struct { type client struct {
f *os.File f *os.File
iot interfaces.IO
scanner *bufio.Scanner scanner *bufio.Scanner
} }
func (c *client) ReadMapping(ctx context.Context) (map[string]any, error) { func (c *client) ReadMapping() (map[string]any, error) {
var ( //TODO implement me
err error panic("implement me")
bs []byte
)
if bs, err = io.ReadAll(c.f); err != nil {
return nil, err
}
m := make(map[string]any)
if err = json.Unmarshal(bs, &m); err != nil {
return nil, err
}
return m, nil
} }
func (c *client) ReadSetting(ctx context.Context) (map[string]any, error) { func (c *client) ReadSetting() (map[string]any, error) {
var ( //TODO implement me
err error panic("implement me")
bs []byte
)
if bs, err = io.ReadAll(c.f); err != nil {
return nil, err
}
m := make(map[string]any)
if err = json.Unmarshal(bs, &m); err != nil {
return nil, err
}
return m, nil
} }
func (c *client) WriteMapping(ctx context.Context, m map[string]any) error { func (c *client) WriteMapping(m map[string]any) error {
bs, err := json.Marshal(m) bs, err := json.Marshal(m)
if err != nil { if err != nil {
return err return err
@@ -66,7 +34,7 @@ func (c *client) WriteMapping(ctx context.Context, m map[string]any) error {
return err return err
} }
func (c *client) WriteSetting(ctx context.Context, m map[string]any) error { func (c *client) WriteSetting(m map[string]any) error {
bs, err := json.Marshal(m) bs, err := json.Marshal(m)
if err != nil { if err != nil {
return err return err
@@ -77,17 +45,16 @@ func (c *client) WriteSetting(ctx context.Context, m map[string]any) error {
return err return err
} }
func (c *client) IOType() interfaces.IO { func (c *client) IsInput() bool {
return c.iot //TODO implement me
panic("implement me")
} }
func (c *client) IsFile() bool { func (c *client) IsFile() bool {
return true return true
} }
func (c *client) ResetOffset() {} func (c *client) WriteData(docs []*interfaces.ESSource) (int, error) {
func (c *client) WriteData(ctx context.Context, docs []*interfaces.ESSource) (int, error) {
var ( var (
err error err error
bs []byte bs []byte
@@ -111,7 +78,7 @@ func (c *client) WriteData(ctx context.Context, docs []*interfaces.ESSource) (in
return count, nil return count, nil
} }
func (c *client) ReadData(ctx context.Context, i int, _ map[string]any) ([]*interfaces.ESSource, error) { func (c *client) ReadData(i int) ([]*interfaces.ESSource, error) {
var ( var (
err error err error
count = 0 count = 0
@@ -148,7 +115,7 @@ func (c *client) Close() error {
} }
func NewClient(file *os.File, ioType interfaces.IO) (interfaces.DumpIO, error) { func NewClient(file *os.File, ioType interfaces.IO) (interfaces.DumpIO, error) {
c := &client{f: file, iot: ioType} c := &client{f: file}
if ioType == interfaces.IOInput { if ioType == interfaces.IOInput {
c.scanner = bufio.NewScanner(c.f) c.scanner = bufio.NewScanner(c.f)
+1 -2
View File
@@ -2,11 +2,10 @@ package main
import ( import (
"context" "context"
"esgo2dump/internal/cmd"
"os/signal" "os/signal"
"syscall" "syscall"
"github.com/loveuer/esgo2dump/internal/cmd"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
-51
View File
@@ -1,51 +0,0 @@
# esgo2dump
# dump elasticsearch with golang
---
- 当前仅支持 elasticsearch 7
---
### install
- with golang >= 1.18
`go install github.com/loveuer/esgo2dump@latest`
- download pre-build release:
[releases](https://github.com/loveuer/esgo2dump/releases)
### usage
`esgo2dump -h`
```bash
esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json
esgo2dump --input=http://127.0.0.1:9200/some_index --output=http://192.168.1.1:9200/some_index --limit=5000
esgo2dump --input=https://username:password@127.0.0.1:9200/some_index --output=./data.json
esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query='{"match": {"name": "some_name"}}'
esgo2dump --input=http://127.0.0.1:9200/some_index --output=./data.json --query_file=my_queries.json
```
- example_queries.json
```json
{"bool":{"should":[{"term":{"user_id":{"value":"123"}}},{"term":{"user_id":{"value":"456"}}}]}}
{"bool":{"should":[{"term":{"user_id":{"value":"abc"}}},{"term":{"user_id":{"value":"def"}}}]}}
{"bool":{"should":[{"term":{"user_id":{"value":"ABC"}}},{"term":{"user_id":{"value":"DEF"}}}]}}
```
### roadmap
- [x] data dump
- [x] mapping dump
- [x] es to file
- [x] es to es
- [x] auto create index with mapping
- [ ] auto create index with mapping,setting
- [ ] support es8