php - Creating dynamic elastic search query in php
问题描述
I have to create the following elastic search query in 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"]]
]
]
];
Where $myvariable should be:
['bool'=>
['should'=>[
['term'=> ['id'=> {$id1}]],
['term'=> ['id'=> {$id2}]],
],
'minimum_should_match'=> 1
]
]
I do not want to hardcode the values as it completely depends on the user whether she/he will choose the mentioned values in drop down or not.
What I tried?
I tried to create the inner part, that is the term part:
$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]);
}
}
}
But, it does not work as expected. I get:
['term'=> ['id'=> {$id1}]]
But, further, I do not get the required result. Moreover, I don't know how to separate them by comma. Can anyone provide a better solution?
解决方案
我稍微修改了代码以使其更易于阅读,但想法是您$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
)
)
)
)
)
如果我做了任何不正确的假设,请告诉我,我会整理出来。
推荐阅读
- oracle - PLS-00355 创建新表类型时出错
- spring - 导航到 localhost 比域登录 github 单一身份验证 spring
- elasticsearch - ES嵌套查询使用嵌套
- javascript - Python - 如何在字符串中查找一个单词,然后只打印 x 个字母
- linux - Linux“权限被拒绝”的解决方案
- sql - 如何在case语句中使用逗号分隔字符串的like子句
- ios - 为什么IOS模拟器检测不到ipa?未找到 .app 文件夹
- opencv - 姿势估计后 3D 坐标轴错位
- python - 错误:(-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' 无人机代码中的错误
- mysql - 存储在数据库中的“正常”数据量是多少?