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	"strings"
12
13	"gopkg.in/olivere/elastic.v2/uritemplates"
14)
15
16type RefreshService struct {
17	client  *Client
18	indices []string
19	force   *bool
20	pretty  bool
21}
22
23func NewRefreshService(client *Client) *RefreshService {
24	builder := &RefreshService{
25		client:  client,
26		indices: make([]string, 0),
27	}
28	return builder
29}
30
31func (s *RefreshService) Index(index string) *RefreshService {
32	s.indices = append(s.indices, index)
33	return s
34}
35
36func (s *RefreshService) Indices(indices ...string) *RefreshService {
37	s.indices = append(s.indices, indices...)
38	return s
39}
40
41func (s *RefreshService) Force(force bool) *RefreshService {
42	s.force = &force
43	return s
44}
45
46func (s *RefreshService) Pretty(pretty bool) *RefreshService {
47	s.pretty = pretty
48	return s
49}
50
51func (s *RefreshService) Do() (*RefreshResult, error) {
52	// Build url
53	path := "/"
54
55	// Indices part
56	indexPart := make([]string, 0)
57	for _, index := range s.indices {
58		index, err := uritemplates.Expand("{index}", map[string]string{
59			"index": index,
60		})
61		if err != nil {
62			return nil, err
63		}
64		indexPart = append(indexPart, index)
65	}
66	if len(indexPart) > 0 {
67		path += strings.Join(indexPart, ",")
68	}
69
70	path += "/_refresh"
71
72	// Parameters
73	params := make(url.Values)
74	if s.force != nil {
75		params.Set("force", fmt.Sprintf("%v", *s.force))
76	}
77	if s.pretty {
78		params.Set("pretty", fmt.Sprintf("%v", s.pretty))
79	}
80
81	// Get response
82	res, err := s.client.PerformRequest("POST", path, params, nil)
83	if err != nil {
84		return nil, err
85	}
86
87	// Return result
88	ret := new(RefreshResult)
89	if err := json.Unmarshal(res.Body, ret); err != nil {
90		return nil, err
91	}
92	return ret, nil
93}
94
95// -- Result of a refresh request.
96
97type RefreshResult struct {
98	Shards shardsInfo `json:"_shards,omitempty"`
99}
100