| | | 1 | | using System.Diagnostics; |
| | | 2 | | using Microsoft.Extensions.Configuration; |
| | | 3 | | using Microsoft.Extensions.Logging; |
| | | 4 | | using Elasticsearch.Net; |
| | | 5 | | using Nest; |
| | | 6 | | using OServices.FiltersServices.FilterModels; |
| | | 7 | | using Services.FiltersServices.DataFilterManagers; |
| | | 8 | | |
| | | 9 | | namespace Services.SearchServices.OrderSearch; |
| | | 10 | | |
| | | 11 | | public class OrderElasticsearchService : IOrderSearchService |
| | | 12 | | { |
| | | 13 | | private readonly IElasticClient _client; |
| | | 14 | | private readonly string _indexName; |
| | | 15 | | private readonly ILogger<OrderElasticsearchService> _logger; |
| | | 16 | | private readonly IOrderSearchDiagnosticsStore _diagnostics; |
| | | 17 | | |
| | 0 | 18 | | public OrderElasticsearchService( |
| | 0 | 19 | | IConfiguration configuration, |
| | 0 | 20 | | ILogger<OrderElasticsearchService> logger, |
| | 0 | 21 | | IOrderSearchDiagnosticsStore diagnostics) |
| | | 22 | | { |
| | 0 | 23 | | _logger = logger; |
| | 0 | 24 | | _diagnostics = diagnostics; |
| | 0 | 25 | | _indexName = configuration["OrdersSearch:IndexName"] ?? "orders"; |
| | | 26 | | |
| | 0 | 27 | | var url = configuration["OrdersSearch:Url"] ?? "http://localhost:9201"; |
| | 0 | 28 | | var settings = new ConnectionSettings(new Uri(url)) |
| | 0 | 29 | | .DefaultIndex(_indexName) |
| | 0 | 30 | | .RequestTimeout(TimeSpan.FromSeconds(30)); |
| | | 31 | | |
| | 0 | 32 | | _client = new ElasticClient(settings); |
| | 0 | 33 | | } |
| | | 34 | | |
| | | 35 | | public async Task<bool> CreateIndexAsync() |
| | | 36 | | { |
| | | 37 | | try |
| | | 38 | | { |
| | 0 | 39 | | var exists = await _client.Indices.ExistsAsync(_indexName); |
| | 0 | 40 | | if (exists.Exists) |
| | | 41 | | { |
| | 0 | 42 | | return await EnsureScanitMappingAsync(); |
| | | 43 | | } |
| | | 44 | | |
| | 0 | 45 | | var response = await _client.Indices.CreateAsync(_indexName, c => c |
| | 0 | 46 | | .Map<OrderSearchDocument>(m => m |
| | 0 | 47 | | .Properties(p => p |
| | 0 | 48 | | .Number(n => n.Name(d => d.Id).Type(NumberType.Integer)) |
| | 0 | 49 | | .Text(t => t.Name(d => d.ShipmentNumber) |
| | 0 | 50 | | .Analyzer("standard") |
| | 0 | 51 | | .Fields(f => f |
| | 0 | 52 | | .Keyword(k => k.Name("keyword").IgnoreAbove(256)) |
| | 0 | 53 | | .Text(tt => tt.Name("ngram").Analyzer("ngram_analyzer")))) |
| | 0 | 54 | | .Keyword(k => k.Name(d => d.Scanit)) |
| | 0 | 55 | | .Text(t => t.Name(d => d.ProductName) |
| | 0 | 56 | | .Analyzer("russian") |
| | 0 | 57 | | .Fields(f => f |
| | 0 | 58 | | .Text(tt => tt.Name("ngram").Analyzer("ngram_analyzer")))) |
| | 0 | 59 | | .Text(t => t.Name(d => d.Article) |
| | 0 | 60 | | .Analyzer("standard") |
| | 0 | 61 | | .Fields(f => f |
| | 0 | 62 | | .Text(tt => tt.Name("ngram").Analyzer("ngram_analyzer")))) |
| | 0 | 63 | | .Text(t => t.Name(d => d.ProductKey) |
| | 0 | 64 | | .Analyzer("standard") |
| | 0 | 65 | | .Fields(f => f |
| | 0 | 66 | | .Text(tt => tt.Name("ngram").Analyzer("ngram_analyzer")))) |
| | 0 | 67 | | .Keyword(k => k.Name(d => d.NormalizedArticleKey)) |
| | 0 | 68 | | .Keyword(k => k.Name(d => d.AppStatusName)) |
| | 0 | 69 | | .Keyword(k => k.Name(d => d.SupplierName)) |
| | 0 | 70 | | .Keyword(k => k.Name(d => d.ManufacturerName)) |
| | 0 | 71 | | .Keyword(k => k.Name(d => d.ShipmentWarehouseName)) |
| | 0 | 72 | | .Keyword(k => k.Name(d => d.OzonClientName)) |
| | 0 | 73 | | .Boolean(b => b.Name(d => d.IsArchived)) |
| | 0 | 74 | | .Date(d => d.Name(doc => doc.UpdatedAt)) |
| | 0 | 75 | | ) |
| | 0 | 76 | | ) |
| | 0 | 77 | | .Settings(s => s |
| | 0 | 78 | | .Setting("index.max_ngram_diff", 8) |
| | 0 | 79 | | .Analysis(a => a |
| | 0 | 80 | | .Analyzers(an => an |
| | 0 | 81 | | .Custom("russian", ca => ca |
| | 0 | 82 | | .Tokenizer("standard") |
| | 0 | 83 | | .Filters("lowercase", "russian_stop", "russian_stemmer")) |
| | 0 | 84 | | .Custom("ngram_analyzer", ca => ca |
| | 0 | 85 | | .Tokenizer("keyword") |
| | 0 | 86 | | .Filters("lowercase", "ngram_filter"))) |
| | 0 | 87 | | .TokenFilters(tf => tf |
| | 0 | 88 | | .Stop("russian_stop", st => st.StopWords("_russian_")) |
| | 0 | 89 | | .Stemmer("russian_stemmer", st => st.Language("russian")) |
| | 0 | 90 | | .NGram("ngram_filter", ng => ng.MinGram(2).MaxGram(10)))) |
| | 0 | 91 | | .NumberOfShards(1) |
| | 0 | 92 | | .NumberOfReplicas(0))); |
| | | 93 | | |
| | 0 | 94 | | if (!response.IsValid) |
| | | 95 | | { |
| | 0 | 96 | | if (response.ServerError?.Error?.Type == "resource_already_exists_exception") |
| | | 97 | | { |
| | 0 | 98 | | return true; |
| | | 99 | | } |
| | | 100 | | |
| | 0 | 101 | | LogTransientOrError(response, "Ошибка создания индекса {IndexName}: {DebugInfo}", _indexName, response.D |
| | | 102 | | } |
| | | 103 | | |
| | 0 | 104 | | return response.IsValid; |
| | | 105 | | } |
| | 0 | 106 | | catch (Exception ex) |
| | | 107 | | { |
| | 0 | 108 | | LogTransientOrError(ex, "Ошибка при создании индекса {IndexName}", _indexName); |
| | 0 | 109 | | return false; |
| | | 110 | | } |
| | 0 | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Индекс, созданный до появления Scanit, не знает этого поля — без явного mapping Elasticsearch |
| | | 115 | | /// вывел бы text, а точный поиск идёт по keyword. Добавление поля идемпотентно. |
| | | 116 | | /// </summary> |
| | | 117 | | private static int _scanitMappingEnsured; |
| | | 118 | | |
| | | 119 | | /// <summary> |
| | | 120 | | /// Первая индексация после деплоя не должна опередить добавление mapping: иначе Elasticsearch |
| | | 121 | | /// выведет для Scanit text и PutMapping уже упрётся в конфликт типов. |
| | | 122 | | /// </summary> |
| | | 123 | | private async Task EnsureScanitMappingOnceAsync() |
| | | 124 | | { |
| | 0 | 125 | | if (Volatile.Read(ref _scanitMappingEnsured) == 1) |
| | | 126 | | { |
| | 0 | 127 | | return; |
| | | 128 | | } |
| | | 129 | | |
| | 0 | 130 | | if (await EnsureScanitMappingAsync()) |
| | | 131 | | { |
| | 0 | 132 | | Volatile.Write(ref _scanitMappingEnsured, 1); |
| | | 133 | | } |
| | 0 | 134 | | } |
| | | 135 | | |
| | | 136 | | private async Task<bool> EnsureScanitMappingAsync() |
| | | 137 | | { |
| | 0 | 138 | | var response = await _client.Indices.PutMappingAsync<OrderSearchDocument>(m => m |
| | 0 | 139 | | .Index(_indexName) |
| | 0 | 140 | | .Properties(p => p.Keyword(k => k.Name(d => d.Scanit)))); |
| | | 141 | | |
| | 0 | 142 | | if (!response.IsValid) |
| | | 143 | | { |
| | 0 | 144 | | LogTransientOrError(response, "Ошибка добавления поля Scanit в индекс {IndexName}: {DebugInfo}", |
| | 0 | 145 | | _indexName, response.DebugInformation); |
| | | 146 | | } |
| | | 147 | | |
| | 0 | 148 | | return response.IsValid; |
| | 0 | 149 | | } |
| | | 150 | | |
| | | 151 | | public async Task<bool> IndexExistsAsync() |
| | | 152 | | { |
| | | 153 | | try |
| | | 154 | | { |
| | 0 | 155 | | var response = await _client.Indices.ExistsAsync(_indexName); |
| | 0 | 156 | | return response.Exists; |
| | | 157 | | } |
| | 0 | 158 | | catch (Exception ex) |
| | | 159 | | { |
| | 0 | 160 | | LogTransientOrError(ex, "Ошибка при проверке существования индекса {IndexName}", _indexName); |
| | 0 | 161 | | return false; |
| | | 162 | | } |
| | 0 | 163 | | } |
| | | 164 | | |
| | | 165 | | public async Task<bool> DeleteIndexAsync() |
| | | 166 | | { |
| | | 167 | | try |
| | | 168 | | { |
| | 0 | 169 | | var response = await _client.Indices.DeleteAsync(_indexName); |
| | 0 | 170 | | return response.IsValid; |
| | | 171 | | } |
| | 0 | 172 | | catch (Exception ex) |
| | | 173 | | { |
| | 0 | 174 | | LogTransientOrError(ex, "Ошибка при удалении индекса {IndexName}", _indexName); |
| | 0 | 175 | | return false; |
| | | 176 | | } |
| | 0 | 177 | | } |
| | | 178 | | |
| | | 179 | | public async Task<bool> IndexOrderAsync(OrderSearchDocument document) |
| | | 180 | | { |
| | 0 | 181 | | var sw = Stopwatch.StartNew(); |
| | | 182 | | try |
| | | 183 | | { |
| | 0 | 184 | | await EnsureScanitMappingOnceAsync(); |
| | 0 | 185 | | document.NormalizedArticleKey = ResolveNormalizedArticleKey(document); |
| | 0 | 186 | | var response = await _client.IndexAsync(document, i => i.Index(_indexName).Id(document.Id)); |
| | 0 | 187 | | var ok = IsIndexSuccessful(response); |
| | 0 | 188 | | if (!ok) |
| | | 189 | | { |
| | 0 | 190 | | LogTransientOrError(response, "Ошибка индексации заказа {OrderId}: {DebugInfo}", document.Id, response.D |
| | | 191 | | } |
| | | 192 | | |
| | 0 | 193 | | _diagnostics.RecordIndex( |
| | 0 | 194 | | OrderSearchIndexOperation.Single, |
| | 0 | 195 | | 1, |
| | 0 | 196 | | sw.ElapsedMilliseconds, |
| | 0 | 197 | | ok, |
| | 0 | 198 | | ok ? "Индексирован" : "Ошибка индексации", |
| | 0 | 199 | | document.Id); |
| | 0 | 200 | | return ok; |
| | | 201 | | } |
| | 0 | 202 | | catch (Exception ex) |
| | | 203 | | { |
| | 0 | 204 | | LogTransientOrError(ex, "Ошибка при индексации заказа {OrderId}", document.Id); |
| | 0 | 205 | | _diagnostics.RecordIndex( |
| | 0 | 206 | | OrderSearchIndexOperation.Single, |
| | 0 | 207 | | 1, |
| | 0 | 208 | | sw.ElapsedMilliseconds, |
| | 0 | 209 | | false, |
| | 0 | 210 | | ex.Message, |
| | 0 | 211 | | document.Id); |
| | 0 | 212 | | return false; |
| | | 213 | | } |
| | 0 | 214 | | } |
| | | 215 | | |
| | | 216 | | public async Task<bool> BulkIndexOrdersAsync(IEnumerable<OrderSearchDocument> documents) |
| | | 217 | | { |
| | 0 | 218 | | var sw = Stopwatch.StartNew(); |
| | | 219 | | try |
| | | 220 | | { |
| | 0 | 221 | | await EnsureScanitMappingOnceAsync(); |
| | 0 | 222 | | var bulkDescriptor = new BulkDescriptor(); |
| | 0 | 223 | | var count = 0; |
| | | 224 | | |
| | 0 | 225 | | foreach (var document in documents) |
| | | 226 | | { |
| | 0 | 227 | | count++; |
| | 0 | 228 | | bulkDescriptor.Index<OrderSearchDocument>(i => i.Document(document).Id(document.Id).Index(_indexName)); |
| | | 229 | | } |
| | | 230 | | |
| | 0 | 231 | | if (count == 0) |
| | | 232 | | { |
| | 0 | 233 | | return true; |
| | | 234 | | } |
| | | 235 | | |
| | 0 | 236 | | var response = await _client.BulkAsync(bulkDescriptor); |
| | 0 | 237 | | var ok = IsBulkSuccessful(response); |
| | 0 | 238 | | if (!ok) |
| | | 239 | | { |
| | 0 | 240 | | LogTransientOrError(response, "Ошибка массовой индексации заказов: {DebugInfo}", response.DebugInformati |
| | | 241 | | } |
| | | 242 | | |
| | 0 | 243 | | _diagnostics.RecordIndex( |
| | 0 | 244 | | OrderSearchIndexOperation.Bulk, |
| | 0 | 245 | | count, |
| | 0 | 246 | | sw.ElapsedMilliseconds, |
| | 0 | 247 | | ok, |
| | 0 | 248 | | ok ? $"Bulk {count} док." : "Ошибка bulk-индексации"); |
| | 0 | 249 | | return ok; |
| | | 250 | | } |
| | 0 | 251 | | catch (Exception ex) |
| | | 252 | | { |
| | 0 | 253 | | LogTransientOrError(ex, "Ошибка при массовой индексации заказов"); |
| | 0 | 254 | | _diagnostics.RecordIndex( |
| | 0 | 255 | | OrderSearchIndexOperation.Bulk, |
| | 0 | 256 | | 0, |
| | 0 | 257 | | sw.ElapsedMilliseconds, |
| | 0 | 258 | | false, |
| | 0 | 259 | | ex.Message); |
| | 0 | 260 | | return false; |
| | | 261 | | } |
| | 0 | 262 | | } |
| | | 263 | | |
| | | 264 | | /// <summary> |
| | | 265 | | /// ES 8 возвращает 201 Created для новых документов — NEST помечает такой bulk как IsValid=false, |
| | | 266 | | /// хотя операции успешны. Смотрим только реальные ошибки (response.Errors / item.Error). |
| | | 267 | | /// </summary> |
| | | 268 | | private static bool IsBulkSuccessful(BulkResponse response) |
| | | 269 | | { |
| | 0 | 270 | | if (response.Errors) |
| | | 271 | | { |
| | 0 | 272 | | return false; |
| | | 273 | | } |
| | | 274 | | |
| | 0 | 275 | | if (response.IsValid) |
| | | 276 | | { |
| | 0 | 277 | | return true; |
| | | 278 | | } |
| | | 279 | | |
| | 0 | 280 | | return response.Items == null || response.Items.All(static item => item.Error == null); |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | private static bool IsIndexSuccessful(IndexResponse response) => |
| | 0 | 284 | | response.IsValid || response.Result is Result.Created or Result.Updated; |
| | | 285 | | |
| | | 286 | | public async Task<bool> DeleteFromIndexAsync(int orderId) |
| | | 287 | | { |
| | 0 | 288 | | var sw = Stopwatch.StartNew(); |
| | | 289 | | try |
| | | 290 | | { |
| | 0 | 291 | | var response = await _client.DeleteAsync<OrderSearchDocument>(orderId, d => d.Index(_indexName)); |
| | 0 | 292 | | var ok = response.IsValid || response.Result == Result.NotFound; |
| | 0 | 293 | | _diagnostics.RecordIndex( |
| | 0 | 294 | | OrderSearchIndexOperation.Delete, |
| | 0 | 295 | | 1, |
| | 0 | 296 | | sw.ElapsedMilliseconds, |
| | 0 | 297 | | ok, |
| | 0 | 298 | | ok ? "Удалён из индекса" : "Ошибка удаления", |
| | 0 | 299 | | orderId); |
| | 0 | 300 | | return ok; |
| | | 301 | | } |
| | 0 | 302 | | catch (Exception ex) |
| | | 303 | | { |
| | 0 | 304 | | LogTransientOrError(ex, "Ошибка при удалении заказа {OrderId} из индекса", orderId); |
| | 0 | 305 | | _diagnostics.RecordIndex( |
| | 0 | 306 | | OrderSearchIndexOperation.Delete, |
| | 0 | 307 | | 1, |
| | 0 | 308 | | sw.ElapsedMilliseconds, |
| | 0 | 309 | | false, |
| | 0 | 310 | | ex.Message, |
| | 0 | 311 | | orderId); |
| | 0 | 312 | | return false; |
| | | 313 | | } |
| | 0 | 314 | | } |
| | | 315 | | |
| | | 316 | | public async Task<OrderSearchDocument?> GetDocumentByIdAsync(int orderId) |
| | | 317 | | { |
| | | 318 | | try |
| | | 319 | | { |
| | 0 | 320 | | var response = await _client.GetAsync<OrderSearchDocument>(orderId, g => g.Index(_indexName)); |
| | 0 | 321 | | if (!response.Found || response.Source == null) |
| | | 322 | | { |
| | 0 | 323 | | return null; |
| | | 324 | | } |
| | | 325 | | |
| | 0 | 326 | | return response.Source; |
| | | 327 | | } |
| | 0 | 328 | | catch (Exception ex) |
| | | 329 | | { |
| | 0 | 330 | | LogTransientOrError(ex, "Ошибка при чтении заказа {OrderId} из индекса", orderId); |
| | 0 | 331 | | return null; |
| | | 332 | | } |
| | 0 | 333 | | } |
| | | 334 | | |
| | | 335 | | public async Task<long> GetTotalCountAsync() |
| | | 336 | | { |
| | | 337 | | try |
| | | 338 | | { |
| | 0 | 339 | | var response = await _client.CountAsync<OrderSearchDocument>(c => c.Index(_indexName)); |
| | 0 | 340 | | return response.Count; |
| | | 341 | | } |
| | 0 | 342 | | catch (Exception ex) |
| | | 343 | | { |
| | 0 | 344 | | LogTransientOrError(ex, "Ошибка при подсчёте документов индекса {IndexName}", _indexName); |
| | 0 | 345 | | return 0; |
| | | 346 | | } |
| | 0 | 347 | | } |
| | | 348 | | |
| | | 349 | | public async Task<IReadOnlySet<int>> GetExistingOrderIdsAsync( |
| | | 350 | | IReadOnlyList<int> orderIds, |
| | | 351 | | CancellationToken cancellationToken = default) |
| | | 352 | | { |
| | 0 | 353 | | var result = new HashSet<int>(); |
| | 0 | 354 | | if (orderIds.Count == 0) |
| | | 355 | | { |
| | 0 | 356 | | return result; |
| | | 357 | | } |
| | | 358 | | |
| | | 359 | | try |
| | | 360 | | { |
| | 0 | 361 | | var response = await _client.SearchAsync<OrderSearchDocument>(s => s |
| | 0 | 362 | | .Index(_indexName) |
| | 0 | 363 | | .Size(orderIds.Count) |
| | 0 | 364 | | .Source(false) |
| | 0 | 365 | | .Query(q => q.Terms(t => t.Field(f => f.Id).Terms(orderIds))), |
| | 0 | 366 | | cancellationToken); |
| | | 367 | | |
| | 0 | 368 | | if (!response.IsValid) |
| | | 369 | | { |
| | 0 | 370 | | _logger.LogWarning( |
| | 0 | 371 | | "Terms-поиск ID в индексе {IndexName} вернул невалидный ответ: {DebugInfo}", |
| | 0 | 372 | | _indexName, |
| | 0 | 373 | | response.DebugInformation); |
| | 0 | 374 | | return result; |
| | | 375 | | } |
| | | 376 | | |
| | 0 | 377 | | foreach (var hit in response.Hits) |
| | | 378 | | { |
| | 0 | 379 | | if (int.TryParse(hit.Id, out var id)) |
| | | 380 | | { |
| | 0 | 381 | | result.Add(id); |
| | | 382 | | } |
| | | 383 | | } |
| | 0 | 384 | | } |
| | 0 | 385 | | catch (Exception ex) |
| | | 386 | | { |
| | 0 | 387 | | LogTransientOrError(ex, "Ошибка mget при проверке существующих документов в индексе {IndexName}", _indexName |
| | 0 | 388 | | } |
| | | 389 | | |
| | 0 | 390 | | return result; |
| | 0 | 391 | | } |
| | | 392 | | |
| | | 393 | | public async Task<IReadOnlyList<int>> GetAllIndexedOrderIdsAsync(CancellationToken cancellationToken = default) |
| | | 394 | | { |
| | 0 | 395 | | var ids = new List<int>(); |
| | 0 | 396 | | ISearchResponse<OrderSearchDocument>? searchResponse = null; |
| | | 397 | | |
| | | 398 | | try |
| | | 399 | | { |
| | 0 | 400 | | searchResponse = await _client.SearchAsync<OrderSearchDocument>(s => s |
| | 0 | 401 | | .Index(_indexName) |
| | 0 | 402 | | .Source(false) |
| | 0 | 403 | | .Size(2000) |
| | 0 | 404 | | .Scroll("2m") |
| | 0 | 405 | | .Query(q => q.MatchAll()), cancellationToken); |
| | | 406 | | |
| | 0 | 407 | | if (!searchResponse.IsValid) |
| | | 408 | | { |
| | 0 | 409 | | _logger.LogWarning( |
| | 0 | 410 | | "Scroll индекса {IndexName} вернул невалидный ответ: {DebugInfo}", |
| | 0 | 411 | | _indexName, |
| | 0 | 412 | | searchResponse.DebugInformation); |
| | 0 | 413 | | return ids; |
| | | 414 | | } |
| | | 415 | | |
| | 0 | 416 | | while (searchResponse.Hits.Count > 0) |
| | | 417 | | { |
| | 0 | 418 | | foreach (var hit in searchResponse.Hits) |
| | | 419 | | { |
| | 0 | 420 | | if (int.TryParse(hit.Id, out var id)) |
| | | 421 | | { |
| | 0 | 422 | | ids.Add(id); |
| | | 423 | | } |
| | | 424 | | } |
| | | 425 | | |
| | 0 | 426 | | if (string.IsNullOrEmpty(searchResponse.ScrollId)) |
| | | 427 | | { |
| | | 428 | | break; |
| | | 429 | | } |
| | | 430 | | |
| | 0 | 431 | | searchResponse = await _client.ScrollAsync<OrderSearchDocument>( |
| | 0 | 432 | | "2m", |
| | 0 | 433 | | searchResponse.ScrollId, |
| | 0 | 434 | | ct: cancellationToken); |
| | | 435 | | } |
| | 0 | 436 | | } |
| | 0 | 437 | | catch (Exception ex) |
| | | 438 | | { |
| | 0 | 439 | | LogTransientOrError(ex, "Ошибка scroll при чтении ID из индекса {IndexName}", _indexName); |
| | 0 | 440 | | } |
| | | 441 | | finally |
| | | 442 | | { |
| | 0 | 443 | | if (!string.IsNullOrEmpty(searchResponse?.ScrollId)) |
| | | 444 | | { |
| | 0 | 445 | | await _client.ClearScrollAsync(new ClearScrollRequest(searchResponse.ScrollId), cancellationToken); |
| | | 446 | | } |
| | | 447 | | } |
| | | 448 | | |
| | 0 | 449 | | return ids; |
| | 0 | 450 | | } |
| | | 451 | | |
| | | 452 | | public async Task<int> BulkDeleteFromIndexAsync( |
| | | 453 | | IReadOnlyList<int> orderIds, |
| | | 454 | | CancellationToken cancellationToken = default) |
| | | 455 | | { |
| | 0 | 456 | | if (orderIds.Count == 0) |
| | | 457 | | { |
| | 0 | 458 | | return 0; |
| | | 459 | | } |
| | | 460 | | |
| | 0 | 461 | | var sw = Stopwatch.StartNew(); |
| | | 462 | | try |
| | | 463 | | { |
| | 0 | 464 | | var bulkDescriptor = new BulkDescriptor(); |
| | 0 | 465 | | foreach (var id in orderIds) |
| | | 466 | | { |
| | 0 | 467 | | bulkDescriptor.Delete<OrderSearchDocument>(d => d.Index(_indexName).Id(id)); |
| | | 468 | | } |
| | | 469 | | |
| | 0 | 470 | | var response = await _client.BulkAsync(bulkDescriptor, cancellationToken); |
| | 0 | 471 | | var deleted = IsBulkSuccessful(response) ? orderIds.Count : 0; |
| | 0 | 472 | | _diagnostics.RecordIndex( |
| | 0 | 473 | | OrderSearchIndexOperation.Delete, |
| | 0 | 474 | | deleted, |
| | 0 | 475 | | sw.ElapsedMilliseconds, |
| | 0 | 476 | | deleted > 0, |
| | 0 | 477 | | deleted > 0 |
| | 0 | 478 | | ? $"Bulk-удаление: {deleted} документов" |
| | 0 | 479 | | : "Ошибка bulk-удаления"); |
| | | 480 | | |
| | 0 | 481 | | if (deleted == 0) |
| | | 482 | | { |
| | 0 | 483 | | _logger.LogWarning( |
| | 0 | 484 | | "Bulk-удаление из индекса {IndexName} завершилось с ошибкой: {DebugInfo}", |
| | 0 | 485 | | _indexName, |
| | 0 | 486 | | response.DebugInformation); |
| | | 487 | | } |
| | | 488 | | |
| | 0 | 489 | | return deleted; |
| | | 490 | | } |
| | 0 | 491 | | catch (Exception ex) |
| | | 492 | | { |
| | 0 | 493 | | LogTransientOrError(ex, "Ошибка bulk-удаления из индекса {IndexName}", _indexName); |
| | 0 | 494 | | _diagnostics.RecordIndex( |
| | 0 | 495 | | OrderSearchIndexOperation.Delete, |
| | 0 | 496 | | 0, |
| | 0 | 497 | | sw.ElapsedMilliseconds, |
| | 0 | 498 | | false, |
| | 0 | 499 | | ex.Message); |
| | 0 | 500 | | return 0; |
| | | 501 | | } |
| | 0 | 502 | | } |
| | | 503 | | |
| | | 504 | | public async Task<OrderSearchIdsResult> SearchOrderIdsAsync( |
| | | 505 | | OrderFilterModel filter, |
| | | 506 | | IReadOnlyList<string>? articleProductKeys = null, |
| | | 507 | | int maxResults = 2000) |
| | | 508 | | { |
| | | 509 | | try |
| | | 510 | | { |
| | 0 | 511 | | var query = BuildSearchQuery(filter, articleProductKeys); |
| | 0 | 512 | | var cappedSize = Math.Clamp(maxResults, 1, 10_000); |
| | | 513 | | |
| | 0 | 514 | | var response = await _client.SearchAsync<OrderSearchDocument>(s => s |
| | 0 | 515 | | .Index(_indexName) |
| | 0 | 516 | | .Query(_ => query) |
| | 0 | 517 | | .Source(sf => sf.Includes(f => f.Field(d => d.Id))) |
| | 0 | 518 | | .Sort(so => so.Descending("_score").Descending(d => d.Id)) |
| | 0 | 519 | | .TrackTotalHits(true) |
| | 0 | 520 | | .Size(cappedSize)); |
| | | 521 | | |
| | 0 | 522 | | if (!response.IsValid) |
| | | 523 | | { |
| | 0 | 524 | | _logger.LogWarning("Поиск по заказам вернул невалидный ответ: {DebugInfo}", response.DebugInformation); |
| | 0 | 525 | | throw new InvalidOperationException( |
| | 0 | 526 | | $"Elasticsearch search failed: {response.ServerError?.Error?.Reason ?? response.DebugInformation}"); |
| | | 527 | | } |
| | | 528 | | |
| | 0 | 529 | | var ids = response.Documents.Select(d => d.Id).ToList(); |
| | 0 | 530 | | var totalHits = response.Total; |
| | 0 | 531 | | var truncated = totalHits > ids.Count; |
| | | 532 | | |
| | 0 | 533 | | return new OrderSearchIdsResult |
| | 0 | 534 | | { |
| | 0 | 535 | | Ids = ids, |
| | 0 | 536 | | TotalHits = totalHits, |
| | 0 | 537 | | MaxResults = cappedSize, |
| | 0 | 538 | | Truncated = truncated |
| | 0 | 539 | | }; |
| | | 540 | | } |
| | 0 | 541 | | catch (Exception ex) |
| | | 542 | | { |
| | 0 | 543 | | LogTransientOrError(ex, "Ошибка при поиске заказов в Elasticsearch"); |
| | 0 | 544 | | throw; |
| | | 545 | | } |
| | 0 | 546 | | } |
| | | 547 | | |
| | | 548 | | public async Task<IReadOnlyList<string>> SuggestArticlesAsync( |
| | | 549 | | string term, |
| | | 550 | | int maxSuggestions = 10, |
| | | 551 | | CancellationToken cancellationToken = default) |
| | | 552 | | { |
| | 0 | 553 | | var normalizedTerm = OrderDataFilterManager.NormalizeArticleForSearch(term); |
| | 0 | 554 | | if (string.IsNullOrWhiteSpace(normalizedTerm)) |
| | | 555 | | { |
| | 0 | 556 | | return Array.Empty<string>(); |
| | | 557 | | } |
| | | 558 | | |
| | | 559 | | try |
| | | 560 | | { |
| | 0 | 561 | | var cappedSize = Math.Clamp(maxSuggestions, 1, 50); |
| | 0 | 562 | | var query = BuildArticleQuery(term, null); |
| | | 563 | | |
| | 0 | 564 | | var response = await _client.SearchAsync<OrderSearchDocument>(s => s |
| | 0 | 565 | | .Index(_indexName) |
| | 0 | 566 | | .Query(_ => query) |
| | 0 | 567 | | .Source(sf => sf.Includes(f => f |
| | 0 | 568 | | .Field(d => d.Article) |
| | 0 | 569 | | .Field(d => d.ProductKey))) |
| | 0 | 570 | | .Sort(so => so.Descending("_score")) |
| | 0 | 571 | | .Size(cappedSize * 5), cancellationToken); |
| | | 572 | | |
| | 0 | 573 | | if (!response.IsValid) |
| | | 574 | | { |
| | 0 | 575 | | _logger.LogWarning( |
| | 0 | 576 | | "Подсказки по артикулу: невалидный ответ ES: {DebugInfo}", response.DebugInformation); |
| | 0 | 577 | | return Array.Empty<string>(); |
| | | 578 | | } |
| | | 579 | | |
| | 0 | 580 | | var suggestions = new List<string>(); |
| | 0 | 581 | | var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | | 582 | | |
| | 0 | 583 | | foreach (var doc in response.Documents) |
| | | 584 | | { |
| | 0 | 585 | | var display = !string.IsNullOrWhiteSpace(doc.ProductKey) ? doc.ProductKey : doc.Article; |
| | 0 | 586 | | if (string.IsNullOrWhiteSpace(display) || !seen.Add(display)) |
| | | 587 | | { |
| | | 588 | | continue; |
| | | 589 | | } |
| | | 590 | | |
| | 0 | 591 | | suggestions.Add(display); |
| | 0 | 592 | | if (suggestions.Count >= cappedSize) |
| | | 593 | | { |
| | | 594 | | break; |
| | | 595 | | } |
| | | 596 | | } |
| | | 597 | | |
| | 0 | 598 | | return suggestions; |
| | | 599 | | } |
| | 0 | 600 | | catch (Exception ex) |
| | | 601 | | { |
| | 0 | 602 | | LogTransientOrError(ex, "Ошибка при получении подсказок по артикулу «{Term}»", term); |
| | 0 | 603 | | return Array.Empty<string>(); |
| | | 604 | | } |
| | 0 | 605 | | } |
| | | 606 | | |
| | | 607 | | private static QueryContainer BuildSearchQuery(OrderFilterModel filter, IReadOnlyList<string>? articleProductKeys = |
| | | 608 | | { |
| | 0 | 609 | | var must = new List<QueryContainer>(); |
| | | 610 | | |
| | 0 | 611 | | if (!string.IsNullOrWhiteSpace(filter.AppStatus) && filter.AppStatus != "Все") |
| | | 612 | | { |
| | 0 | 613 | | must.Add(new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.AppStatusName), Value = filter.AppS |
| | | 614 | | } |
| | | 615 | | |
| | 0 | 616 | | if (!string.IsNullOrWhiteSpace(filter.Supplier) && filter.Supplier != "Все") |
| | | 617 | | { |
| | 0 | 618 | | must.Add(new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.SupplierName), Value = filter.Suppl |
| | | 619 | | } |
| | | 620 | | |
| | 0 | 621 | | if (!string.IsNullOrWhiteSpace(filter.Manufacturer)) |
| | | 622 | | { |
| | 0 | 623 | | must.Add(new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.ManufacturerName), Value = filter.M |
| | | 624 | | } |
| | | 625 | | |
| | 0 | 626 | | if (!string.IsNullOrWhiteSpace(filter.ShipmentWarehouse) && filter.ShipmentWarehouse != "Все") |
| | | 627 | | { |
| | 0 | 628 | | must.Add(new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.ShipmentWarehouseName), Value = fil |
| | | 629 | | } |
| | | 630 | | |
| | 0 | 631 | | if (!string.IsNullOrWhiteSpace(filter.OzonClient) && filter.OzonClient != "Все") |
| | | 632 | | { |
| | 0 | 633 | | must.Add(new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.OzonClientName), Value = filter.Ozo |
| | | 634 | | } |
| | | 635 | | |
| | 0 | 636 | | if (!string.IsNullOrWhiteSpace(filter.Search)) |
| | | 637 | | { |
| | 0 | 638 | | must.Add(BuildGlobalTextQuery(filter.Search.Trim())); |
| | | 639 | | } |
| | | 640 | | |
| | 0 | 641 | | if (!string.IsNullOrWhiteSpace(filter.ShipmentNumber)) |
| | | 642 | | { |
| | 0 | 643 | | must.Add(BuildShipmentNumberQuery(filter.ShipmentNumber)); |
| | | 644 | | } |
| | | 645 | | |
| | 0 | 646 | | if (!string.IsNullOrWhiteSpace(filter.ProductName)) |
| | | 647 | | { |
| | 0 | 648 | | must.Add(new MatchQuery |
| | 0 | 649 | | { |
| | 0 | 650 | | Field = Infer.Field<OrderSearchDocument>(f => f.ProductName), |
| | 0 | 651 | | Query = filter.ProductName.Trim(), |
| | 0 | 652 | | Fuzziness = Fuzziness.Auto |
| | 0 | 653 | | }); |
| | | 654 | | } |
| | | 655 | | |
| | 0 | 656 | | var article = string.IsNullOrWhiteSpace(filter.Article) ? filter.Article2 : filter.Article; |
| | 0 | 657 | | if (!string.IsNullOrWhiteSpace(article) || articleProductKeys is { Count: > 0 }) |
| | | 658 | | { |
| | 0 | 659 | | must.Add(BuildArticleQuery(article, articleProductKeys)); |
| | | 660 | | } |
| | | 661 | | |
| | 0 | 662 | | if (must.Count == 0) |
| | | 663 | | { |
| | 0 | 664 | | return new MatchAllQuery(); |
| | | 665 | | } |
| | | 666 | | |
| | 0 | 667 | | return new BoolQuery { Must = must }; |
| | | 668 | | } |
| | | 669 | | |
| | | 670 | | private static QueryContainer BuildGlobalTextQuery(string term) |
| | | 671 | | { |
| | 5 | 672 | | var trimmed = term.Trim(); |
| | 5 | 673 | | if (string.IsNullOrWhiteSpace(trimmed)) |
| | | 674 | | { |
| | 0 | 675 | | return new MatchNoneQuery(); |
| | | 676 | | } |
| | | 677 | | |
| | 5 | 678 | | if (LooksLikeShipmentNumber(trimmed)) |
| | | 679 | | { |
| | 3 | 680 | | var normalized = OrderDataFilterManager.NormalizeShipmentNumberForSearch(trimmed); |
| | 3 | 681 | | var phrase = string.IsNullOrWhiteSpace(normalized) ? trimmed : normalized; |
| | 3 | 682 | | return new BoolQuery |
| | 3 | 683 | | { |
| | 3 | 684 | | Should = new QueryContainer[] |
| | 3 | 685 | | { |
| | 3 | 686 | | new TermQuery |
| | 3 | 687 | | { |
| | 3 | 688 | | Field = Infer.Field<OrderSearchDocument>(f => f.ShipmentNumber), |
| | 3 | 689 | | Value = trimmed, |
| | 3 | 690 | | Boost = 5.0 |
| | 3 | 691 | | }, |
| | 3 | 692 | | new MatchPhraseQuery |
| | 3 | 693 | | { |
| | 3 | 694 | | Field = Infer.Field<OrderSearchDocument>(f => f.ShipmentNumber), |
| | 3 | 695 | | Query = phrase, |
| | 3 | 696 | | Boost = 10.0 |
| | 3 | 697 | | }, |
| | 3 | 698 | | BuildScanitTerm(trimmed) |
| | 3 | 699 | | }, |
| | 3 | 700 | | MinimumShouldMatch = 1 |
| | 3 | 701 | | }; |
| | | 702 | | } |
| | | 703 | | |
| | 2 | 704 | | return trimmed.Length switch |
| | 2 | 705 | | { |
| | 1 | 706 | | <= 3 => BuildShortGlobalTextQuery(trimmed), |
| | 1 | 707 | | <= 7 => BuildMediumGlobalTextQuery(trimmed), |
| | 0 | 708 | | _ => BuildFullGlobalTextQuery(trimmed) |
| | 2 | 709 | | }; |
| | | 710 | | } |
| | | 711 | | |
| | | 712 | | /// <summary>Короткий токен (≤3): только точные поля, без ngram — иначе тысячи ложных совпадений.</summary> |
| | | 713 | | private static QueryContainer BuildShortGlobalTextQuery(string term) => |
| | 1 | 714 | | new BoolQuery |
| | 1 | 715 | | { |
| | 1 | 716 | | Should = new QueryContainer[] |
| | 1 | 717 | | { |
| | 1 | 718 | | new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.ShipmentNumber), Value = term, Boost = 5 |
| | 1 | 719 | | new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.Article), Value = term, Boost = 5.0 }, |
| | 1 | 720 | | new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.ProductKey), Value = term, Boost = 4.0 } |
| | 1 | 721 | | }, |
| | 1 | 722 | | MinimumShouldMatch = 1 |
| | 1 | 723 | | }; |
| | | 724 | | |
| | | 725 | | /// <summary>4–7 символов: ngram по артикулу, без ngram по наименованию товара.</summary> |
| | | 726 | | private static QueryContainer BuildMediumGlobalTextQuery(string term) => |
| | 1 | 727 | | new BoolQuery |
| | 1 | 728 | | { |
| | 1 | 729 | | Should = new QueryContainer[] |
| | 1 | 730 | | { |
| | 1 | 731 | | new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.ShipmentNumber), Value = term, Boost = 5 |
| | 1 | 732 | | new MatchPhraseQuery |
| | 1 | 733 | | { |
| | 1 | 734 | | Field = Infer.Field<OrderSearchDocument>(f => f.ShipmentNumber), |
| | 1 | 735 | | Query = term, |
| | 1 | 736 | | Boost = 4.5 |
| | 1 | 737 | | }, |
| | 1 | 738 | | new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.Article), Value = term, Boost = 5.0 }, |
| | 1 | 739 | | new MatchQuery { Field = Infer.Field<OrderSearchDocument>(f => f.Article.Suffix("ngram")), Query = term, |
| | 1 | 740 | | new MatchQuery { Field = Infer.Field<OrderSearchDocument>(f => f.ProductKey.Suffix("ngram")), Query = te |
| | 1 | 741 | | new MatchQuery |
| | 1 | 742 | | { |
| | 1 | 743 | | Field = Infer.Field<OrderSearchDocument>(f => f.ProductName), |
| | 1 | 744 | | Query = term, |
| | 1 | 745 | | Fuzziness = Fuzziness.Auto, |
| | 1 | 746 | | Boost = 1.0 |
| | 1 | 747 | | } |
| | 1 | 748 | | }, |
| | 1 | 749 | | MinimumShouldMatch = 1 |
| | 1 | 750 | | }; |
| | | 751 | | |
| | | 752 | | /// <summary>Длинный глобальный поиск: полный набор полей.</summary> |
| | | 753 | | private static QueryContainer BuildFullGlobalTextQuery(string term) => |
| | 0 | 754 | | new BoolQuery |
| | 0 | 755 | | { |
| | 0 | 756 | | Should = new QueryContainer[] |
| | 0 | 757 | | { |
| | 0 | 758 | | new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.ShipmentNumber), Value = term, Boost = 5 |
| | 0 | 759 | | new MatchPhraseQuery |
| | 0 | 760 | | { |
| | 0 | 761 | | Field = Infer.Field<OrderSearchDocument>(f => f.ShipmentNumber), |
| | 0 | 762 | | Query = term, |
| | 0 | 763 | | Boost = 4.5 |
| | 0 | 764 | | }, |
| | 0 | 765 | | new TermQuery { Field = Infer.Field<OrderSearchDocument>(f => f.Article), Value = term, Boost = 5.0 }, |
| | 0 | 766 | | new MatchQuery { Field = Infer.Field<OrderSearchDocument>(f => f.Article.Suffix("ngram")), Query = term, |
| | 0 | 767 | | new MatchQuery { Field = Infer.Field<OrderSearchDocument>(f => f.ProductKey.Suffix("ngram")), Query = te |
| | 0 | 768 | | new MatchQuery |
| | 0 | 769 | | { |
| | 0 | 770 | | Field = Infer.Field<OrderSearchDocument>(f => f.ProductName), |
| | 0 | 771 | | Query = term, |
| | 0 | 772 | | Fuzziness = Fuzziness.Auto, |
| | 0 | 773 | | Boost = 1.0 |
| | 0 | 774 | | }, |
| | 0 | 775 | | new MatchQuery { Field = Infer.Field<OrderSearchDocument>(f => f.ProductName.Suffix("ngram")), Query = t |
| | 0 | 776 | | }, |
| | 0 | 777 | | MinimumShouldMatch = 1 |
| | 0 | 778 | | }; |
| | | 779 | | |
| | | 780 | | private static bool LooksLikeShipmentNumber(string term) |
| | | 781 | | { |
| | 5 | 782 | | if (string.IsNullOrWhiteSpace(term)) |
| | | 783 | | { |
| | 0 | 784 | | return false; |
| | | 785 | | } |
| | | 786 | | |
| | 5 | 787 | | var t = term.Trim(); |
| | 5 | 788 | | if (t.Contains('-', StringComparison.Ordinal) && t.Any(char.IsDigit)) |
| | | 789 | | { |
| | 2 | 790 | | return true; |
| | | 791 | | } |
| | | 792 | | |
| | 3 | 793 | | if (t.StartsWith("СП", StringComparison.OrdinalIgnoreCase) |
| | 3 | 794 | | || t.StartsWith("ВУ", StringComparison.OrdinalIgnoreCase)) |
| | | 795 | | { |
| | 0 | 796 | | return true; |
| | | 797 | | } |
| | | 798 | | |
| | 3 | 799 | | var normalized = OrderDataFilterManager.NormalizeShipmentNumberForSearch(t); |
| | 3 | 800 | | return normalized.Length >= 6 && normalized.Count(char.IsDigit) >= 4; |
| | | 801 | | } |
| | | 802 | | |
| | | 803 | | /// <summary>Точное совпадение со ScanIt без учёта регистра (сканер и ручной ввод дают разный регистр).</summary> |
| | | 804 | | private static QueryContainer BuildScanitTerm(string value) => |
| | 9 | 805 | | new TermQuery |
| | 9 | 806 | | { |
| | 9 | 807 | | Field = Infer.Field<OrderSearchDocument>(f => f.Scanit), |
| | 9 | 808 | | Value = value.Trim(), |
| | 9 | 809 | | CaseInsensitive = true, |
| | 9 | 810 | | Boost = 10.0 |
| | 9 | 811 | | }; |
| | | 812 | | |
| | | 813 | | private static QueryContainer BuildShipmentNumberQuery(string shipmentNumber) |
| | | 814 | | { |
| | 5 | 815 | | var parts = OrderDataFilterManager.GetShipmentNumbersFromFilter(shipmentNumber); |
| | 5 | 816 | | if (parts.Count == 0) |
| | | 817 | | { |
| | 0 | 818 | | parts = new List<string> { shipmentNumber }; |
| | | 819 | | } |
| | | 820 | | |
| | 5 | 821 | | var should = new List<QueryContainer>(); |
| | 22 | 822 | | foreach (var part in parts) |
| | | 823 | | { |
| | 6 | 824 | | var normalized = OrderDataFilterManager.NormalizeShipmentNumberForSearch(part); |
| | 6 | 825 | | if (string.IsNullOrWhiteSpace(normalized)) |
| | | 826 | | { |
| | | 827 | | continue; |
| | | 828 | | } |
| | | 829 | | |
| | 6 | 830 | | should.Add(BuildScanitTerm(normalized)); |
| | | 831 | | |
| | | 832 | | // match_phrase на standard-поле покрывает целый номер. Для фрагмента из пяти и более |
| | | 833 | | // символов добавляем keyword-wildcard, чтобы поведение совпадало с MySQL Contains: |
| | | 834 | | // например, «44568» находит «63044568-0016-2». Более короткие фрагменты намеренно |
| | | 835 | | // не раскрываем wildcard-ом: они дают слишком широкую выдачу. |
| | 6 | 836 | | should.Add(new MatchPhraseQuery |
| | 6 | 837 | | { |
| | 6 | 838 | | Field = Infer.Field<OrderSearchDocument>(f => f.ShipmentNumber), |
| | 6 | 839 | | Query = normalized, |
| | 6 | 840 | | Boost = 10.0 |
| | 6 | 841 | | }); |
| | | 842 | | |
| | 6 | 843 | | if (normalized.Length >= 5) |
| | | 844 | | { |
| | 6 | 845 | | should.Add(new WildcardQuery |
| | 6 | 846 | | { |
| | 6 | 847 | | Field = Infer.Field<OrderSearchDocument>(f => f.ShipmentNumber.Suffix("keyword")), |
| | 6 | 848 | | Value = $"*{normalized}*", |
| | 6 | 849 | | CaseInsensitive = true, |
| | 6 | 850 | | Boost = 2.0 |
| | 6 | 851 | | }); |
| | | 852 | | } |
| | | 853 | | } |
| | | 854 | | |
| | 5 | 855 | | if (should.Count == 0) |
| | | 856 | | { |
| | 0 | 857 | | return new MatchNoneQuery(); |
| | | 858 | | } |
| | | 859 | | |
| | 5 | 860 | | return new BoolQuery { Should = should, MinimumShouldMatch = 1 }; |
| | | 861 | | } |
| | | 862 | | |
| | | 863 | | private static QueryContainer BuildArticleQuery(string? article, IReadOnlyList<string>? articleProductKeys) |
| | | 864 | | { |
| | 3 | 865 | | var terms = CollectArticleSearchTerms(article, articleProductKeys) |
| | 3 | 866 | | .Select(OrderDataFilterManager.NormalizeArticleForSearch) |
| | 4 | 867 | | .Where(term => !string.IsNullOrWhiteSpace(term)) |
| | 3 | 868 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 3 | 869 | | .ToList(); |
| | | 870 | | |
| | 3 | 871 | | if (terms.Count == 0) |
| | | 872 | | { |
| | 0 | 873 | | return new MatchNoneQuery(); |
| | | 874 | | } |
| | | 875 | | |
| | 3 | 876 | | var should = new List<QueryContainer>(); |
| | 12 | 877 | | foreach (var term in terms) |
| | | 878 | | { |
| | 3 | 879 | | var normalizedTerm = term.ToLowerInvariant(); |
| | | 880 | | |
| | | 881 | | // Wildcard *term* — честное вхождение подпоследовательности в ЛЮБОЙ позиции |
| | | 882 | | // (как SQL LIKE '%term%'), по индексированному терму: без ngram-фаззи и без |
| | | 883 | | // зависимости от заполненности NormalizedArticleKey. |
| | 3 | 884 | | var wildcardValue = $"*{normalizedTerm}*"; |
| | 3 | 885 | | should.Add(new WildcardQuery |
| | 3 | 886 | | { |
| | 3 | 887 | | Field = Infer.Field<OrderSearchDocument>(f => f.NormalizedArticleKey), |
| | 3 | 888 | | Value = wildcardValue, |
| | 3 | 889 | | Boost = 11.0 |
| | 3 | 890 | | }); |
| | 3 | 891 | | should.Add(new WildcardQuery |
| | 3 | 892 | | { |
| | 3 | 893 | | Field = Infer.Field<OrderSearchDocument>(f => f.Article), |
| | 3 | 894 | | Value = wildcardValue, |
| | 3 | 895 | | Boost = 6.0 |
| | 3 | 896 | | }); |
| | 3 | 897 | | should.Add(new WildcardQuery |
| | 3 | 898 | | { |
| | 3 | 899 | | Field = Infer.Field<OrderSearchDocument>(f => f.ProductKey), |
| | 3 | 900 | | Value = wildcardValue, |
| | 3 | 901 | | Boost = 5.0 |
| | 3 | 902 | | }); |
| | | 903 | | } |
| | | 904 | | |
| | 3 | 905 | | return new BoolQuery { Should = should, MinimumShouldMatch = 1 }; |
| | | 906 | | } |
| | | 907 | | |
| | | 908 | | private static List<string> CollectArticleSearchTerms(string? article, IReadOnlyList<string>? articleProductKeys) |
| | | 909 | | { |
| | 3 | 910 | | var terms = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | | 911 | | |
| | 3 | 912 | | if (!string.IsNullOrWhiteSpace(article)) |
| | | 913 | | { |
| | 3 | 914 | | terms.Add(article.Trim()); |
| | | 915 | | } |
| | | 916 | | |
| | 3 | 917 | | if (articleProductKeys is { Count: > 0 }) |
| | | 918 | | { |
| | 4 | 919 | | foreach (var key in articleProductKeys) |
| | | 920 | | { |
| | 1 | 921 | | if (!string.IsNullOrWhiteSpace(key)) |
| | | 922 | | { |
| | 1 | 923 | | terms.Add(key.Trim()); |
| | | 924 | | } |
| | | 925 | | } |
| | | 926 | | } |
| | | 927 | | |
| | 3 | 928 | | return terms.ToList(); |
| | | 929 | | } |
| | | 930 | | |
| | | 931 | | private static string? ResolveNormalizedArticleKey(OrderSearchDocument document) |
| | | 932 | | { |
| | 0 | 933 | | var fromProductKey = OrderDataFilterManager.NormalizeArticleForSearch(document.ProductKey); |
| | 0 | 934 | | if (!string.IsNullOrWhiteSpace(fromProductKey)) |
| | | 935 | | { |
| | 0 | 936 | | return fromProductKey.ToLowerInvariant(); |
| | | 937 | | } |
| | | 938 | | |
| | 0 | 939 | | var fromArticle = OrderDataFilterManager.NormalizeArticleForSearch(document.Article); |
| | 0 | 940 | | return string.IsNullOrWhiteSpace(fromArticle) ? null : fromArticle.ToLowerInvariant(); |
| | | 941 | | } |
| | | 942 | | |
| | | 943 | | private void LogTransientOrError(Nest.IResponse response, string messageTemplate, params object?[] args) |
| | | 944 | | { |
| | 0 | 945 | | if (IsTransientElasticsearchResponse(response)) |
| | | 946 | | { |
| | 0 | 947 | | _logger.LogWarning(messageTemplate, args); |
| | | 948 | | } |
| | | 949 | | else |
| | | 950 | | { |
| | 0 | 951 | | _logger.LogError(messageTemplate, args); |
| | | 952 | | } |
| | 0 | 953 | | } |
| | | 954 | | |
| | | 955 | | private void LogTransientOrError(Exception ex, string messageTemplate, params object?[] args) |
| | | 956 | | { |
| | 0 | 957 | | if (IsTransientElasticsearchException(ex)) |
| | | 958 | | { |
| | 0 | 959 | | _logger.LogWarning(ex, messageTemplate, args); |
| | | 960 | | } |
| | | 961 | | else |
| | | 962 | | { |
| | 0 | 963 | | _logger.LogError(ex, messageTemplate, args); |
| | | 964 | | } |
| | 0 | 965 | | } |
| | | 966 | | |
| | | 967 | | private static bool IsTransientElasticsearchResponse(Nest.IResponse response) |
| | | 968 | | { |
| | 0 | 969 | | if (response.OriginalException != null && IsTransientElasticsearchException(response.OriginalException)) |
| | | 970 | | { |
| | 0 | 971 | | return true; |
| | | 972 | | } |
| | | 973 | | |
| | 0 | 974 | | var reason = response.ServerError?.Error?.Reason ?? string.Empty; |
| | 0 | 975 | | if (reason.Contains("all shards failed", StringComparison.OrdinalIgnoreCase) |
| | 0 | 976 | | || reason.Contains("node_not_connected_exception", StringComparison.OrdinalIgnoreCase)) |
| | | 977 | | { |
| | 0 | 978 | | return true; |
| | | 979 | | } |
| | | 980 | | |
| | 0 | 981 | | var debugInfo = response.DebugInformation ?? string.Empty; |
| | 0 | 982 | | return debugInfo.Contains("all shards failed", StringComparison.OrdinalIgnoreCase) |
| | 0 | 983 | | || debugInfo.Contains("Connection refused", StringComparison.OrdinalIgnoreCase) |
| | 0 | 984 | | || debugInfo.Contains("unsuccessful product check", StringComparison.OrdinalIgnoreCase) |
| | 0 | 985 | | || debugInfo.Contains("node_not_connected_exception", StringComparison.OrdinalIgnoreCase); |
| | | 986 | | } |
| | | 987 | | |
| | | 988 | | private static bool IsTransientElasticsearchException(Exception ex) |
| | | 989 | | { |
| | 0 | 990 | | for (Exception? current = ex; current != null; current = current.InnerException) |
| | | 991 | | { |
| | 0 | 992 | | if (current is System.Net.Http.HttpRequestException or System.Net.Sockets.SocketException or Elasticsearch.N |
| | | 993 | | { |
| | 0 | 994 | | return true; |
| | | 995 | | } |
| | | 996 | | |
| | 0 | 997 | | if (current.Message.Contains("all shards failed", StringComparison.OrdinalIgnoreCase) |
| | 0 | 998 | | || current.Message.Contains("Connection refused", StringComparison.OrdinalIgnoreCase) |
| | 0 | 999 | | || current.Message.Contains("unsuccessful product check", StringComparison.OrdinalIgnoreCase) |
| | 0 | 1000 | | || current.Message.Contains("node_not_connected_exception", StringComparison.OrdinalIgnoreCase)) |
| | | 1001 | | { |
| | 0 | 1002 | | return true; |
| | | 1003 | | } |
| | | 1004 | | } |
| | | 1005 | | |
| | 0 | 1006 | | return false; |
| | | 1007 | | } |
| | | 1008 | | } |