Rename and Deleting Elasticsearch Indexes

2019-01-28 09:30发布

I'm using C# .NET application with NEST to create an index.

I've created an elasticsearch index that customers can query called index_1. I then build another version of the index using a different instance of the application and call it index_1_temp.

What is the safest way for me to rename index_1_temp to index_1 then delete the original index_1?

I know ES has aliases but I'm not sure how to use them for this task

EDIT: The original index does not have an Alias associated with it.

1条回答
啃猪蹄的小仙女
2楼-- · 2019-01-28 09:35

I would recommend always using aliases in scenarios where you may create incrementally differing versions of an index, as may be the case when refining the model of signals within your search strategy.

You can add an alias at the point of creating an index

var client = new ElasticClient(connectionSettings);

var indices = new[] { "index-v1", "index-v2" };
var alias = "index-alias";

// delete index-v1 and index-v2 if they exist, to 
// allow this example to be repeatable
foreach (var index in indices)
{
    if (client.IndexExists(index).Exists)
    {
        client.DeleteIndex(index);
    }
}

var createIndexResponse = client.CreateIndex(indices[0], c => c
    .Aliases(a => a
        .Alias(alias)
    )
);

Then when you create a new index, you can remove the alias from current indices and add it to the new index. This alias swap operation is atomic

createIndexResponse = client.CreateIndex(indices[1]);

// wait for index-v2 to be operable
var clusterHealthResponse = client.ClusterHealth(c => c
    .WaitForStatus(WaitForStatus.Yellow)
    .Index(indices[1]));

// swap the alias
var bulkAliasResponse = client.Alias(ba => ba
    .Add(add => add.Alias(alias).Index(indices[1]))
    .Remove(remove => remove.Alias(alias).Index("*"))
);

// verify that the alias only exists on index-v2
var aliasResponse = client.GetAlias(a => a.Name(alias));

The output of the last response is

{
  "index-v2" : {
    "aliases" : {
      "index-alias" : { }
    }
  }
}

When searching, the consumers would always use the alias. Since the alias points to a single index only, you can also use it to index new documents and update existing documents.

查看更多
登录 后发表回答