@@ -70,8 +70,19 @@ func (ec *elasticClient) CheckAndCreatePolicy(policyName string, policy *bytes.B
7070}
7171
7272// SetWriteIndexTrue will set the provided index as write index
73- func (ec * elasticClient ) SetWriteIndexTrue (alias string , index string ) error {
74- body := fmt .Sprintf (`{"actions":[{"add":{"index":"%s","alias":"%s","is_write_index":true}}]}` , index , alias )
73+ func (ec * elasticClient ) SetWriteIndexTrue (alias string , providedIndex string ) error {
74+ writeIndexFromCluster , isSet , err := ec .getWriteIndex (alias )
75+ if err != nil {
76+ return fmt .Errorf ("err getting write index from cluster: %v" , err )
77+ }
78+ if isSet {
79+ return nil
80+ }
81+ if writeIndexFromCluster == alias {
82+ writeIndexFromCluster = providedIndex
83+ }
84+
85+ body := fmt .Sprintf (`{"actions":[{"add":{"index":"%s","alias":"%s","is_write_index":true}}]}` , writeIndexFromCluster , alias )
7586 res , err := ec .client .Indices .UpdateAliases (
7687 bytes .NewBufferString (body ),
7788 )
@@ -174,7 +185,7 @@ func (ec *elasticClient) DoQueryRemove(ctx context.Context, index string, body *
174185 log .Warn ("elasticClient.doRefresh" , "cannot do refresh" , err )
175186 }
176187
177- writeIndex , err := ec .getWriteIndex (index )
188+ writeIndex , _ , err := ec .getWriteIndex (index )
178189 if err != nil {
179190 log .Warn ("elasticClient.getWriteIndex" , "cannot do get write index" , err )
180191 return err
@@ -282,12 +293,12 @@ func (ec *elasticClient) createAlias(alias string, index string) error {
282293 return parseResponse (res , nil , elasticDefaultErrorResponseHandler )
283294}
284295
285- func (ec * elasticClient ) getWriteIndex (alias string ) (string , error ) {
296+ func (ec * elasticClient ) getWriteIndex (alias string ) (string , bool , error ) {
286297 res , err := ec .client .Indices .GetAlias (
287298 ec .client .Indices .GetAlias .WithIndex (alias ),
288299 )
289300 if err != nil {
290- return "" , err
301+ return "" , false , err
291302 }
292303
293304 var indexData map [string ]struct {
@@ -297,22 +308,21 @@ func (ec *elasticClient) getWriteIndex(alias string) (string, error) {
297308 }
298309 err = parseResponse (res , & indexData , elasticDefaultErrorResponseHandler )
299310 if err != nil {
300- return "" , err
311+ return "" , false , err
301312 }
302313
303314 for index , details := range indexData {
304- if len (indexData ) == 1 {
305- return index , nil
306- }
307-
308315 for _ , indexAlias := range details .Aliases {
309316 if indexAlias .IsWriteIndex {
310- return index , nil
317+ return index , true , nil
311318 }
312319 }
320+ if len (indexData ) == 1 {
321+ return index , false , nil
322+ }
313323 }
314324
315- return alias , nil
325+ return alias , false , nil
316326}
317327
318328// UpdateByQuery will update all the documents that match the provided query from the provided index
0 commit comments