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
| package main
import ( "context" "fmt"
"github.com/olivere/elastic/v7" )
var client *elastic.Client
func init() { var err error client, err = elastic.NewClient(elastic.SetURL("http://xmge.top:9200/"),elastic.SetSniff(false)) if err != nil { panic(err) } fmt.Println("connect to es success") }
type Person struct { Id int `json:"id"` Name string `json:"name"` Age int `json:"age"` Married bool `json:"married"` CompanyId int `json:"company_id"` }
type Company struct { Id int `json:"id"` Name string `json:"name"` Location string `json:"location"` }
func main() { persons := []Person{ {1, "小明", 30, true,1}, {2, "小白", 30, true,1}, {3, "小黑", 28, true,2}, {4, "小红", 27, true,3}, {5, "小蓝", 26, true,3}, } insertPersons("users",persons...)
companys := []Company{ {1, "A公司", "西二旗"}, {2, "B公司", "上地"}, {3, "C公司", "望京"}, } insertCompany("company",companys...) }
func insertPersons(index string,items ...Person) { for _, item := range items { put1,err :=client.Index().Index(index).BodyJson(item).Do(context.Background()) if err != nil { panic(err) } fmt.Printf("Indexed %s %s to index %s, type %s\n", index,put1.Id, put1.Index, put1.Type) } }
func insertCompany(index string,items ...Company) { for _, item := range items { put1,err :=client.Index().Index(index).BodyJson(item).Do(context.Background()) if err != nil { panic(err) } fmt.Printf("Indexed %s %s to index %s, type %s\n", index,put1.Id, put1.Index, put1.Type) } }
|