1

我需要使用 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()))));

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

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

4

2 回答 2

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

希望能帮助到你。

于 2015-11-26T14:59:03.590 回答
1

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

 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))));
于 2015-11-27T11:24:50.303 回答