Skip to content

Instantly share code, notes, and snippets.

@jpda
Created April 8, 2015 05:41
Show Gist options
  • Select an option

  • Save jpda/661f612f772cdda93bcb to your computer and use it in GitHub Desktop.

Select an option

Save jpda/661f612f772cdda93bcb to your computer and use it in GitHub Desktop.
Create Index Schema from Type
public static void CreateIndexFromType(Type t)
{
var indexName = t.Name.ToLower();
if (SearchClient.Indexes.Exists(indexName))
{
Trace.WriteLine("Found existing index, deleting...");
SearchClient.Indexes.Delete(indexName);
}
try
{
Trace.WriteLine("Finding properties containing indexing metadata...");
var properties = t.GetProperties().Where(y => y.GetCustomAttribute<IndexMetadataAttribute>() != null).Select(x => new { Property = x.Name, Type = x.PropertyType, IndexFields = x.GetCustomAttribute<IndexMetadataAttribute>() }).ToList();
Trace.WriteLine($"Found {properties.Count} properties with index metadata, creating fields collection...");
var fields =
properties.Select(
x =>
new Field(x.Property, x.Type.ToSearchType())
{
IsKey = x.IndexFields.IsKey,
IsSearchable = x.IndexFields.IsSearchable,
IsFilterable = x.IndexFields.IsFilterable,
IsSortable = x.IndexFields.IsSortable,
IsFacetable = x.IndexFields.IsFacetable,
IsRetrievable = x.IndexFields.IsRetrievable
});
Trace.WriteLine($"Creating index {indexName}...");
var indexDefinition = new Index() { Name = indexName, Fields = fields.ToArray() };
SearchClient.Indexes.Create(indexDefinition);
Trace.WriteLine($"Created index {indexName}");
}
catch (Exception ex)
{
Trace.WriteLine("Error creating index: {0}\r\n", ex.Message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment