【问题标题】:Dinamically add filter clause in QueryContainer在 QueryContainer 中动态添加过滤子句
【发布时间】:2020-12-09 02:44:50
【问题描述】:

我已经有两个 QueryDescriptor 变量动态保存布尔查询构建,例如:

QueryContainer should_container = new QueryContainer();
QueryContainer filter_container = new QueryContainer();

foreach (var parameter in should_parameters) {
    should_container |= constructClause(parameter);
}
foreach (var parameter in filter_parameters) {
    filter_container &= constructClause(parameter);
}

当我尝试合并这两个变量来构建我的查询时,如下所示:

var result = client.Search<ElasticSearchProject>(s=>s
    .From(0)
    .Size(10)
    .Query(qr => qr
        .Bool(b => b
            .Should(should_container)
            .Filter(filter_container)
        )
    )
);

调试它返回的结果变量:

"query": {
    "bool": {
        "should" : [
            "bool": {
                "should": [
                    {...},
                    {...}
                ]
            }
        ],
        "filter": [
            "bool": {
                "must": [
                    {...},
                    {...}
                ]
            }
        ]

不正确!但是不知道有没有办法避免使用这两个should子句,得到如下输出:

"query": {
    "bool": {
        "should" : [
            {...},
            {...}
        ],
        "filter": [
            "bool": {
                "must": [
                    {...},
                    {...}
                ]
            }
        ]

这给了我完全相同的结果。如何用 NEST 编写它来获得上述查询? 我正在使用弹性搜索 6.8.0

【问题讨论】:

    标签: elasticsearch nest dsl elasticsearch-dsl elasticsearch-query


    【解决方案1】:

    所有布尔查询shouldmustfiltermust_not 子句接受params QueryContainer[] 的查询,因此对于每个子句,您可以使用List&lt;QueryContainer&gt; 来收集子句的查询,然后.ToArray()列表

    var client = new ElasticClient();
    
    var should_container = new List<QueryContainer>();
    var filter_container = new List<QueryContainer>();
    
    // TODO: add queries to clause lists
    
    var result = client.Search<ElasticSearchProject>(s => s
        .From(0)
        .Size(10)
        .Query(qr => qr
            .Bool(b => b
                .Should(should_container.ToArray())
                .Filter(filter_container.ToArray())
            )
        )
    );
    

    如果您在子句中有很多查询,请使用 will be faster than combining many queries with the overloaded operators

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 2012-03-25
      • 1970-01-01
      相关资源
      最近更新 更多