1// Copyright 2013 Matthew Baird 2// Licensed under the Apache License, Version 2.0 (the "License"); 3// you may not use this file except in compliance with the License. 4// You may obtain a copy of the License at 5// http://www.apache.org/licenses/LICENSE-2.0 6// Unless required by applicable law or agreed to in writing, software 7// distributed under the License is distributed on an "AS IS" BASIS, 8// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 9// See the License for the specific language governing permissions and 10// limitations under the License. 11 12package elastigo 13 14import ( 15 "encoding/json" 16 "fmt" 17) 18 19// SortDsl accepts any number of Sort commands 20// 21// Query().Sort( 22// Sort("last_name").Desc(), 23// Sort("age"), 24// ) 25func Sort(field string) *SortDsl { 26 return &SortDsl{Name: field} 27} 28 29func GeoDistanceSort(field interface{}) *SortDsl { 30 return &SortDsl{GeoDistance: field} 31} 32 33type SortBody []interface{} 34type SortDsl struct { 35 Name string 36 IsDesc bool 37 GeoDistance interface{} 38} 39 40func (s *SortDsl) Desc() *SortDsl { 41 s.IsDesc = true 42 return s 43} 44func (s *SortDsl) Asc() *SortDsl { 45 s.IsDesc = false 46 return s 47} 48 49func (s *SortDsl) MarshalJSON() ([]byte, error) { 50 if s.GeoDistance != nil { 51 return json.Marshal(map[string]interface{}{"_geo_distance": s.GeoDistance}) 52 } 53 if s.IsDesc { 54 return json.Marshal(map[string]string{s.Name: "desc"}) 55 } 56 if s.Name == "_score" { 57 return []byte(`"_score"`), nil 58 } 59 return []byte(fmt.Sprintf(`"%s"`, s.Name)), nil // "user" assuming default = asc? 60} 61