Skip to content

Commit 4c76d45

Browse files
authored
Merge pull request #52 from HeidiSteen/master
Indexer sample update: Added a schedule, field mappings, parameters, CheckIndexerStatus
2 parents c712a97 + 3e37b39 commit 4c76d45

File tree

2 files changed

+70
-11
lines changed

2 files changed

+70
-11
lines changed

DotNetHowToIndexers/Program.cs

Lines changed: 70 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System;
22
using System.Net;
3-
using System.Threading;
43
using System.Threading.Tasks;
54
using Azure;
65
using Azure.Search.Documents.Indexes;
@@ -26,7 +25,7 @@ public static async Task Main(string[] args)
2625
Environment.Exit(-1);
2726
}
2827

29-
if (configuration["SearchServiceAdminApiKey"] == "Put your primary or secondary API key here")
28+
if (configuration["SearchServiceAdminApiKey"] == "Put your search service admin API key here")
3029
{
3130
Console.Error.WriteLine("Specify SearchServiceAdminApiKey in appsettings.json");
3231
Environment.Exit(-1);
@@ -44,7 +43,7 @@ public static async Task Main(string[] args)
4443
Console.WriteLine("Creating index...");
4544
FieldBuilder fieldBuilder = new FieldBuilder();
4645
var searchFields = fieldBuilder.Build(typeof(Hotel));
47-
var searchIndex = new SearchIndex("hotels", searchFields);
46+
var searchIndex = new SearchIndex("hotels-sql-idx", searchFields);
4847

4948
// If we have run the sample before, this index will be populated
5049
// We can clear the index by deleting it if it exists and creating
@@ -68,19 +67,43 @@ public static async Task Main(string[] args)
6867
// https://docs.microsoft.com/en-us/sql/relational-databases/track-changes/about-change-tracking-sql-server
6968
var dataSource =
7069
new SearchIndexerDataSourceConnection(
71-
"azure-sql",
70+
"hotels-sql-ds",
7271
SearchIndexerDataSourceType.AzureSql,
7372
configuration["AzureSQLConnectionString"],
7473
new SearchIndexerDataContainer("hotels"));
7574

7675
// The data source does not need to be deleted if it was already created,
7776
// but the connection string may need to be updated if it was changed
78-
indexerClient.CreateDataSourceConnection(dataSource);
77+
indexerClient.CreateOrUpdateDataSourceConnection(dataSource);
7978

8079
Console.WriteLine("Creating Azure SQL indexer...");
81-
var indexer = new SearchIndexer("azure-sql", dataSource.Name, searchIndex.Name)
80+
81+
var schedule = new IndexingSchedule(TimeSpan.FromDays(1))
82+
{
83+
StartTime = DateTimeOffset.Now
84+
};
85+
86+
var parameters = new IndexingParameters()
87+
{
88+
BatchSize = 100,
89+
MaxFailedItems = 0,
90+
MaxFailedItemsPerBatch = 0
91+
};
92+
93+
// Indexer declarations require a data source and search index.
94+
// Common optional properties include a schedule, parameters, and field mappings
95+
// The field mappings below are redundant due to how the Hotel class is defined, but
96+
// we included them anyway to show the syntax
97+
var indexer = new SearchIndexer("hotels-sql-idxr", dataSource.Name, searchIndex.Name)
8298
{
8399
Description = "Data indexer",
100+
Schedule = schedule,
101+
Parameters = parameters,
102+
FieldMappings =
103+
{
104+
new FieldMapping("_id") {TargetFieldName = "HotelId"},
105+
new FieldMapping("Amenities") {TargetFieldName = "Tags"}
106+
}
84107
};
85108

86109
// Indexers contain metadata about how much they have already indexed
@@ -89,7 +112,7 @@ public static async Task Main(string[] args)
89112
// To avoid this, reset the indexer if it exists
90113
CleanupSearchIndexerClientResources(indexerClient, indexer);
91114

92-
indexerClient.CreateIndexer(indexer);
115+
await indexerClient.CreateOrUpdateIndexerAsync(indexer);
93116

94117
// We created the indexer with a schedule, but we also
95118
// want to run it immediately
@@ -104,11 +127,47 @@ public static async Task Main(string[] args)
104127
Console.WriteLine("Failed to run indexer: {0}", e.Response.Content);
105128
}
106129

130+
// Wait 5 seconds for indexing to complete before checking status
131+
Console.WriteLine("Waiting for indexing...\n");
132+
System.Threading.Thread.Sleep(5000);
133+
134+
// After an indexer run, you can retrieve status.
135+
CheckIndexerStatus(indexerClient, indexer);
136+
107137
Console.WriteLine("Press any key to continue...");
108138
Console.ReadKey();
109139
Environment.Exit(0);
110140
}
111141

142+
private static void CheckIndexerStatus(SearchIndexerClient indexerClient, SearchIndexer indexer)
143+
{
144+
try
145+
{
146+
string indexerName = "hotels-sql-idxr";
147+
SearchIndexerStatus execInfo = indexerClient.GetIndexerStatus(indexerName);
148+
149+
Console.WriteLine("Indexer has run {0} times.", execInfo.ExecutionHistory.Count);
150+
Console.WriteLine("Indexer Status: " + execInfo.Status.ToString());
151+
152+
IndexerExecutionResult result = execInfo.LastResult;
153+
154+
Console.WriteLine("Latest run");
155+
Console.WriteLine("Run Status: {0}", result.Status.ToString());
156+
Console.WriteLine("Total Documents: {0}, Failed: {1}", result.ItemCount, result.FailedItemCount);
157+
158+
TimeSpan elapsed = result.EndTime.Value - result.StartTime.Value;
159+
Console.WriteLine("StartTime: {0:T}, EndTime: {1:T}, Elapsed: {2:t}", result.StartTime.Value, result.EndTime.Value, elapsed);
160+
161+
string errorMsg = (result.ErrorMessage == null) ? "none" : result.ErrorMessage;
162+
Console.WriteLine("ErrorMessage: {0}", errorMsg);
163+
Console.WriteLine(" Document Errors: {0}, Warnings: {1}\n", result.Errors.Count, result.Warnings.Count);
164+
}
165+
catch (Exception e)
166+
{
167+
// Handle exception
168+
}
169+
}
170+
112171
private static void CleanupSearchIndexClientResources(SearchIndexClient indexClient, SearchIndex index)
113172
{
114173
try
@@ -120,8 +179,8 @@ private static void CleanupSearchIndexClientResources(SearchIndexClient indexCli
120179
}
121180
catch (RequestFailedException e) when (e.Status == 404)
122181
{
123-
//if exception occurred and status is "Not Found", this is work as expect
124-
Console.WriteLine("Failed to find index and this is because it's not there.");
182+
//if exception occurred and status is "Not Found", this is working as expected
183+
Console.WriteLine("Failed to find index and this is because it doesn't exist.");
125184
}
126185
}
127186

@@ -136,8 +195,8 @@ private static void CleanupSearchIndexerClientResources(SearchIndexerClient inde
136195
}
137196
catch (RequestFailedException e) when (e.Status == 404)
138197
{
139-
//if exception occurred and status is "Not Found", this is work as expect
140-
Console.WriteLine("Failed to find indexer and this is because it's not there.");
198+
//if exception occurred and status is "Not Found", this is working as expected
199+
Console.WriteLine("Failed to find indexer and this is because it doesn't exist.");
141200
}
142201
}
143202
}

DotNetHowToIndexers/hotels.sql

8 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)