logService.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package logapi
  2. import (
  3. "context"
  4. "encoding/json"
  5. "github.com/olivere/elastic"
  6. "iot_manager_service/util/es"
  7. )
  8. type logService struct {
  9. }
  10. var LogService logService
  11. func (l logService) search(indexName string,
  12. page, size int,
  13. query *elastic.BoolQuery) (*res, error) {
  14. result, err := es.Client.Search(indexName).
  15. Query(query).
  16. Size(size).
  17. From((page-1)*size).
  18. Sort("t", false).
  19. Do(context.Background())
  20. //查询错误
  21. if err != nil {
  22. return nil, err
  23. }
  24. //处理结果
  25. var logVOS []logVO
  26. var a logVO
  27. var total int64
  28. if total = result.Hits.TotalHits; total > 0 {
  29. // Iterate through results
  30. for _, hit := range result.Hits.Hits {
  31. // hit.Index contains the name of the index
  32. // Deserialize hit.Source into a Tweet (could also be just a map[string]interface{}).
  33. json.Unmarshal(*hit.Source, &a)
  34. a.Id = hit.Id
  35. logVOS = append(logVOS, a)
  36. }
  37. res := &res{
  38. Current: page,
  39. Size: size,
  40. Pages: int(total)/size + 1,
  41. Total: total,
  42. Records: logVOS,
  43. }
  44. return res, nil
  45. } else {
  46. // No hits
  47. return nil, nil
  48. }
  49. }