我有以下代码向Elasticsearch发出请求:
// Prepare request
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
req, err := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", ES_AUTH)
// Make request
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
d := json.NewDecoder(resp.Body)
d.UseNumber()
var x interface{}
if err = d.Decode(&x); err != nil {
log.Fatal(err)
}
fmt.Printf("decoded to %#v\n", x)
输出是这样的:
decoded to map[string]interface {}{"took":"2", "timed_out":false, "_shards":map[string]interface {}{"total":"1", "successful":"1", "failed":"0"}, "hits":map[string]interface {}{"total":"15", "max_score":"1.0", "hits":[]interface {}{map[string]interface {}{"_index":"reports2", "_type":"insiders", "_id":"cbaf7513-0046-4929-a740-afe13d6616b4", "_score":"1.0", "_routing":"524364278561685819", "_source":map[string]interface {}{"insider_mean":"420.7546961325966", "friend_total":"3.7859686E7", "sum_of_followers":"3.531951269E10", "follower_total":"50000.0"}}}}}
我正在尝试使用d.UseNumber()
来尽可能地使输出具有整数,而不是使用浮点数来表示所有内容。我希望"friend_total"
,"sum_of_followers"
和"follower_total"
具有整数样式的值。
如果我向邮递员提出相同的请求,您可以看到这些值应该是整数:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"failed": 0
},
"hits": {
"total": 15,
"max_score": 1,
"hits": [
{
"_index": "reports2",
"_type": "insiders",
"_id": "cbaf7513-0046-4929-a740-afe13d6616b4",
"_score": 1,
"_routing": "524364278561685819",
"_source": {
"insider_mean": 420.7546961325966,
"sum_of_followers": 35319512690,
"follower_total": 50000,
"friend_total": 37859686
}
}
]
}
}
我无法复制this Go Playground中的错误,所以我认为错误可能是因为请求本身,而不是解码。
编辑:
我发现做一个curl请求会返回有效负载,所以现在我确定解码不是问题。
curl localhost:9200/524364278561685819/insiders/_search\?size\=1
{"took":2,"timed_out":false,"_shards":{"total":1,"successful":1,"failed":0},"hits":{"total":15,"max_score":1.0,"hits":[{"_index":"reports2","_type":"insiders","_id":"cbaf7513-0046-4929-a740-afe13d6616b4","_score":1.0,"_routing":"524364278561685819","_source":{"insider_mean":420.7546961325966,"sum_of_followers":3.531951269E10,"follower_total":50000.0,"friend_total":3.7859686E7}}]}}
答案 0 :(得分:0)
正如卷曲输出所示,Elasticsearch实际上是以浮点格式给出结果。看起来Postman和jq
为您进行转换,所以我现在的解决方案是只调用jq
:
// Make request
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Use jq to convert the floating point stuff to Longs / Ints
cmd := exec.Command("jq", ".")
cmd.Stdin = resp.Body
var out bytes.Buffer
cmd.Stdout = &out
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
// Decode the output from jq
d := json.NewDecoder(bytes.NewReader(out.Bytes())
d.UseNumber()
var x interface{}
if err = d.Decode(&x); err != nil {
log.Fatal(err)
}
fmt.Printf("decoded to %#v\n", x)
澄清Postman / curl:
(他们)只是为浮动使用不同的格式。没有 比如JSON中的整数,所以35319512690只是一个浮点数 没有小数点,相当于35319512690.0和 3.531951269E10 - JimB