【问题标题】:Nest Elasticsearch search for null valueNest Elasticsearch 搜索空值
【发布时间】:2016-02-29 15:31:05
【问题描述】:

使用 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");

但没有任何成功。 有任何想法吗 ?谢谢你:)

【问题讨论】:

  • 它是否具有字符串值"NULL",或者该字段是否应该为空,即缺失?
  • 这个字段存在,当我把这个文档放到elasticsearch中时,值为"" (string.Empty)
  • 旧的,但仅供将来参考 - 它是无条件查询功能,可以使用 .Strict() /now obsolete/ 禁用它

标签: c# elasticsearch nest


【解决方案1】:

对于 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"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

【讨论】:

    【解决方案2】:

    这是我能找到的最好的一个

     Filter<Document>.Query(q1 =>q1.Bool(q2 => q2
                                   .MustNot(q3 => q3
                                   .Exists(q4 => q4
                                   .Field(q5 => q5.Field)))));
    

    希望有更好的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      相关资源
      最近更新 更多