I have search for subjects. Teacher can add multiple subjects and students can search those subject and can apply filter on resulted data. student can filter by LEVEL, CURRICULUM, LOCATION.
My query is what if student has not applied LOCATION filter?
Of I pass Location string in filter everything works fine for me.. but when I do not apply LOCATION filter.. it gives me No text specified for text query.
Here is my query:
$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);
I have also tried like this for NULL or EMPTY value
$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);
But not worked, Can anyone helps me out?
You cannot add empty queries inside a bool/must
query. You need to build your query incrementally:
$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);