Rework search to return a list

Like a proper search would!"
This commit is contained in:
2024-08-13 17:41:01 +02:00
parent a6626761e7
commit 8fd8d53cc3
6 changed files with 61 additions and 32 deletions

View File

@@ -19,6 +19,10 @@ type (
Per100 float32 `json:"per100"`
Energy float32 `json:"energy"`
}
FoodSearch struct {
Food
Score int64 `json:"score"`
}
AggregatedFood struct {
Period string `json:"period"`
Amount float32 `json:"amount"`
@@ -56,27 +60,44 @@ func (s *FoodService) GetRecent() ([]Food, error) {
return res, nil
}
func (s *FoodService) GetLastPer100(name string) (Food, error) {
res := Food{}
func (s *FoodService) GetLastPer100(name string) ([]FoodSearch, error) {
res := []FoodSearch{}
if s.db == nil || !s.db.Ready {
return res, fmt.Errorf("cannot get last per100, db is nil or is not ready")
}
row := s.db.readConn.QueryRow(fmt.Sprintf(`
query := fmt.Sprintf(`
with search_results as (
select word, rank
from foodfix
where word MATCH ?
limit 1
select word, score, f.rowid, f.*
from foodfix
inner join food f on f.food == word
where word MATCH ?
)
select %s
from search_results s
inner join food f on s.word = f.food
order by f.date desc;
`, foodColumns), name)
err := row.Scan(&res.Rowid, &res.Date, &res.Food, &res.Descripton, &res.Amount, &res.Per100, &res.Energy)
select %s, score
from search_results
group by food
order by score asc, date desc
limit %d
`, foodColumns, Settings.SearchLimit)
// log.Printf("%#v", query)
rows, err := s.db.readConn.Query(query, name)
if err != nil {
return res, fmt.Errorf("error scanning row: %v", err)
log.Printf("error getting last per100: %v", err)
return res, err
}
for rows.Next() {
var f FoodSearch
err := rows.Scan(&f.Rowid, &f.Date, &f.Food.Food, &f.Descripton, &f.Amount, &f.Per100, &f.Energy, &f.Score)
if err != nil {
log.Printf("error scanning row: %v", err)
continue
}
res = append(res, f)
}
if len(res) == 0 {
return nil, fmt.Errorf("no results found for %s", name)
}
return res, nil