【问题标题】:Combining queries using bool in Nest Elasticsearch在 Nest Elasticsearch 中使用 bool 组合查询
【发布时间】:2015-11-27 19:24:50
【问题描述】:

我需要使用 NEST 客户端从 ES 获取文档,并在两个字段上具有多个 And/OR 条件。

我的查询如下:

SELECT * FROM Document WHERE (Year!=2012 && Year!=2013 ) AND (Format=".pdf" || Format=".prt" || Format=".jpeg") 

下面是我的代码:

var qc = new List<QueryContainer>();        
    foreach (var year in years)// years is the list of years that must not be included
    {
        qc.Add(Query<Document>.Match(m => m.OnField(p => p.Year).Query(year)));
    }

    var qF = new List<QueryContainer>();
    foreach (var format in txtDocs)// txtDocs is the list of formats that should be included if available
    {
        qF.Add(Query<Document>.Match(m => m.OnField(p => p.Format).Query(format)));
    }

    var searchResults = client.Search<Document>(s => s.Index(defaultIndex).From(0).Size(50).
       Query(
       f => f.Bool(
           b => b
               .MustNot(qc.ToArray()).Should(qF.ToArray()))));

当我尝试此代码时,它适用于不得出现在结果中的年份,但适用于用户应选择的格式,尽管它们可用,但它不会显示这些选定的格式。 我也使用了“must”而不是“should”,但它根本没有检索到任何东西。

有人遇到过类似的问题吗?

【问题讨论】:

    标签: elasticsearch nest booleanquery


    【解决方案1】:
    public class Test
    {
        public int Year { get; set; }
        [ElasticProperty(Index = FieldIndexOption.NotAnalyzed)]
        public string Format { get; set; }
    }
    
    var searchResponse = client.Search<Test>(s => s.Query(q => q
        .Bool(b => b
            .MustNot(
                m => m.Term(t => t.OnField(f => f.Year).Value(2012)),
                m => m.Term(t => t.OnField(f => f.Year).Value(2013))
            )
            .Should(
                should => should.Term(t => t.OnField(f => f.Format).Value(".pdf")),
                should => should.Term(t => t.OnField(f => f.Format).Value(".prt")),
                should => should.Term(t => t.OnField(f => f.Format).Value(".jpeg"))
            )
        )));
    

    希望对你有帮助。

    【讨论】:

    • 谢谢罗伯!实际上,我一直在寻找进行动态查询的代码,因为用户可以选择多种格式和年份。所以,最后根据你的回答,我知道我错了!格式字段应为“未分析”,然后作为新答案添加的我的代码运行良好!
    【解决方案2】:

    这是进行动态查询的代码:

     QueryContainer qYear=null;
        foreach (var year in years)
        {
            qYear |= new TermQuery() { Field = "year", Value = year };     
        }
    
        QueryContainer qDoc=null;
        foreach (var format in txtDocs)
        {
            qDoc|=new TermQuery() {Field="format", Value= format};            
        }
    
        var searchResults = client.Search<Document>(s => s.Index(defaultIndex).From(0).Size(50).
           Query(q => q.Bool(b => b.Should(qDoc).MustNot(qYear))));
    

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 2020-05-01
      • 2016-10-11
      • 1970-01-01
      • 2018-10-01
      • 2015-06-05
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      相关资源
      最近更新 更多