我一直在使用這個庫:如何反序列化hit.Source成一個struct在golang
https://github.com/olivere/elastic
下面的代碼是在golang elasticsearch查詢的例子:
searchResult, err := client.Search().
Index("mx").
Type("postal_code").
Source(searchJson).
Pretty(true).
Do()
if err != nil {
panic(err)
}
if searchResult.Hits.TotalHits > 0 {
for _, hit := range searchResult.Hits.Hits {
var d Document
err := json.Unmarshal(*hit.Source, &d)
if err != nil {
// Deserialization failed
}
fmt.Printf("Document by %s: %s\n", d.Colonia, d.Ciudad)
}
} else {
fmt.Print("Found no documents\n")
}
這工作正常,出來是這樣的:
Document by Villa de Cortes: Distrito Federal
Document by Villa de Cortes: Sinaloa
Document by Villa de Cortes: Sinaloa
但我需要出像json陣列,這樣的事情:
[
{
"cp": "03530",
"colonia": "Villa de Cortes",
"ciudad": "Distrito Federal",
"delegacion": "Benito Juarez",
"location": {
"lat": "19.3487",
"lon": "-99.166"
}
},
{
"cp": "81270",
"colonia": "Villa de Cortes",
"ciudad": "Sinaloa",
"delegacion": "Ahome",
"location": {
"lat": "25.1584",
"lon": "-107.7063"
}
},
{
"cp": "80140",
"colonia": "Villa de Cortes",
"ciudad": "Sinaloa",
"delegacion": "Culiacan",
"location": {
"lat": "25.0239",
"lon": "-108.032"
}
}
]
我該如何反序列化hit.Source到一個Document結構?
type Document struct {
Ciudad string `json:"ciudad"`
Colonia string `json:"colonia"`
Cp string `json:"cp"`
Delegacion string `json:"delegacion"`
Location struct {
Lat string `json:"lat"`
Lon string `json:"lon"`
} `json:"location"`
}
下面是腳本的完整源代碼:
https://gist.github.com/hectorgool/67730c8a72f2d34b09e5a8888987ea0c
可能有更好的解決方法 – Sanx