duanchun1909
2018-09-07 00:16
浏览 66
已采纳

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

I'm using elasticsearch php and trying to optimize my query contraction in one place. Typical Elasticsearch query like:

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

So the question is, does it possible to put conditional query in $params before 'match' string maybe like:

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

Thank you in any advice

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dopt85756 2018-09-07 00:35
    已采纳

    You can use this:

     <?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
                 ]
             ]
        ]
     ];
    

    or this;

     <?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' ] ];
    
    打赏 评论

相关推荐 更多相似问题