如果是elasticsearch查询构造中的else语句

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果是elasticsearch查询构造中的else语句相关的知识,希望对你有一定的参考价值。

我正在使用elasticsearch php并试图在一个地方优化我的查询收缩。典型的Elasticsearch查询如:

$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'body' => [
        'query' => [
            'bool' => [
                'must' => [
                    [ 'match' => [ 'testField' => 'abc' ] ],
                    [ 'match' => [ 'testField2' => 'xyz' ] ],
                ]
            ]
        ]
    ]
];

所以问题是,是否有可能在'match'字符串之前将条件查询放入$ params中:

<?php if (isset($_GET['query'])) [ 'match' => [ 'testField' => 'abc' ] ]; ?>

谢谢你的任何建议

答案

你可以用这个:

 <?php
 $must = [[ 'match' => [ 'testField2' => 'xyz' ] ] ];
 if (isset($_GET['query']))
     $must[] = [ 'match' => [ 'testField' => 'abc' ] ];

 $params = [
     'index' => 'my_index',
     'type' => 'my_type',
     'body' => [
         'query' => [
             'bool' => [
                 'must' => $must
             ]
         ]
    ]
 ];

或这个;

 <?php
 $params = [
     'index' => 'my_index',
     'type' => 'my_type',
     'body' => [
         'query' => [
             'bool' => [
                 'must' => [
                      [ 'match' => [ 'testField2' => 'xyz' ] ],
                 ],
             ]
         ]
    ]
 ];

 if (isset($_GET['query']))
     $params['body']['query']['bool']['must'][] = [ 'match' => [ 'testField' => 'abc' ] ];

以上是关于如果是elasticsearch查询构造中的else语句的主要内容,如果未能解决你的问题,请参考以下文章

Elasticsearch:Elasticsearch percolate 查询

Elasticsearch:Elasticsearch percolate 查询

Elasticsearches 模糊查询导致Elasticsearch服务宕机

Elasticsearch java api 常用查询方法QueryBuilder构造举例

如何通过Elasticsearch 6.x中的动态或未知字段进行聚合

ElasticSearch查询