meilisearch/search.go

56 lines
1.1 KiB
Go
Raw Normal View History

2022-10-27 03:03:35 +00:00
package meilisearch
import (
"encoding/json"
"errors"
"git.selly.red/Selly-Modules/logger"
ms "github.com/meilisearch/meilisearch-go"
)
2022-11-14 03:11:11 +00:00
func (i Index) Search(payload SearchPayload, response interface{}) (int64, error) {
result, err := getIndex(i.Name).Search(payload.Query, &ms.SearchRequest{
2022-10-27 03:03:35 +00:00
Offset: payload.Pagination.Offset,
Limit: payload.Pagination.Limit,
Filter: payload.Filter,
Sort: payload.Sort,
})
if err != nil {
logger.Error("search", logger.LogData{
Source: "meilisearch.Search",
Message: err.Error(),
Data: logger.Map{
2022-11-14 03:11:11 +00:00
"index": i.Name,
2022-10-27 03:03:35 +00:00
"payload": payload,
},
})
return 0, errors.New("cannot search data")
}
// return if no result
if len(result.Hits) == 0 {
return 0, nil
}
// map data to response variable
b, _ := json.Marshal(result.Hits)
if err = json.Unmarshal(b, &response); err != nil {
logger.Error("unmarshal result", logger.LogData{
Source: "meilisearch.Search",
Message: err.Error(),
Data: logger.Map{
2022-11-14 03:11:11 +00:00
"index": i.Name,
2022-10-27 03:03:35 +00:00
"payload": payload,
"hits": result.Hits,
},
})
return 0, err
}
// return
return result.EstimatedTotalHits, nil
}