|
| 1 | +// Copyright © 2018 NAME HERE <EMAIL ADDRESS> |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package cmd |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "encoding/json" |
| 20 | + "fmt" |
| 21 | + "os" |
| 22 | + "strings" |
| 23 | + |
| 24 | + "github.com/ibbd-dev/go-csv" |
| 25 | + "github.com/spf13/cobra" |
| 26 | + "gopkg.in/olivere/elastic.v5" |
| 27 | +) |
| 28 | + |
| 29 | +// exportCmd represents the export command |
| 30 | +var exportCmd = &cobra.Command{ |
| 31 | + Use: "export", |
| 32 | + Short: "export data to csv from es", |
| 33 | + Long: `export data to csv from es", |
| 34 | +`, |
| 35 | + Example: ` |
| 36 | +csv2es export --host=locahost --port=9200 --index=test --csv=source.csv |
| 37 | +`, |
| 38 | + Run: func(cmd *cobra.Command, args []string) { |
| 39 | + // 创建输出文件 |
| 40 | + out, err := os.Create(cParams.CsvFilename) |
| 41 | + if err != nil { |
| 42 | + panic(err) |
| 43 | + } |
| 44 | + defer out.Close() |
| 45 | + writer := goCsv.NewMapWriterSimple(out) |
| 46 | + |
| 47 | + // es |
| 48 | + conn, err := getESConnect() |
| 49 | + ctx := context.Background() |
| 50 | + exists, err := conn.IndexExists(cParams.IndexName).Do(ctx) |
| 51 | + if err != nil { |
| 52 | + panic(fmt.Errorf("check index exists error: %v", err.Error())) |
| 53 | + } |
| 54 | + |
| 55 | + if !exists { |
| 56 | + panic(fmt.Errorf("index %s is not exists", cParams.IndexName)) |
| 57 | + } |
| 58 | + if cParams.Size <= 0 { |
| 59 | + cParams.Size = 1000 |
| 60 | + } |
| 61 | + |
| 62 | + search := conn.Search(cParams.IndexName) |
| 63 | + if len(cParams.QueryField) > 0 { |
| 64 | + var query = elastic.NewTermQuery(cParams.QueryField, cParams.QueryValue) |
| 65 | + search.Query(query) |
| 66 | + } |
| 67 | + |
| 68 | + searchResult, err := search.Size(cParams.Size).Do(ctx) |
| 69 | + if err != nil { |
| 70 | + panic(fmt.Errorf("search error: %v", err.Error())) |
| 71 | + } |
| 72 | + |
| 73 | + var count int |
| 74 | + for i, hit := range searchResult.Hits.Hits { |
| 75 | + var row = make(map[string]interface{}) |
| 76 | + err = json.Unmarshal(*hit.Source, &row) |
| 77 | + if err != nil { |
| 78 | + panic(fmt.Errorf("search %d: json unmarshal error: %v", i, err.Error())) |
| 79 | + } |
| 80 | + if count == 0 { |
| 81 | + // 首行 |
| 82 | + var headers []string |
| 83 | + for k, _ := range row { |
| 84 | + headers = append(headers, k) |
| 85 | + } |
| 86 | + |
| 87 | + writer.SetHeader(headers) |
| 88 | + if err = writer.WriteHeader(); err != nil { |
| 89 | + panic(fmt.Errorf("csv writer header error: %s", err.Error())) |
| 90 | + } |
| 91 | + fmt.Printf("Fieldnames: %s\n", strings.Join(headers, ", ")) |
| 92 | + } |
| 93 | + |
| 94 | + count += 1 |
| 95 | + var strRow = make(map[string]string) |
| 96 | + for k, v := range row { |
| 97 | + if sv, err := json.Marshal(v); err != nil { |
| 98 | + panic(fmt.Errorf("csv writer header error: %s", err.Error())) |
| 99 | + } else { |
| 100 | + strRow[k] = string(sv) |
| 101 | + strRow[k] = strings.Trim(strRow[k], "\"") |
| 102 | + } |
| 103 | + } |
| 104 | + writer.WriteRow(strRow) |
| 105 | + } |
| 106 | + writer.Flush() |
| 107 | + |
| 108 | + fmt.Printf("Total %d\n", count) |
| 109 | + }, |
| 110 | +} |
| 111 | + |
| 112 | +func init() { |
| 113 | + rootCmd.AddCommand(exportCmd) |
| 114 | + |
| 115 | + // Here you will define your flags and configuration settings. |
| 116 | + |
| 117 | + // Cobra supports Persistent Flags which will work for this command |
| 118 | + // and all subcommands, e.g.: |
| 119 | + // exportCmd.PersistentFlags().String("foo", "", "A help for foo") |
| 120 | + exportCmd.PersistentFlags().StringVar(&cParams.QueryField, "query-field", "", "过滤字段") |
| 121 | + exportCmd.PersistentFlags().StringVar(&cParams.QueryValue, "query-value", "", "过滤字段对应的值") |
| 122 | + |
| 123 | + // Cobra supports local flags which will only run when this command |
| 124 | + // is called directly, e.g.: |
| 125 | + // exportCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") |
| 126 | +} |
0 commit comments