这里以插入更新ES返回的json数据为例:
{
"_index":"zhenai",
"_type":"users",
"_id":"0",
"_version":28,
"result":"updated",
"forced_refresh":true,
"_shards":{"total":2,"successful":1,"failed":0},
"_seq_no":172,
"_primary_term":1
}
json数据处理方法一
- 我们可以直接将json数据映射到预定义好的结构体中,但是必须要确保json的字段和结构体必须要一致。
json数据处理方式二
- 如果JSON数据的定义过于复杂化,可以将JSON数据映射到一个map中,这样处理更加灵活。
以下为ES操作的一个简单code 包含了两种处理方式
package persist
import (
"bufio"
"context"
"encoding/json"
"fmt"
"github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v7/esapi"
"io/ioutil"
"learn16/model"
"reflect"
"strconv"
"strings"
)
type shard struct {
Total int `json:"total"`
Successful int `json:"successful"`
Failed int `json:"failed"`
}
type result struct {
Index string `json:"_index"`
Type string `json:"_type"`
Id string `json:"_id"`
Version int `json:"_version"`
Result string `json:"result"`
ForcedRefresh bool `json:"forced_refresh"`
Shards shard `json:"_shards"`
SeqNo int `json:"_seq_no"`
PrimaryTerm int `json:"_primary_term"`
}
func save(i int, item interface{}) (id string, err error) {
//type assertion
user := item.(model.User)
client, err := elasticsearch.NewDefaultClient()
if err != nil {
return "", err
}
//build the request body
var b strings.Builder
t := reflect.TypeOf(user)
v := reflect.ValueOf(user)
b.WriteString(`{`)
//遍历user结构体
for j := 0; j < t.NumField(); j++ {
var stringVal string
if val, ok := v.Field(j).Interface().(int); ok {
stringVal = strconv.Itoa(val)
}else {
stringVal = v.Field(j).Interface().(string)
}
//拼接json
b.WriteString(`"`)
b.WriteString(t.Field(j).Name)
b.WriteString(`": "`)
b.WriteString(stringVal)
if j == t.NumField()-1 {
b.WriteString(`"`)
}else {
b.WriteString(`",`)
}
}
b.WriteString(`}`)
//set up the request object
req := esapi.IndexRequest{
Index: "zhenai",
DocumentType: "users",
DocumentID: strconv.Itoa(i),
Body: strings.NewReader(b.String()),
Refresh: "true",
}
//perform the request with the client
res, err := req.Do(context.Background(), client)
if err != nil {
return "", err
}
defer res.Body.Close()
//打印字符串结果
fmt.Println(res.String())
//采用bufio读取返回数据为byte切片
bufReader := bufio.NewReader(res.Body)
content, err := ioutil.ReadAll(bufReader)
if err != nil {
return "", err
}
return handleJsonTwo(content),nil
}
func handleJsonOne(content []byte) string {
//定义一个result类型变量 json处理方法一
var data result
json.Unmarshal(content, &data)
//取得返回的id
return data.Id
}
func handleJsonTwo(content []byte) string {
//创建一个map json处理方法二
var jsonObj map[string]interface{}
//将byte切片映射到指定map上
json.Unmarshal(content, &jsonObj)
//取得返回的id
return jsonObj["_id"].(string)
}
package persist
import (
"fmt"
"learn16/model"
"testing"
)
func TestSave(t *testing.T) {
userData := []model.User{
{Name:"xxxx", Sex:"男", Age:22, MaritalStatus:"注孤生", Address:"asdasd", Height:170, Education: "大学", Wages: "5000", DetailUrl:"www.baidu.com"},
{Name:"arvin", Sex:"男", Age:18, MaritalStatus:"已婚", Address:"asdasd", Height:170, Education: "大学", Wages: "5000", DetailUrl:"www.baidu.com"},
}
for i, user := range userData {
id, err := save(i, user)
if err != nil {
t.Errorf("%s",err)
}
fmt.Println(id)
}
}