From aa39238b5c353344d7c9b73bbb2917a12c51a83d Mon Sep 17 00:00:00 2001 From: Mike Alhayek Date: Thu, 21 Dec 2023 07:29:24 -0800 Subject: [PATCH 1/5] Cleanup search services --- .../Providers/ElasticContentPickerResultProvider.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Providers/ElasticContentPickerResultProvider.cs b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Providers/ElasticContentPickerResultProvider.cs index edeb9e812a5..cbef6607aaa 100644 --- a/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Providers/ElasticContentPickerResultProvider.cs +++ b/src/OrchardCore/OrchardCore.Search.Elasticsearch.Core/Providers/ElasticContentPickerResultProvider.cs @@ -100,7 +100,7 @@ await _elasticIndexManager.SearchAsync(indexName, async elasticClient => { ContentItemId = doc["ContentItemId"].ToString(), DisplayText = doc["Content.ContentItem.DisplayText.keyword"].ToString(), - HasPublished = doc["Content.ContentItem.Published"].ToString().ToLower() == "true" + HasPublished = doc["Content.ContentItem.Published"].ToString().ToLowerInvariant() == "true" }); } } From 0ee977ad4659eb055f3cb3fe7884d1b8551aec16 Mon Sep 17 00:00:00 2001 From: Mike Alhayek Date: Thu, 21 Dec 2023 07:29:51 -0800 Subject: [PATCH 2/5] rest --- .../Indexing/FullTextContentIndexHandler.cs | 23 +-- .../Controllers/AdminController.cs | 163 ++++++++++-------- .../ElasticsearchIndexPermissionHelper.cs | 7 +- .../ElasticsearchAuthorizationHandler.cs | 14 +- .../Services/ElasticSearchService.cs | 23 +-- .../Startup.cs | 11 +- .../Views/ElasticSettings.Edit.cshtml | 5 +- .../Handler/LuceneAuthorizationHandler.cs | 14 +- .../Services/LuceneSearchService.cs | 10 +- .../OrchardCore.Search.Lucene/Startup.cs | 11 +- .../Handlers/ElasticIndexingContentHandler.cs | 38 ++-- .../Models/ElasticIndexSettings.cs | 31 ++-- .../ElasticContentPickerResultProvider.cs | 5 +- .../Recipes/ElasticIndexRebuildStep.cs | 2 +- .../Recipes/ElasticIndexResetStep.cs | 2 +- .../Recipes/ElasticIndexStep.cs | 2 +- .../ElasticIndexInitializerService.cs | 2 +- .../Services/ElasticIndexManager.cs | 56 ++---- .../Services/ElasticIndexingService.cs | 56 +++--- 19 files changed, 226 insertions(+), 249 deletions(-) diff --git a/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/FullTextContentIndexHandler.cs b/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/FullTextContentIndexHandler.cs index 71410a360dd..adb117c1b21 100644 --- a/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/FullTextContentIndexHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Contents/Indexing/FullTextContentIndexHandler.cs @@ -1,4 +1,3 @@ -using System; using System.Threading.Tasks; using Cysharp.Text; using OrchardCore.ContentManagement; @@ -7,14 +6,9 @@ namespace OrchardCore.Contents.Indexing { - public class FullTextContentIndexHandler : IContentItemIndexHandler + public class FullTextContentIndexHandler(IContentManager contentManager) : IContentItemIndexHandler { - private readonly IContentManager _contentManager; - - public FullTextContentIndexHandler(IContentManager contentManager) - { - _contentManager = contentManager; - } + private readonly IContentManager _contentManager = contentManager; public async Task BuildIndexAsync(BuildIndexContext context) { @@ -24,16 +18,17 @@ public async Task BuildIndexAsync(BuildIndexContext context) foreach (var segment in result.Segments) { - stringBuilder.Append(segment + " "); + stringBuilder.AppendLine(segment); } - if (!string.IsNullOrEmpty(stringBuilder.ToString())) + var value = stringBuilder.ToString(); + + if (string.IsNullOrEmpty(value)) { - context.DocumentIndex.Set( - IndexingConstants.FullTextKey, - stringBuilder.ToString(), - DocumentIndexOptions.Sanitize); + return; } + + context.DocumentIndex.Set(IndexingConstants.FullTextKey, value, DocumentIndexOptions.Sanitize); } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs index de7e1092e12..93ba53c465b 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Controllers/AdminController.cs @@ -21,7 +21,6 @@ using OrchardCore.DisplayManagement; using OrchardCore.DisplayManagement.Notify; using OrchardCore.Liquid; -using OrchardCore.Localization; using OrchardCore.Navigation; using OrchardCore.Routing; using OrchardCore.Search.Elasticsearch.Core.Models; @@ -44,13 +43,14 @@ public class AdminController : Controller private readonly ElasticIndexingService _elasticIndexingService; private readonly ElasticIndexSettingsService _elasticIndexSettingsService; private readonly JavaScriptEncoder _javaScriptEncoder; - protected readonly dynamic New; - protected readonly IStringLocalizer S; - protected readonly IHtmlLocalizer H; private readonly ElasticsearchOptions _elasticSearchOptions; private readonly INotifier _notifier; private readonly ILogger _logger; private readonly IOptions _templateOptions; + private readonly IShapeFactory _shapeFactory; + + protected readonly IStringLocalizer S; + protected readonly IHtmlLocalizer H; public AdminController( ISession session, @@ -63,13 +63,13 @@ public AdminController( ElasticIndexingService elasticIndexingService, ElasticIndexSettingsService elasticIndexSettingsService, JavaScriptEncoder javaScriptEncoder, - IShapeFactory shapeFactory, - IStringLocalizer stringLocalizer, - IHtmlLocalizer htmlLocalizer, IOptions elasticSearchOptions, INotifier notifier, ILogger logger, - IOptions templateOptions + IOptions templateOptions, + IShapeFactory shapeFactory, + IStringLocalizer stringLocalizer, + IHtmlLocalizer htmlLocalizer ) { _session = session; @@ -82,13 +82,14 @@ IOptions templateOptions _elasticIndexingService = elasticIndexingService; _elasticIndexSettingsService = elasticIndexSettingsService; _javaScriptEncoder = javaScriptEncoder; - New = shapeFactory; - S = stringLocalizer; - H = htmlLocalizer; _elasticSearchOptions = elasticSearchOptions.Value; _notifier = notifier; _logger = logger; _templateOptions = templateOptions; + + _shapeFactory = shapeFactory; + S = stringLocalizer; + H = htmlLocalizer; } public async Task Index(ContentOptions options, PagerParameters pagerParameters) @@ -98,47 +99,54 @@ public async Task Index(ContentOptions options, PagerParameters p return Forbid(); } - var indexes = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(i => new IndexViewModel { Name = i.IndexName }); + var indexes = (await _elasticIndexSettingsService.GetSettingsAsync()) + .Select(i => new IndexViewModel { Name = i.IndexName }) + .ToList(); + var totalIndexes = indexes.Count; var siteSettings = await _siteService.GetSiteSettingsAsync(); var pager = new Pager(pagerParameters, siteSettings.PageSize); - var count = indexes.Count(); - var results = indexes; if (!string.IsNullOrWhiteSpace(options.Search)) { - results = results.Where(q => q.Name.Contains(options.Search, StringComparison.OrdinalIgnoreCase)); + indexes = indexes.Where(q => q.Name.Contains(options.Search, StringComparison.OrdinalIgnoreCase)).ToList(); } - results = results + indexes = indexes .Skip(pager.GetStartIndex()) - .Take(pager.PageSize).ToList(); + .Take(pager.PageSize) + .ToList(); - // Maintain previous route data when generating page links + // Maintain previous route data when generating page links. var routeData = new RouteData(); - var pagerShape = (await New.Pager(pager)).TotalItemCount(count).RouteData(routeData); + var pagerShape = await _shapeFactory.CreateAsync("Pager", Arguments.From(new + { + pager.Page, + pager.PageSize, + TotalItemCount = totalIndexes + })); var model = new AdminIndexViewModel { - Indexes = results, + Indexes = indexes, Options = options, Pager = pagerShape }; - model.Options.ContentsBulkAction = new List() { - new SelectListItem() { Text = S["Reset"], Value = nameof(ContentsBulkAction.Reset) }, - new SelectListItem() { Text = S["Rebuild"], Value = nameof(ContentsBulkAction.Rebuild) }, - new SelectListItem() { Text = S["Delete"], Value = nameof(ContentsBulkAction.Remove) } - }; + model.Options.ContentsBulkAction = [ + new SelectListItem(S["Reset"], nameof(ContentsBulkAction.Reset)), + new SelectListItem(S["Rebuild"], nameof(ContentsBulkAction.Rebuild)), + new SelectListItem(S["Delete"], nameof(ContentsBulkAction.Remove)), + ]; return View(model); } - [HttpPost, ActionName("Index")] + [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.Filter")] public ActionResult IndexFilterPOST(AdminIndexViewModel model) { - return RedirectToAction("Index", new RouteValueDictionary { + return RedirectToAction(nameof(Index), new RouteValueDictionary { { "Options.Search", model.Options.Search } }); } @@ -166,23 +174,20 @@ public async Task Edit(string indexName = null) var model = new ElasticIndexSettingsViewModel { IsCreate = IsCreate, - IndexName = IsCreate ? "" : settings.IndexName, + IndexName = IsCreate ? string.Empty : settings.IndexName, AnalyzerName = IsCreate ? "standardanalyzer" : settings.AnalyzerName, IndexLatest = settings.IndexLatest, Culture = settings.Culture, - Cultures = ILocalizationService.GetAllCulturesAndAliases() - .Select(x => new SelectListItem { Text = x.Name + " (" + x.DisplayName + ")", Value = x.Name }), - Analyzers = _elasticSearchOptions.Analyzers - .Select(x => new SelectListItem { Text = x.Key, Value = x.Key }), - IndexedContentTypes = IsCreate ? (await _contentDefinitionManager.ListTypeDefinitionsAsync()) - .Select(x => x.Name).ToArray() : settings.IndexedContentTypes, + IndexedContentTypes = settings.IndexedContentTypes, StoreSourceData = settings.StoreSourceData }; + PopulateMenuOptions(model); + return View(model); } - [HttpPost, ActionName("Edit")] + [HttpPost, ActionName(nameof(Edit))] public async Task EditPost(ElasticIndexSettingsViewModel model, string[] indexedContentTypes) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageElasticIndexes)) @@ -194,26 +199,22 @@ public async Task EditPost(ElasticIndexSettingsViewModel model, st if (model.IsCreate) { - if (await _elasticIndexManager.Exists(model.IndexName)) + if (await _elasticIndexManager.ExistsAsync(model.IndexName)) { - ModelState.AddModelError(nameof(ElasticIndexSettingsViewModel.IndexName), S["An index named {0} already exists.", _elasticIndexManager.GetFullIndexName(model.IndexName)]); + ModelState.AddModelError(nameof(ElasticIndexSettingsViewModel.IndexName), S["An index named {0} already exists.", model.IndexName]); } } else { - if (!await _elasticIndexManager.Exists(model.IndexName)) + if (!await _elasticIndexManager.ExistsAsync(model.IndexName)) { - ModelState.AddModelError(nameof(ElasticIndexSettingsViewModel.IndexName), S["An index named {0} doesn't exist.", _elasticIndexManager.GetFullIndexName(model.IndexName)]); + ModelState.AddModelError(nameof(ElasticIndexSettingsViewModel.IndexName), S["An index named {0} doesn't exist.", model.IndexName]); } } if (!ModelState.IsValid) { - model.Cultures = CultureInfo.GetCultures(CultureTypes.AllCultures) - .Select(x => new SelectListItem { Text = x.Name + " (" + x.DisplayName + ")", Value = x.Name }); - - model.Analyzers = _elasticSearchOptions.Analyzers - .Select(x => new SelectListItem { Text = x.Key, Value = x.Key }); + PopulateMenuOptions(model); return View(model); } @@ -240,11 +241,14 @@ public async Task EditPost(ElasticIndexSettingsViewModel model, st catch (Exception e) { await _notifier.ErrorAsync(H["An error occurred while creating the index."]); - _logger.LogError(e, "An error occurred while creating an index."); + _logger.LogError(e, "An error occurred while creating index: {indexName}.", _elasticIndexManager.GetFullIndexName(model.IndexName)); + + PopulateMenuOptions(model); + return View(model); } - await _notifier.SuccessAsync(H["Index {0} created successfully.", _elasticIndexManager.GetFullIndexName(model.IndexName)]); + await _notifier.SuccessAsync(H["Index {0} created successfully.", model.IndexName]); } else { @@ -265,14 +269,17 @@ public async Task EditPost(ElasticIndexSettingsViewModel model, st catch (Exception e) { await _notifier.ErrorAsync(H["An error occurred while editing the index."]); - _logger.LogError(e, "An error occurred while editing an index."); + _logger.LogError(e, "An error occurred while editing index: {indexName}.", _elasticIndexManager.GetFullIndexName(model.IndexName)); + + PopulateMenuOptions(model); + return View(model); } - await _notifier.SuccessAsync(H["Index {0} modified successfully, please consider doing a rebuild on the index.", _elasticIndexManager.GetFullIndexName(model.IndexName)]); + await _notifier.SuccessAsync(H["Index {0} modified successfully, please consider doing a rebuild on the index.", model.IndexName]); } - return RedirectToAction("Index"); + return RedirectToAction(nameof(Index)); } [HttpPost] @@ -283,7 +290,7 @@ public async Task Reset(string id) return Forbid(); } - if (!await _elasticIndexManager.Exists(id)) + if (!await _elasticIndexManager.ExistsAsync(id)) { return NotFound(); } @@ -304,7 +311,7 @@ public async Task Rebuild(string id) return Forbid(); } - if (!await _elasticIndexManager.Exists(id)) + if (!await _elasticIndexManager.ExistsAsync(id)) { return NotFound(); } @@ -326,7 +333,7 @@ public async Task Rebuild(string id) await _notifier.SuccessAsync(H["Index {0} rebuilt successfully.", id]); - return RedirectToAction("Index"); + return RedirectToAction(nameof(Index)); } [HttpPost] @@ -337,9 +344,9 @@ public async Task Delete(ElasticIndexSettingsViewModel model) return Forbid(); } - if (!await _elasticIndexManager.Exists(model.IndexName)) + if (!await _elasticIndexManager.ExistsAsync(model.IndexName)) { - await _notifier.SuccessAsync(H["Index not found on Elasticsearch server.", _elasticIndexManager.GetFullIndexName(model.IndexName)]); + await _notifier.SuccessAsync(H["Index not found on Elasticsearch server.", model.IndexName]); return RedirectToAction("Index"); } @@ -347,12 +354,12 @@ public async Task Delete(ElasticIndexSettingsViewModel model) { await _elasticIndexingService.DeleteIndexAsync(model.IndexName); - await _notifier.SuccessAsync(H["Index {0} deleted successfully.", _elasticIndexManager.GetFullIndexName(model.IndexName)]); + await _notifier.SuccessAsync(H["Index {0} deleted successfully.", model.IndexName]); } catch (Exception e) { await _notifier.ErrorAsync(H["An error occurred while deleting the index."]); - _logger.LogError(e, "An error occurred while deleting the index {indexname}", _elasticIndexManager.GetFullIndexName(model.IndexName)); + _logger.LogError(e, "An error occurred while deleting the index {indexName}", _elasticIndexManager.GetFullIndexName(model.IndexName)); } return RedirectToAction("Index"); @@ -370,7 +377,7 @@ public async Task ForceDelete(ElasticIndexSettingsViewModel model) { await _elasticIndexingService.DeleteIndexAsync(model.IndexName); - await _notifier.SuccessAsync(H["Index {0} deleted successfully.", _elasticIndexManager.GetFullIndexName(model.IndexName)]); + await _notifier.SuccessAsync(H["Index {0} deleted successfully.", model.IndexName]); } catch (Exception e) { @@ -378,7 +385,7 @@ public async Task ForceDelete(ElasticIndexSettingsViewModel model) _logger.LogError(e, "An error occurred while deleting the index {indexName}", _elasticIndexManager.GetFullIndexName(model.IndexName)); } - return RedirectToAction("Index"); + return RedirectToAction(nameof(Index)); } public async Task Mappings(string indexName) @@ -401,18 +408,15 @@ public async Task SyncSettings() await _elasticIndexingService.SyncSettings(); - return RedirectToAction("index"); + return RedirectToAction(nameof(Index)); } public Task Query(string indexName, string query) - { - query = string.IsNullOrWhiteSpace(query) ? string.Empty : System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(query)); - return Query(new AdminQueryViewModel + => Query(new AdminQueryViewModel { IndexName = indexName, - DecodedQuery = query + DecodedQuery = string.IsNullOrWhiteSpace(query) ? string.Empty : System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(query)) }); - } [HttpPost] public async Task Query(AdminQueryViewModel model) @@ -424,10 +428,10 @@ public async Task Query(AdminQueryViewModel model) model.Indices = (await _elasticIndexSettingsService.GetSettingsAsync()).Select(x => x.IndexName).ToArray(); - // Can't query if there are no indices + // Can't query if there are no indices. if (model.Indices.Length == 0) { - return RedirectToAction("Index"); + return RedirectToAction(nameof(Index)); } if (string.IsNullOrEmpty(model.IndexName)) @@ -435,7 +439,7 @@ public async Task Query(AdminQueryViewModel model) model.IndexName = model.Indices[0]; } - if (!await _elasticIndexManager.Exists(model.IndexName)) + if (!await _elasticIndexManager.ExistsAsync(model.IndexName)) { return NotFound(); } @@ -478,7 +482,7 @@ public async Task Query(AdminQueryViewModel model) return View(model); } - [HttpPost, ActionName("Index")] + [HttpPost, ActionName(nameof(Index))] [FormValueRequired("submit.BulkAction")] public async Task IndexPost(ContentOptions options, IEnumerable itemIds) { @@ -506,7 +510,7 @@ public async Task IndexPost(ContentOptions options, IEnumerable IndexPost(ContentOptions options, IEnumerable{0} reset successfully.", _elasticIndexManager.GetFullIndexName(item.IndexName)]); + await _notifier.SuccessAsync(H["Index {0} reset successfully.", item.IndexName]); } break; case ContentsBulkAction.Rebuild: foreach (var item in checkedContentItems) { - if (!await _elasticIndexManager.Exists(item.IndexName)) + if (!await _elasticIndexManager.ExistsAsync(item.IndexName)) { return NotFound(); } await _elasticIndexingService.RebuildIndexAsync(await _elasticIndexSettingsService.GetSettingsAsync(item.IndexName)); await _elasticIndexingService.ProcessContentItemsAsync(item.IndexName); - await _notifier.SuccessAsync(H["Index {0} rebuilt successfully.", _elasticIndexManager.GetFullIndexName(item.IndexName)]); + await _notifier.SuccessAsync(H["Index {0} rebuilt successfully.", item.IndexName]); } break; default: @@ -535,14 +539,14 @@ public async Task IndexPost(ContentOptions options, IEnumerable new SelectListItem { Text = $"{x.Name} ({x.DisplayName})", Value = x.Name }); + + model.Analyzers = _elasticSearchOptions.Analyzers + .Select(x => new SelectListItem { Text = x.Key, Value = x.Key }); + } } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/ElasticsearchIndexPermissionHelper.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/ElasticsearchIndexPermissionHelper.cs index 3bdd5210b0b..b65910fc713 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/ElasticsearchIndexPermissionHelper.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/ElasticsearchIndexPermissionHelper.cs @@ -10,14 +10,11 @@ public class ElasticsearchIndexPermissionHelper private static readonly Permission _indexPermissionTemplate = new("QueryElasticsearch{0}Index", "Query Elasticsearch {0} Index", new[] { ManageElasticIndexes }); - private static readonly Dictionary _permissions = new(); + private static readonly Dictionary _permissions = []; public static Permission GetElasticIndexPermission(string indexName) { - if (string.IsNullOrEmpty(indexName)) - { - throw new ArgumentException($"{nameof(indexName)} cannot be null or empty"); - } + ArgumentException.ThrowIfNullOrEmpty(indexName, nameof(indexName)); if (!_permissions.TryGetValue(indexName, out var permission)) { diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Handlers/ElasticsearchAuthorizationHandler.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Handlers/ElasticsearchAuthorizationHandler.cs index e402f2921ef..a7f1b382d80 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Handlers/ElasticsearchAuthorizationHandler.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Handlers/ElasticsearchAuthorizationHandler.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.DependencyInjection; -using OrchardCore.Entities; using OrchardCore.Search.Abstractions; using OrchardCore.Search.Elasticsearch; using OrchardCore.Search.Elasticsearch.Core.Models; @@ -12,18 +11,13 @@ namespace OrchardCore.Search.Lucene.Handler; -public class ElasticsearchAuthorizationHandler : AuthorizationHandler +public class ElasticsearchAuthorizationHandler(IServiceProvider serviceProvider) : AuthorizationHandler { - private readonly IServiceProvider _serviceProvider; + private readonly IServiceProvider _serviceProvider = serviceProvider; private IAuthorizationService _authorizationService; private ISiteService _siteService; - public ElasticsearchAuthorizationHandler(IServiceProvider serviceProvider) - { - _serviceProvider = serviceProvider; - } - protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement) { if (context.HasSucceeded) @@ -37,9 +31,7 @@ protected override async Task HandleRequirementAsync(AuthorizationHandlerContext return; } - var service = _serviceProvider.GetService(); - - if (service == null || service.Name != parameters.ServiceName) + if (ElasticsearchService.Key != parameters.ServiceName) { // Only validate if Elasticsearch is requested. return; diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Services/ElasticSearchService.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Services/ElasticSearchService.cs index 403281a17fe..3fb3aaa136a 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Services/ElasticSearchService.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Services/ElasticSearchService.cs @@ -17,6 +17,8 @@ namespace OrchardCore.Search.Elasticsearch.Services; public class ElasticsearchService : ISearchService { + public const string Key = "Elasticsearch"; + private readonly ISiteService _siteService; private readonly ElasticIndexManager _elasticIndexManager; private readonly ElasticIndexSettingsService _elasticIndexSettingsService; @@ -47,15 +49,18 @@ ILogger logger _logger = logger; } - public string Name => "Elasticsearch"; + public string Name => Key; public async Task SearchAsync(string indexName, string term, int start, int pageSize) { - var index = !string.IsNullOrWhiteSpace(indexName) ? indexName.Trim() : await DefaultIndexAsync(); + var siteSettings = await _siteService.GetSiteSettingsAsync(); + var searchSettings = siteSettings.As(); + + var index = !string.IsNullOrWhiteSpace(indexName) ? indexName.Trim() : searchSettings.SearchIndex; var result = new SearchResult(); - if (index == null || !await _elasticIndexManager.Exists(index)) + if (index == null || !await _elasticIndexManager.ExistsAsync(index)) { _logger.LogWarning("Elasticsearch: Couldn't execute search. The search index doesn't exist."); @@ -65,12 +70,9 @@ public async Task SearchAsync(string indexName, string term, int s var elasticIndexSettings = await _elasticIndexSettingsService.GetSettingsAsync(index); result.Latest = elasticIndexSettings.IndexLatest; - var siteSettings = await _siteService.GetSiteSettingsAsync(); - var searchSettings = siteSettings.As(); - if (searchSettings.DefaultSearchFields == null || searchSettings.DefaultSearchFields.Length == 0) { - _logger.LogWarning("Elasticsearch: Couldn't execute search. No serach provider settings was defined."); + _logger.LogWarning("Elasticsearch: Couldn't execute search. No search provider settings was defined."); return result; } @@ -125,11 +127,4 @@ public async Task SearchAsync(string indexName, string term, int s return result; } - - private async Task DefaultIndexAsync() - { - var siteSettings = await _siteService.GetSiteSettingsAsync(); - - return siteSettings.As().SearchIndex; - } } diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Startup.cs b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Startup.cs index 5a3ad95badf..57f2601fbb3 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Startup.cs +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Startup.cs @@ -119,8 +119,6 @@ public override void ConfigureServices(IServiceCollection services) services.AddScoped, ElasticQueryDisplayDriver>(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); - services.AddScoped(sp => sp.GetRequiredService()); services.AddScoped(); } @@ -259,6 +257,15 @@ private static IConnectionPool GetConnectionPool(ElasticConnectionOptions elasti } } + [RequireFeatures("OrchardCore.Search")] + public class SearchStartup : StartupBase + { + public override void ConfigureServices(IServiceCollection services) + { + services.AddScoped(); + } + } + [RequireFeatures("OrchardCore.Deployment")] public class DeploymentStartup : StartupBase { diff --git a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Views/ElasticSettings.Edit.cshtml b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Views/ElasticSettings.Edit.cshtml index 85e1e6801bf..2fe0d31efe2 100644 --- a/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Views/ElasticSettings.Edit.cshtml +++ b/src/OrchardCore.Modules/OrchardCore.Search.Elasticsearch/Views/ElasticSettings.Edit.cshtml @@ -1,10 +1,11 @@ +@using OrchardCore.Contents.Indexing @using OrchardCore.Search.Elasticsearch.Core.Models @model ElasticSettingsViewModel @if (!Model.SearchIndexes.Any()) { -
@T["You need to create at least an index to set as the Search index."]
+
@T["No indices exists! Please create at least one index to configure Elasticsearch service."]
return; } @@ -38,7 +39,7 @@ - @T["A comma separated list of fields to use for search pages. The default value is Content.ContentItem.FullText."] + @T["A comma separated list of fields to use for search pages. The default value is {0}.", $"{IndexingConstants.FullTextKey}"]