package main import ( "bytes" "context" "encoding/json" "fmt" "github.com/elastic/go-elasticsearch/v7" "time" ) //ES insert data demo var cli *elasticsearch.Client type Student struct { Name string `json:"name"` Age int `json:"age"` Married bool `json:"married"` } func main() { cli, _ = initEsConnect() //创建索引 err := createIndices("student", time.Second) if err != nil { return } doc := Student{ Name: "wangao", Age: 18, Married: false, } err = InsertDocument("student", doc) if err != nil { fmt.Println(err) return } } func initEsConnect() (cli *elasticsearch.Client, err error) { //1.初始化一个elasticsearch客户端进行链接 cfg := elasticsearch.Config{ Addresses: []string{"https://es-o3log3sa.public.tencentelasticsearch.com:9200"}, Username: "elastic", Password: "wangao1996!", } cli, err = elasticsearch.NewClient(cfg) if err != nil { panic(err) } fmt.Println("connect to es success!") //链接成功 return cli, nil } func createIndices(indices string, timeout time.Duration) error { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() select { case <-ctx.Done(): err := ctx.Err() fmt.Println("create index timeout ") return err default: withContext := cli.Indices.Create.WithContext(ctx) resp, err := cli.Indices.Create(indices, withContext) if err != nil { fmt.Printf("create index failed, err:%v\n", err) return err } if resp.StatusCode != 200 { fmt.Printf("create index error: %s\n", resp.Status()) return err } fmt.Println("create index success") } return nil } func InsertDocument(indexName string, doc Student) error { // 将结构体转换为 JSON 的字节切片 marshal, err := json.Marshal(doc) if err != nil { fmt.Println(err) return err } //// 反射获取id //idFiled := reflect.ValueOf(doc).FieldByName("Id") //if !idFiled.IsValid() { // return fmt.Errorf("invalid id field") //} //kind := idFiled.Kind() //if kind != reflect.String { // return fmt.Errorf("invalid id is not string type") //} response, err := cli.Index( indexName, // 输入流 bytes.NewReader(marshal), // 上下文 cli.Index.WithContext(context.Background()), // 自定义Id //cli.Index.WithDocumentID(idFiled.String()), ) if err != nil { return fmt.Errorf("insert document error: %s", err) } if response.StatusCode != 201 { return fmt.Errorf("insert document error: %s", response.Status()) } fmt.Printf("insert document: %#v\n", doc) return nil }