SHARE
TWEET

golang elasticsearch individual insert

diegogaulke Feb 1st, 2019 (edited) 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "context"
  5.     "encoding/json"
  6.     "fmt"
  7.     "io/ioutil"
  8.     "log"
  9.     "os"
  10.  
  11.     "github.com/olivere/elastic"
  12. )
  13.  
  14. func main() {
  15.     // check if all elasticsearch env vars were exported
  16.     url := os.Getenv("ELASTIC_URL")
  17.     index := os.Getenv("ELASTIC_INDEX")
  18.     _type := os.Getenv("ELASTIC_TYPE")
  19.  
  20.     if url == "" || index == "" || _type == "" {
  21.         log.Fatal("Please set all elastic search env vars.")
  22.     }
  23.  
  24.     // Open our jsonFile
  25.     jsonFile, _ := os.Open("states.json")
  26.     defer jsonFile.Close()
  27.  
  28.     byteValue, _ := ioutil.ReadAll(jsonFile)
  29.  
  30.     var states States
  31.  
  32.     json.Unmarshal(byteValue, &states)
  33.  
  34.     //  get elasticsearch client
  35.     fmt.Println("Get elasticsearch client...")
  36.     client, _ := elastic.NewClient()
  37.     ctx := context.Background()
  38.  
  39.     fmt.Println("Start insert into elasticsearch...")
  40.  
  41.     for i := 0; i < len(states.States); i++ {
  42.         _, _ = client.Index().Index(index).Type(_type).Id(states.States[i].State).BodyJson(states.States[i]).Do(ctx)
  43.     }
  44.  
  45.     fmt.Println("Done...")
  46. }
  47.  
  48. // State reference of a single state
  49. type State struct {
  50.     State      string `json:"state"`
  51.     Population uint32 `json:"population"`
  52. }
  53.  
  54. // States list of states
  55. type States struct {
  56.     States []State `json:"states"`
  57. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top