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
5package elastic
6
7import (
8	"encoding/json"
9	"fmt"
10	"net/url"
11
12	"gopkg.in/olivere/elastic.v2/uritemplates"
13)
14
15type DeleteService struct {
16	client  *Client
17	index   string
18	_type   string
19	id      string
20	routing string
21	refresh *bool
22	version *int
23	pretty  bool
24}
25
26func NewDeleteService(client *Client) *DeleteService {
27	builder := &DeleteService{
28		client: client,
29	}
30	return builder
31}
32
33func (s *DeleteService) Index(index string) *DeleteService {
34	s.index = index
35	return s
36}
37
38func (s *DeleteService) Type(_type string) *DeleteService {
39	s._type = _type
40	return s
41}
42
43func (s *DeleteService) Id(id string) *DeleteService {
44	s.id = id
45	return s
46}
47
48func (s *DeleteService) Parent(parent string) *DeleteService {
49	if s.routing == "" {
50		s.routing = parent
51	}
52	return s
53}
54
55func (s *DeleteService) Refresh(refresh bool) *DeleteService {
56	s.refresh = &refresh
57	return s
58}
59
60func (s *DeleteService) Version(version int) *DeleteService {
61	s.version = &version
62	return s
63}
64
65func (s *DeleteService) Pretty(pretty bool) *DeleteService {
66	s.pretty = pretty
67	return s
68}
69
70// Do deletes the document. It fails if any of index, type, and identifier
71// are missing.
72func (s *DeleteService) Do() (*DeleteResult, error) {
73	if s.index == "" {
74		return nil, ErrMissingIndex
75	}
76	if s._type == "" {
77		return nil, ErrMissingType
78	}
79	if s.id == "" {
80		return nil, ErrMissingId
81	}
82
83	// Build url
84	path, err := uritemplates.Expand("/{index}/{type}/{id}", map[string]string{
85		"index": s.index,
86		"type":  s._type,
87		"id":    s.id,
88	})
89	if err != nil {
90		return nil, err
91	}
92
93	// Parameters
94	params := make(url.Values)
95	if s.refresh != nil {
96		params.Set("refresh", fmt.Sprintf("%v", *s.refresh))
97	}
98	if s.version != nil {
99		params.Set("version", fmt.Sprintf("%d", *s.version))
100	}
101	if s.routing != "" {
102		params.Set("routing", fmt.Sprintf("%s", s.routing))
103	}
104	if s.pretty {
105		params.Set("pretty", fmt.Sprintf("%v", s.pretty))
106	}
107
108	// Get response
109	res, err := s.client.PerformRequest("DELETE", path, params, nil)
110	if err != nil {
111		return nil, err
112	}
113
114	// Return response
115	ret := new(DeleteResult)
116	if err := json.Unmarshal(res.Body, ret); err != nil {
117		return nil, err
118	}
119	return ret, nil
120}
121
122// -- Result of a delete request.
123
124type DeleteResult struct {
125	Found   bool   `json:"found"`
126	Index   string `json:"_index"`
127	Type    string `json:"_type"`
128	Id      string `json:"_id"`
129	Version int64  `json:"_version"`
130}
131