exists.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2012-2015 Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic
  5. import (
  6. "fmt"
  7. "github.com/olivere/elastic/uritemplates"
  8. )
  9. type ExistsService struct {
  10. client *Client
  11. index string
  12. _type string
  13. id string
  14. }
  15. func NewExistsService(client *Client) *ExistsService {
  16. builder := &ExistsService{
  17. client: client,
  18. }
  19. return builder
  20. }
  21. func (s *ExistsService) String() string {
  22. return fmt.Sprintf("exists([%v][%v][%v])",
  23. s.index,
  24. s._type,
  25. s.id)
  26. }
  27. func (s *ExistsService) Index(index string) *ExistsService {
  28. s.index = index
  29. return s
  30. }
  31. func (s *ExistsService) Type(_type string) *ExistsService {
  32. s._type = _type
  33. return s
  34. }
  35. func (s *ExistsService) Id(id string) *ExistsService {
  36. s.id = id
  37. return s
  38. }
  39. func (s *ExistsService) Do() (bool, error) {
  40. // Build url
  41. path, err := uritemplates.Expand("/{index}/{type}/{id}", map[string]string{
  42. "index": s.index,
  43. "type": s._type,
  44. "id": s.id,
  45. })
  46. if err != nil {
  47. return false, err
  48. }
  49. // Get response
  50. res, err := s.client.PerformRequest("HEAD", path, nil, nil)
  51. if err != nil {
  52. return false, err
  53. }
  54. if res.StatusCode == 200 {
  55. return true, nil
  56. } else if res.StatusCode == 404 {
  57. return false, nil
  58. }
  59. return false, fmt.Errorf("elastic: got HTTP code %d when it should have been either 200 or 404", res.StatusCode)
  60. }