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
func Search(index string, payload SearchPayload, response interface{}) (int64, error) {
result, err := client.Index(index).Search(payload.Query, &ms.SearchRequest{
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
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{
"index": index,
"payload": payload,
"hits": result.Hits,
},
})
return 0, err
}
// return
return result.EstimatedTotalHits, nil
}