-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathcustom_field_sort.go
More file actions
70 lines (61 loc) · 1.67 KB
/
custom_field_sort.go
File metadata and controls
70 lines (61 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package sort
import (
"errors"
"fmt"
"sort"
"strings"
"time"
"github.com/alibaba/pairec/v2/log"
"github.com/alibaba/pairec/v2/module"
"github.com/alibaba/pairec/v2/recconf"
)
type CustomFieldSort struct {
sortByField string
sortOrder string // "asc" 表示升序,"desc" 表示降序
name string
}
func NewCustomFieldSort(config recconf.SortConfig) *CustomFieldSort {
if config.SortByField == "" {
log.Error(fmt.Sprintf("sort by field is not configured for sort %s", config.Name))
config.SortByField = "current_score"
}
// 默认降序
sortOrder := strings.ToLower(config.SortOrder)
if sortOrder != "asc" && sortOrder != "desc" {
sortOrder = "desc"
}
return &CustomFieldSort{
sortByField: config.SortByField,
sortOrder: sortOrder,
name: config.Name,
}
}
func (s *CustomFieldSort) Sort(sortData *SortData) error {
start := time.Now()
items, ok := sortData.Data.([]*module.Item)
if !ok {
return errors.New("sort data type error")
}
ctx := sortData.Context
sortByField := s.sortByField
isAsc := s.sortOrder == "asc"
sort.Slice(items, func(i, j int) bool {
iScore, err1 := items[i].FloatExprData(sortByField)
if err1 != nil {
iScore = items[i].Score
ctx.LogWarning(fmt.Sprintf("get sort field %s from item %s failed", sortByField, items[i].Id))
}
jScore, err2 := items[j].FloatExprData(sortByField)
if err2 != nil {
jScore = items[j].Score
ctx.LogWarning(fmt.Sprintf("get sort field %s from item %s failed", sortByField, items[j].Id))
}
if isAsc {
return iScore < jScore
}
return iScore > jScore
})
sortData.Data = items
sortInfoLogWithName(sortData, "CustomFieldSort", s.name, len(items), start)
return nil
}