Tim Sadvak
Tim Sadvak

Reputation: 101

If else statement in elasticsearch query construction

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

Upvotes: 0

Views: 1190

Answers (1)

cagri
cagri

Reputation: 828

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

Upvotes: 1

Related Questions