Nest Elasticsearch 搜索空值
本文关键字:空值 搜索 Elasticsearch Nest | 更新日期: 2023-09-27 18:36:47
使用 NEST (1.7.1) 我有一个特定的搜索,其中一个字段应该与一些值集合匹配,或者这个字段应该为空。似乎很复杂,但我无法创建此查询,因此当我不按此字段过滤文档时,结果将与结果相同。
公文:
public class Document
{
...
[ElasticProperty(Index = FieldIndexOption.NotAnalyzed)]
public string Field{ get; set; }
}
查询以匹配给定集合中的任何值:
Filter<Document>.Query(q => q.Terms(p=> p.Field, matchingCollection));
为了匹配那些将 NULL 设置为字段的文档,我试图添加:
matchingCollection.Add(string.Empty);
matchingCollection.Add("NULL");
但没有任何成功。有什么想法吗?谢谢:)
对于 NEST 1.x,如下所示
client.Search<Document>(x => x
.Query(q => q
.Terms(f => f.Field, new [] { "term1", "term2", "term3" }) || q
.Filtered(fq => fq
.Filter(fqf => fqf
.Missing(f => f.Field)
)
)
)
);
生成以下查询
{
"query": {
"bool": {
"should": [
{
"terms": {
"field": [
"term1",
"term2",
"term3"
]
}
},
{
"filtered": {
"filter": {
"missing": {
"field": "Field"
}
}
}
}
]
}
}
}
对于 NEST 2.x 及更高版本,类似
client.Search<Document>(x => x
.Query(q => q
.Terms(t => t
.Field(f => f.Field)
.Terms("term1","term2","term3")
) || !q
.Exists(e => e
.Field(f => f.Field)
)
)
);
生成以下查询
{
"query": {
"bool": {
"should": [
{
"terms": {
"field": [
"term1",
"term2",
"term3"
]
}
},
{
"bool": {
"must_not": [
{
"exists": {
"field": "field"
}
}
]
}
}
]
}
}
}
这是我
能找到的最好的一个
Filter<Document>.Query(q1 =>q1.Bool(q2 => q2
.MustNot(q3 => q3
.Exists(q4 => q4
.Field(q5 => q5.Field)))));
希望有更好的答案。