2016-11-23 3 views
0

я использую этот репозиторий:Как Deserialize hit.Source в структуры в golang

https://github.com/olivere/elastic

Следующий код является примером elasticsearch запроса в golang:

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 в структуры документа?

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

ответ

1

Ну, вы немаршалинг данные в документе структуры, если вы хотите напечатать его в качестве сырья JSON можно просто Маршал снова, так что только теги, которые вы указали в своей структуре Document, показываются.

Если вы хотите, чтобы вывод будет массив JSON, просто хранить все ваши документы в срез, а затем Marshal всего делу

var documents []Document 
for (...) { 
    (...) 
    documents = append(documents, d) 
} 

rawJsonDocuments, err := json.Marshal(documents) 
fmt.Printf("%v", string(rawJsonDocuments)) 
0

Я нашел следующее решение:

package main 

import (
    "fmt" 
    j "github.com/ricardolonga/jsongo" 
    "gopkg.in/olivere/elastic.v3" 
) 

func main() { 

    term := "villa de cortes" 

    searchJson := j.Object(). 
    Put("size", 10). 
    Put("query", j.Object(). 
     Put("match", j.Object(). 
     Put("_all", j.Object(). 
      Put("query", term). 
      Put("operator", "and")))). 
    Put("sort", j.Array(). 
     Put(j.Object(). 
     Put("colonia", j.Object(). 
      Put("order", "asc"). 
      Put("mode", "avg")))) 

    elasticHost := "http://172.17.0.2:9200" 

    client, err := elastic.NewClient(elastic.SetURL(elasticHost)) 
    if err != nil { 
     panic(err) 
    } 

    searchResult, err := client.Search(). 
     Index("mx"). 
     Type("postal_code"). 
     Source(searchJson). 
     Pretty(true). 
     Do() 
    if err != nil { 
     panic(err) 
    } 

    if searchResult.Hits.TotalHits > 0 { 

    jsonArray := j.Array() 
    for _, hit := range searchResult.Hits.Hits { 
     jsonArray.Put(hit.Source) 
    } 

    fmt.Print(jsonArray.Indent()) 

    } else { 
    fmt.Print("Found no documents\n") 
    } 

} 
+0

может быть иметь лучший способ решить – Sanx

Смежные вопросы