2016-02-29 97 views
1

使用NEST(1.7.1)我有一个特定的搜索,其中一个字段应该匹配一些值的集合或者该字段应该为空。似乎trival,但我不能创建这个查询,所以结果将是相同的,因为当我没有过滤这个领域的文件。Nest Elasticsearch搜索空值

文件:

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

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

+0

它具有字符串值“NULL”吗,还是该字段应为null即丢失? –

+0

这个字段存在,当我把这个文件给elasticsearch时,值是“”(string.Empty) –

+0

旧的,但仅供将来参考 - 它的无条件查询功能,可以用.Strict )/现在已经过时/ –

回答

0

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

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

希望有更好的答案。

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