meilisearch/search.go

57 lines
1.2 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"
)
// Search return result from database
2022-10-29 08:33:07 +00:00
func Search(index string, payload SearchPayload, result interface{}) (int64, error) {
response, err := client.Index(index).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{
"index": index,
"payload": payload,
},
})
return 0, errors.New("cannot search data")
}
// return if no result
2022-10-29 08:33:07 +00:00
if len(response.Hits) == 0 {
2022-10-27 03:03:35 +00:00
return 0, nil
}
// map data to response variable
2022-10-29 08:33:07 +00:00
b, _ := json.Marshal(response.Hits)
if err = json.Unmarshal(b, &result); err != nil {
2022-10-27 03:03:35 +00:00
logger.Error("unmarshal result", logger.LogData{
Source: "meilisearch.Search",
Message: err.Error(),
Data: logger.Map{
"index": index,
"payload": payload,
2022-10-29 08:33:07 +00:00
"hits": response.Hits,
2022-10-27 03:03:35 +00:00
},
})
return 0, err
}
// return
2022-10-29 08:33:07 +00:00
return response.EstimatedTotalHits, nil
2022-10-27 03:03:35 +00:00
}