Advertisement
SeverinDK

Untitled

Nov 28th, 2019
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var waitGroup sync.WaitGroup
  2.  
  3. // CitySearchByName returns autocomplete suggestions for cities
  4. func CitySearchByName(es *elasticsearch.Client, name string, location locationModel.Location, unit string) ([]*City, error) {
  5.     q, err := GenerateAutocompleteQuery(name, location, unit)
  6.     if err != nil {
  7.         return nil, err
  8.     }
  9.  
  10.     elasticsearchResult, err := esService.Search(es, q)
  11.     if err != nil {
  12.         return nil, err
  13.     }
  14.  
  15.     resultLength := len(elasticsearchResult.Hits)
  16.     c := make(chan *City, resultLength)
  17.  
  18.     waitGroup.Add(resultLength)
  19.  
  20.     go mapElasticsearchResultToCities(c, elasticsearchResult, unit)
  21.  
  22.     cities := make([]*City, 0)
  23.     for elem := range c {
  24.         cities = append(cities, elem)
  25.     }
  26.     waitGroup.Wait()
  27.  
  28.     return cities, nil
  29. }
  30.  
  31. func mapElasticsearchResultToCities(c chan *City, elasticsearchResult *esService.ElasticsearchResult, unit string) {
  32.     for _, hit := range elasticsearchResult.Hits {
  33.         source := hit.Source
  34.         fields := hit.Fields
  35.         highlight := hit.Highlight
  36.  
  37.         city, err := mapElasticsearchHitToCity(source, fields, highlight, unit)
  38.  
  39.         if err != nil {
  40.             // Error handling...
  41.         }
  42.  
  43.         c <- city
  44.         waitGroup.Done()
  45.     }
  46.  
  47.     close(c)
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement