c# .net core2.1使用NEST包对es进行嵌套排序查询
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SearchList.Core.ElasticSearchs;
using SearchList.Core.Entity.Items;
using SearchList.Core.Entity.Listings;
namespace ExpandSearchListService.Controllers
{
[ApiController]
public class TestController : ControllerBase
{
[HttpGet]
[Route("[controller]/TestSortNested")]
public void TestSortNested()
{
var query = new List<Func<QueryContainerDescriptor<BundleSku>, QueryContainer>>();
//当数据量多的时候用来排序的字段必须加上索引,不然会报错
DateTime dt1 = System.DateTime.Now;
var client = EsClientProvider.GetClientByIndex(SearchIndex.testindex);
var listings = client.Search<BundleSku>(s => s
.Query(q => q.Bool(b => b.Must(query))
).Sort(GetListingSortBy())).Documents;
var result = client.Search<BundleSku>(s => s
.Query(q => q.Bool(b => b.Must(query))
).Size(10).From(0).Sort(GetListingSortBy())
);
}
private Func<SortDescriptor<BundleSku>, IPromise<IList<ISort>>> GetListingSortBy()
{
//排序
Func<SortDescriptor<BundleSku>, IPromise<IList<ISort>>> sortDesc = sd =>
{
sd.Field(f =>
{
f.Order(Nest.SortOrder.Descending);
f.Nested(a => {
a.Filter(b => b.Term(c => c.Field("newProductPlatformInfos.platformType").Value(0)));
a.Path(new Field("newProductPlatformInfos"));
return a;
});
f.Field("newProductPlatformInfos.audited");
return f;
});
return sd;
};
return sortDesc;
}
}
[ElasticsearchType(IdProperty = "Id")]
public class BundleSku : ItemCommon
{
public Guid Id { get; set; }
[Keyword]
public string Code { get; set; }
[Nested]
public List<NewProductPlatformInfo> NewProductPlatformInfos { get; set; }
public List<ListingSiteInfo> ListingSiteInfos { get; set; }
}
public class NewProductPlatformInfo
{
/// <summary>
/// 平台类型
/// </summary>
public int PlatformType { get; set; }
/// <summary>
/// 审核时间
/// </summary>
public DateTime? Audited { get; set; }
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构