在 QueryContainer 中动态添加过滤子句

Dinamically add filter clause in QueryContainer

我已经有两个 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)
        )
    )
);

正在调试结果变量 returns:

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

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

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

这给了我完全相同的结果。我怎样才能用 NEST 编写它来获取上述查询? 我正在使用 elasticsearch 6.8.0

所有布尔查询 shouldmustfiltermust_not 子句接受 params QueryContainer[] 个查询,因此对于每个子句,您可以使用a List<QueryContainer> 收集子句的查询,然后 .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