我必须在php中创建以下弹性搜索查询:
$parameters = [
'index' => 'myindex',
'from' => 0,
'size' => 60,
'body' => [
'query' => [
'bool' => [
'filter' => [[
'bool' => [
'must' => [
$myvariable,
['nested' => [
'path' => 'sh',
'query' => [
'bool' => [
'filter' => [
['term' => ['sh.keyword' => 'PK']]
]
]
]
]
]
]
]
]],
]
],
"sort" => [
["score" => ["mode" => "avg"]]
]
]
];
$ myvariable应该在哪里:
['bool'=>
['should'=>[
['term'=> ['id'=> {$id1}]],
['term'=> ['id'=> {$id2}]],
],
'minimum_should_match'=> 1
]
]
我不想对值进行硬编码,因为这完全取决于用户是否要在下拉列表中选择提及的值。
我尝试了什么?
我尝试创建内部部分,即术语“部分”:
$countofids = count($combined_array['ids']);
if ($countofids != 0) {
for ($i = 0; $i < $countofids ; $i++) {
if ($i == 0) {
$myvariable= array('term' => array('id' => $combined_array['ids'][$i]));
} else {
array_push($myvariable, $combined_array['ids'][$i]);
}
}
}
但是,它不能按预期方式工作。我得到:
['term'=> ['id'=> {$id1}]]
但是,此外,我没有得到所需的结果。而且,我不知道如何用逗号分隔它们。 谁能提供更好的解决方案?
答案 0 :(得分:1)
我对代码进行了少许修改,以使其更易于阅读,但想法是您每次都只是覆盖$myvariable
。我出于个人目的提供了一些测试数据,并演示了它的作用,但是主要部分是替换您已经拥有的代码...
$combined_array = ['ids' => [1,2]];
if (count($combined_array['ids']) != 0) {
// Define array for terms
$myvariable = [];
foreach ( $combined_array['ids'] as $id ) {
// Add new term to existing list
$myvariable[]= array('term' => array('id' => $id));
}
// Combine data with main structure
$myvariable = [ 'bool' => ['should' => $myvariable,
'minimum_should_match'=> 1]
];
}
print_r($myvariable);
这给...
Array
(
[bool] => Array
(
[should] => Array
(
[0] => Array
(
[term] => Array
(
[id] => 1
)
)
[1] => Array
(
[term] => Array
(
[id] => 2
)
)
)
)
)
如果我做出了任何错误的假设,请告诉我,我将对其进行整理。