【问题标题】:Should + Must combination query using NEST client for elastic使用 NEST 客户端进行弹性应该 + 必须组合查询
【发布时间】:2021-09-29 04:34:15
【问题描述】:

我需要根据属性与 OR 和 AND 组合来获取数据,但我无法完成此查询。帮助我了解它在 json 中应该是什么样的,并使用 NEST 客户端。

SQL 查询:

Select * 
From MySourceTable
Where (flag1 In ("Y","N") 
       And EntityStatus In ("STAT1", "STAT2") 
       And EntityType In ("T3"))
   Or (flag1 In ("N") And EntityType In ("T1", "T2"))

到目前为止,我的查询构建了所有导致更少或没有结果的必须查询。所以理论上我相信每个查询都是必须查询,所有必须查询都必须使用 OR 合并。

帮我构建json

【问题讨论】:

    标签: elasticsearch nest elasticsearch-5


    【解决方案1】:

    你的方法很好,查询看起来像

    var searchResponse = await elasticClient.SearchAsync<EsDocument>(s => s
        .Query(q =>
            (
                q.Terms(t => t.Field(f => f.Flag1.Suffix("keyword")).Terms("Y", "N")) &&
                q.Terms(t => t.Field(f => f.EntityStatus.Suffix("keyword")).Terms("STAT1", "STAT2")) &&
                q.Terms(t => t.Field(f => f.EntityType.Suffix("keyword")).Terms("T3"))
            ) ||
            (
                q.Terms(t => t.Field(f => f.Flag1.Suffix("keyword")).Terms("N")) &&
                q.Terms(t => t.Field(f => f.EntityType.Suffix("keyword")).Terms("T1", "T2"))
            )));
    

    你没有分享你的索引映射和查询,所以很难说你的查询为什么不起作用。

    更新

    您可以使用以下动态组合此类查询

    var should = new QueryContainer();
    
    should |=
        (
            new TermsQuery { Field = Infer.Field<EsDocument>(f => f.Flag1.Suffix("keyword")), Terms = new []{ "Y", "N" }} &&
            new TermsQuery { Field = Infer.Field<EsDocument>(f => f.EntityStatus.Suffix("keyword")), Terms = new []{ "STAT1", "STAT2" }} &&
            new TermsQuery { Field = Infer.Field<EsDocument>(f => f.EntityType.Suffix("keyword")), Terms = new []{ "T3" }}
            );
    should |=
        (
            new TermsQuery { Field = Infer.Field<EsDocument>(f => f.Flag1.Suffix("keyword")), Terms = new []{ "N" }} &&
            new TermsQuery { Field = Infer.Field<EsDocument>(f => f.EntityType.Suffix("keyword")), Terms = new []{ "T1", "T2" }}
            );
    
    var searchResponse = await elasticClient.SearchAsync<EsDocument>(s => s
        .Query(q => should));
    

    【讨论】:

    • ||查询是动态的,这意味着我可能有多个或基于 UI 选择的查询。那么如何让它变得动态呢?
    猜你喜欢
    • 1970-01-01
    • 2022-08-09
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    相关资源
    最近更新 更多