Elasticsearch聚合查询转Elastic.Clients.Elasticsearch 8.x .NET客户端报错求助
问题:Elastic.Clients.Elasticsearch 8.x聚合代码编译失败(.Terms无效)
原始Elasticsearch查询
GET stediresponses/_search { "size": 0, "query": { "bool": { "must": [ { "term": { "parentId": { "value": "16fda1d8-2e9f-402e-ac76-0d01615b371f" } } }, { "term": { "responseType": { "value": "835" } } } ] } }, "aggs": { "practitioner_sum": { "terms": { "field": "practitionerId" }, "aggs": { "total_payment": { "sum": { "field": "totalActualProviderPaymentAmount" } } } } } }
环境信息
- 使用的命名空间:
using Elastic.Clients.Elasticsearch; using Elastic.Clients.Elasticsearch.Aggregations; using Elastic.Clients.Elasticsearch.QueryDsl;
- 文档实体
StediClaimResponse结构:
{ "source": "Blue Cross and Blue Shield of Texas", "claimId": "", "fhirClaimId": "", "responseType": "835", "transactionId": "", "status": "Payment", "statusCode": "1", "statusCategory": "", "statusCategoryCode": "", "controlNumber": "", "tradingPartnerServiceId": "", "tradingPartnerClaimNumber": "", "messages": [], "aiSummary": "", "isRejected": false, "information837": {}, "totalActualProviderPaymentAmount": 448, "practitionerId": "-", "practitionerFhirId": "-", "practitionerName": "-", "practitionerPhoto": "", "practitionerPhotoTransparent": "", "id": "01J4DB4P7D2BJ69FAQX75SPEHT", "parentId": "", "dateCreated": "2024-08-04T00:03:01.4882155Z", "dateModified": "2024-08-04T00:03:01.4882787Z", "elementTypeId": 19, "isDeleting": false, "dateCreatedDate": "8/4/2024", "dateModifiedDate": "8/4/2024" }
尝试的代码(编译报错.Terms无效)
var searchResponse = await _elasticSearchClient.SearchAsync<StediClaimResponse>( s => s .Aggregations( a => a .Terms( "practitioner_sum", t => t .Field( "practitionerId" ) .Aggregations( aa => aa .Sum( "total_payment", sa => sa .Field( "totalActualProviderPaymentAmount" ) ) ) ) ) );
解决方案
Elastic.Clients.Elasticsearch 8.x的聚合API写法与旧版NEST不同,需匹配正确的重载方法,同时要补充原始查询中的size=0和bool查询条件。正确代码如下:
var searchResponse = await _elasticSearchClient.SearchAsync<StediClaimResponse>(s => s .Size(0) // 对应原始查询的size:0 .Query(q => q .Bool(b => b .Must(must => must .Term(t => t.Field(f => f.parentId).Value("16fda1d8-2e9f-402e-ac76-0d01615b371f")) .Term(t => t.Field(f => f.responseType).Value("835")) ) ) ) .Aggregations(a => a .Terms("practitioner_sum", t => t .Field(f => f.practitionerId) // 推荐用强类型字段,也可改用字符串"practitionerId" .Aggregations(aa => aa .Sum("total_payment", sa => sa .Field(f => f.totalActualProviderPaymentAmount) ) ) ) ) );
错误原因说明
- 8.x客户端中
Aggregations下的Terms方法需要正确匹配重载,之前的写法因重载匹配失败导致编译报错,使用强类型字段绑定不仅能解决错误,还能获得类型安全检查。 - 尝试的代码缺失了原始查询中的
size=0和bool过滤条件,补充后才能完全对齐原始ES查询逻辑。
内容的提问来源于stack exchange,提问作者Chris Parker
相关产品推荐
相关产品推荐

