
func BatchInsert(index string, Do cment ...interface{}) { bulk := esClient.Bulk() for _,doc:=range docment { insertDoc:=elastic.NewBulkIndexRequest().Index(index).Doc(doc) bulk = bulk.Add(insertDoc) } _, err := bulk.Do(context.Background()) //beelog.Error(response.Errors) if err != nil { beelog.Error("Batch Insert ES ERROR:",err) } }
使用以上代码做数据插入。程序显示没有错误。但是ES中没有数据。
原因分析
1、参数列表,因为传入参数的数据类型是interface{}类型,所以当擦换入的数据是Array类型时,参数列表就是Array。比如,传入的为[]string,那么接收时就等价于[][]string。
所以参数 docment为二维数组。doc为数组。类型为[…..]。2、插入格式,首先我们看下内部代码。此代码为数据的转换, json 转码后数据为{[……]}。由于没有key值,所以无法插入。正确格式应该是{“data”:[……]}
if r.doc != nil { switch t := r.doc.(type) { default: body, err := json.Marshal(r.doc) if err != nil { return nil, err } lines[1] = string(body) case json.RawMessage: lines[1] = string(t) case *json.RawMessage: lines[1] = string(*t) case string: lines[1] = t case *string: lines[1] = *t } } else { lines[1] = "{}" }
代码修改
func BatchInsert(index string,docment []interface{}) { beelog.Error(docment) bulk := esClient.Bulk() for _,doc:=range docment { insertDoc:=elastic.NewBulkIndexRequest().Index(index).Doc(doc) bulk = bulk.Add(insertDoc) } _, err := bulk.Do(context.Background()) //beelog.Error(response.Errors) if err !=nil{ beelog.Error("Batch Insert ES ERROR:",err) } }