-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathArticlesAzureSearcSearchEngine.cs
More file actions
77 lines (69 loc) · 2.52 KB
/
ArticlesAzureSearcSearchEngine.cs
File metadata and controls
77 lines (69 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CoreWiki.Application.Articles.Search;
using Microsoft.Azure.Search;
using Microsoft.Azure.Search.Models;
using Microsoft.Extensions.Logging;
namespace CoreWiki.Azure.Areas.AzureSearch
{
/// <summary>
/// Tutorial here: https://github.com/Azure-Samples/search-dotnet-getting-started/blob/master/DotNetHowTo/DotNetHowTo/Program.cs
/// </summary>
/// <typeparam name="T"></typeparam>
public class AzureSearchProvider<T> : ISearchProvider<T> where T : class
{
private readonly ILogger _logger;
private readonly IAzureSearchClient _searchClient;
private readonly ISearchIndexClient _myclient;
public AzureSearchProvider(ILogger<AzureSearchProvider<T>> logger, IAzureSearchClient searchClient)
{
_logger = logger;
_searchClient = searchClient;
_myclient = _searchClient.GetSearchClient<T>();
}
public async Task<int> IndexElementsAsync(params T[] items)
{
var action = items.Select(IndexAction.MergeOrUpload);
var job = new IndexBatch<T>(action);
try
{
var myclient = _searchClient.CreateServiceClient<T>();
var res = await _myclient.Documents.IndexAsync<T>(job).ConfigureAwait(false);
return res.Results.Count;
}
catch (IndexBatchException e)
{
// Sometimes when your Search service is under load, indexing will fail for some of the documents in
// the batch. Depending on your application, you can take compensating actions like delaying and
// retrying. For this simple demo, we just log the failed document keys and continue.
var failedElements = e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key);
_logger.LogError(e, "Failed to index some of the documents", failedElements);
return items.Length - failedElements.Count();
}
}
public async Task<(IEnumerable<T> results, long total)> SearchAsync(string Query, int pageNumber, int resultsPerPage)
{
var offset = (pageNumber - 1) * resultsPerPage;
var parameters = new SearchParameters()
{
IncludeTotalResultCount = true,
Top = resultsPerPage,
Skip = offset,
};
try
{
var res = await _myclient.Documents.SearchAsync(Query, parameters).ConfigureAwait(false);
var total = res.Count.GetValueOrDefault();
var list = res.Results;
//TODO: map results
return (results: null, total: total);
}
catch (System.Exception e)
{
_logger.LogCritical(e, $"{nameof(SearchAsync)} Search failed horribly, you should check it out");
return (results: null, total: 0);
}
}
}
}