php - Elasticsearch查询构造中的if else语句

标签 php elasticsearch

我正在使用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' ] ];

关于php - Elasticsearch查询构造中的if else语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52213659/

相关文章:

php - 如何使用 AJAX 返回两个字符串?

php - jQuery 自动完成 - 当从列表中选择一个项目时,将其存储在 php 变量中

python - Elasticsearch - field_value_factor,缺少参数

mysql - 将包含 LONGTEXT 字段的 MySQL 表索引到 Elastic Search 中

api - 在AWS实例上查询Elasticsearch

PHP 依赖注入(inject)。我这里的代码实际上是依赖注入(inject)容器吗?

javascript - 如何使用 jQuery/Ajax 将数据传递到 URL

elasticsearch - 在 Elasticsearch 中获取值的百分比

elasticsearch - ElasticSearch快照创建-了解如何/在何处存储它们

php - 将值从 View 页面传递到 codeigniter 中的 Controller 页面