Last active
December 17, 2015 17:39
-
-
Save kijanawoodard/5647379 to your computer and use it in GitHub Desktop.
Put a new index before deleting the old one
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IIndexHandler | |
{ | |
void CreateIndexes(); | |
} | |
public class RavenIndexHandler : IIndexHandler | |
{ | |
private readonly IDocumentSession _session; | |
private IndexNameMap _map; | |
public RavenIndexHandler(IDocumentSession session, IndexNameMap map) | |
{ | |
_session = session; | |
_map = map; | |
} | |
public void CreateIndexes() | |
{ | |
var productIndex = new ProductIndex(); | |
var productIndexName = productIndex.IndexName; | |
var catalog = new CompositionContainer(new AssemblyCatalog(typeof(ProductIndex).Assembly)); | |
var tasks = catalog.GetExportedValues<AbstractIndexCreationTask>(); | |
foreach (var task in tasks) | |
{ | |
//skip just the index(es) that need special attention | |
if (task.IndexName == productIndexName) | |
continue; | |
task.Execute(_session.Advanced.DocumentStore); | |
} | |
var newName = ""; | |
var definition = productIndex.CreateIndexDefinition(); | |
using (var md5 = MD5.Create()) | |
{ | |
var bytes = md5.ComputeHash(definition.GetIndexHash()); | |
var hash = HttpServerUtility.UrlTokenEncode(bytes); | |
newName = string.Format("{0}.{1}", productIndexName, hash); | |
} | |
var oldName = ""; | |
_map.IndexNames.TryGetValue(productIndexName, out oldName); | |
if (oldName == newName) return; //no updates; we're done | |
_session.Advanced.DocumentStore.DatabaseCommands.PutIndex(newName, definition, true); ; | |
_map.IndexNames.AddOrUpdate(productIndexName, s => newName, (s, s1) => newName); | |
_session.Store(_map); //probably not the same session it was loaded from | |
_session.SaveChanges(); | |
if (!string.IsNullOrWhiteSpace(oldName)) | |
{ | |
_session.Advanced.DocumentStore.DatabaseCommands.DeleteIndex(oldName); | |
} | |
} | |
} | |
public interface IIndexNameProvider | |
{ | |
string GetIndexName<T>() where T : AbstractIndexCreationTask, new(); | |
} | |
public class IndexNameMap : IIndexNameProvider | |
{ | |
public static string DocumentId { get { return "admin/indexes/map"; } } | |
public string Id { get { return DocumentId; } } | |
public ConcurrentDictionary<string, string> IndexNames { get; set; } | |
public string GetIndexName<T>() where T : AbstractIndexCreationTask, new() | |
{ | |
var name = new T().IndexName; | |
return IndexNames.GetOrAdd(name, s => name); | |
} | |
public IndexNameMap() | |
{ | |
IndexNames = new ConcurrentDictionary<string, string>(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment