合并云商品分支到 master 并适配插件结构

This commit is contained in:
chfei committed 2026-11-02 10:01:33 +08:00
commit 1fa91a9cfb
15 files changed
+968 -48

No files matched your search

@@ -16,7 +16,7 @@ namespace Store.Modules.CloudProduct.Services
public interface IOpenSearchService : ISingletonDependency
{
Task AddDocumentAsync(GoodsSearchDocument document);
Task BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents);
Task<long[]> BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents);
Task<bool> ClearIndexAsync();
Task<long> CountDocumentsAsync();
Task<bool> CreateIndexAsync();
@@ -26,7 +26,7 @@ namespace Store.Modules.CloudProduct.Services
Task<bool> IndexExistsAsync();
Task<bool> IsIndexMappingHealthyAsync();
Task RefreshIndexAsync();
Task<long> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList);
Task<long[]> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList);
Task<(long Total, List<GoodsSearchDocument> Documents)> SearchByTitleAsync(GoodsSearchRequest request, GoodsSearchSortBy sortBy = GoodsSearchSortBy.Relevance);
}
@@ -41,10 +41,15 @@ namespace Store.Modules.CloudProduct.Services
// 批量写入/建索引/删除索引等管理类操作超时(数据量大时需要更长,可挪到配置文件)
private static readonly TimeSpan AdminTimeout = TimeSpan.FromSeconds(30);
private readonly ILogger<OpenSearchService> _logger;
private readonly IFreeSql _database;
private readonly GoodsIndexLock _indexLock;
public OpenSearchService([FromKeyedServices("CloudProduct")] PluginContext context,ILogger<OpenSearchService> logger)
{
var config = context.Configuration.GetSection("Search");
public OpenSearchService([FromKeyedServices("CloudProduct")] PluginContext context, ILogger<OpenSearchService> logger,
[FromKeyedServices("CloudProductConnection")] IFreeSql database, GoodsIndexLock indexLock)
{
_database = database;
_indexLock = indexLock;
var config = context.Configuration.GetSection("Search");
_nodeUrl = config.GetValue<string>("Url") ?? "";
_indexName = config.GetValue<string>("IndexName") ?? "";
_client = CreateClient();
@@ -206,12 +211,18 @@ namespace Store.Modules.CloudProduct.Services
/// <summary>
/// ============ 3.1 批量写入商品搜索文档(存在则覆盖) ============
/// </summary>
public async Task BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents)
public async Task<long[]> BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents)
{
if (documents == null) throw new ArgumentNullException(nameof(documents));
var list = documents.ToList();
if (list.Count == 0) return;
if (list.Count == 0) return [];
await using var lease = await _indexLock.AcquireAsync();
var ids = list.Select(x => x.Id).Distinct().ToArray();
var blocked = (await _database.Select<GoodsViolationEntity>()
.Where(x => ids.Contains(x.GoodsId)).ToListAsync(x => x.GoodsId)).ToHashSet();
list = list.Where(x => !blocked.Contains(x.Id)).ToList();
if (list.Count == 0) return [];
// 确保索引已按 IK 分词映射创建,否则中文分词无效
await CreateIndexAsync();
@@ -222,19 +233,20 @@ namespace Store.Modules.CloudProduct.Services
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout))
);
if (!bulkResponse.IsValid)
if (!bulkResponse.IsValid || bulkResponse.Errors)
{
throw new AppException("写入 OpenSearch 失败: " + bulkResponse.DebugInformation);
}
// 刷新索引,保证数据立即可搜索(仅用于演示,生产环境不建议频繁 Refresh)
await RefreshIndexAsync();
return list.Select(x => x.Id).Distinct().ToArray();
}
/// <summary>
/// ============ 3.2 根据数据库商品重建搜索索引 ============
/// </summary>
public async Task<long> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList)
public async Task<long[]> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList)
{
if (goodsList == null) throw new ArgumentNullException(nameof(goodsList));
@@ -242,6 +254,8 @@ namespace Store.Modules.CloudProduct.Services
.Where(x => x != null && x.GoodsId > 0)
.Select(x => new GoodsSearchDocument
{
Platform = x.Platform,
ThumbUrl = x.ThumbUrl,
Id = x.GoodsId,
Title = x.Title ?? string.Empty,
CatId1 = x.CatId1,
@@ -253,10 +267,7 @@ namespace Store.Modules.CloudProduct.Services
})
.ToList();
if (documents.Count == 0) return 0;
await BulkIndexGoodsAsync(documents);
return documents.Count;
return await BulkIndexGoodsAsync(documents);
}
/// <summary>
@@ -271,7 +282,8 @@ namespace Store.Modules.CloudProduct.Services
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
if (!exists.Exists)
{
return;
if (exists.ApiCall?.HttpStatusCode == 404) return;
throw new AppException("检查 OpenSearch 索引失败: " + exists.DebugInformation);
}
var response = await _client.BulkAsync(b =>
@@ -284,7 +296,9 @@ namespace Store.Modules.CloudProduct.Services
return b;
});
if (!response.IsValid)
if (response.ApiCall?.HttpStatusCode is not (>= 200 and < 300)
|| response.Items.Count != list.Count
|| response.Items.Any(x => x.Status != 404 && (x.Error != null || x.Status < 200 || x.Status >= 300)))
{
throw new AppException("删除 OpenSearch 文档失败: " + response.DebugInformation);
}
@@ -298,6 +312,9 @@ namespace Store.Modules.CloudProduct.Services
public async Task AddDocumentAsync(GoodsSearchDocument document)
{
if (document == null) throw new ArgumentNullException(nameof(document));
await using var lease = await _indexLock.AcquireAsync();
if (await _database.Select<GoodsViolationEntity>().AnyAsync(x => x.GoodsId == document.Id))
throw new AppException("违规商品不能写入搜索索引");
var response = await _client.IndexAsync(document, i => i
.Index(_indexName)
@@ -524,6 +541,7 @@ namespace Store.Modules.CloudProduct.Services
/// </summary>
public async Task<bool> ClearIndexAsync()
{
await using var lease = await _indexLock.AcquireAsync();
var existsResponse = await _client.Indices.ExistsAsync(_indexName, d => d
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
if (!existsResponse.Exists)
@@ -541,7 +559,10 @@ namespace Store.Modules.CloudProduct.Services
}
Console.WriteLine($"索引 {_indexName} 已删除");
return await CreateIndexAsync();
var created = await CreateIndexAsync();
await _database.Update<GoodsEntity>().Set(x => x.IsSegmented, (byte)0)
.Where(x => x.Status == 0).ExecuteAffrowsAsync();
return created;
}
}
}