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; }
}

}

posted @ 2022-08-12 14:45  元点  阅读(767)  评论(0编辑  收藏  举报