如果未应用所有筛选器怎么办?字段值为空的筛选器在文档中不是空值

lbsnaicq  于 2021-06-13  发布在  ElasticSearch
关注(0)|答案(1)|浏览(433)

我在找主题。教师可以添加多个主题,学生可以搜索这些主题,并对结果数据进行筛选。学生可以按级别、课程、地点进行筛选。
我的问题是,如果学生没有应用位置过滤器怎么办?
我在过滤器中传递位置字符串,一切对我来说都很好。。但当我不应用位置过滤器时。。它没有为文本查询指定文本。
我的问题是:

$client = ClientBuilder::create()->build();
$location = $request->location;
$level = $request->level;
$curriculum = $request->curriculum;
$params = [
    'index' => 'tutors',
    'body'  => 
    [
        "query" => [
            "bool" => [
                "must" => [
                    [ "term" => [ "approved" => 1 ]],
                    [ "match" => [ "country_en_name" =>  $location ]],
                    [ "match" => [ "local_rates.levels" =>  $level ]],
                    [ "match" => [ "local_rates.curriculums" =>  $curriculum ]],
                ]
            ],
        ]
    ]
];
$search = $client->search($params);

对于null或空值,我也尝试过这样的方法

$client = ClientBuilder::create()->build();
$location = $request->location;
$level = $request->level;
$curriculum = $request->curriculum;
$params = [
    'index' => 'tutors',
    'body'  => 
    [
        "query" => [
            "bool" => [
                "must" => [
                    [ "term" => [ "approved" => 1 ]],
                    $location && $location != null ? [ "match" => [ "country_en_name" =>  $location ]] : '',
                    $level && $level != null ? [ "match" => [ "local_rates.levels" =>  $level ]] : '',
                    $curriculum && $curriculum != null ? [ "match" => [ "local_rates.curriculums" =>  $curriculum ]] : '',
                ]
            ],
        ]
    ]
];
$search = $client->search($params);

但没用,有人能帮我吗?

kmbjn2e3

kmbjn2e31#

不能在内部添加空查询 bool/must 查询。您需要以增量方式生成查询:

$params = [
    'index' => 'tutors',
    'body'  => 
    [
        "query" => [
            "bool" => [
                "must" => [
                    [ "term" => [ "approved" => 1 ]],
                ]
            ],
        ]
    ]
];

if ($location && $location != null) {
   $params['body']['query']['bool']['must'][] = [ "match" => [ "country_en_name" =>  $location ]];
}
if ($level && $level != null) {
   $params['body']['query']['bool']['must'][] = [ "match" => [ "local_rates.levels" =>  $level ]];
}
if ($curriculum && $curriculum != null) {
   $params['body']['query']['bool']['must'][] = [ "match" => [ "local_rates.curriculums" =>  $curriculum ]];
}

$search = $client->search($params);

相关问题