Elastic.Clients.Elasticsearch多Must条件查询异常问题咨询
解决Elastic.Clients.Elasticsearch C# API多条件精确匹配问题
你的代码问题出在.Must()内的链式调用写法上——新版Elastic.Clients.Elasticsearch的Fluent API中,连续调用.Term()会覆盖之前的查询条件,最终只有最后一个periodType的Term查询生效,所以只会返回匹配该字段的记录。
要实现多条件同时满足的逻辑与查询,有两种正确写法:
写法一:在.Must()中传入多个Term查询参数
var response = await client.SearchAsync<EffectSerie>(s => s .Index(_indexName) .Query(q => q .Bool(b => b .Must( t => t.Term(f => f.startDate, "2023-11-01"), t => t.Term(f => f.endDate, "2023-11-02"), t => t.Term(f => f.periodType, 4) ) ) ) );
写法二:多次调用.Must()添加单个查询条件
var response = await client.SearchAsync<EffectSerie>(s => s .Index(_indexName) .Query(q => q .Bool(b => b .Must(t => t.Term(f => f.startDate, "2023-11-01")) .Must(t => t.Term(f => f.endDate, "2023-11-02")) .Must(t => t.Term(f => f.periodType, 4)) ) ) );
额外注意事项
如果startDate和endDate是Elasticsearch中的日期类型字段,建议直接传入DateTime对象而非字符串,API会自动处理正确的序列化格式,避免解析错误:
.Term(f => f.startDate, new DateTime(2023, 11, 1))
内容的提问来源于stack exchange,提问作者Eric Herlitz
相关产品推荐
相关产品推荐

