我试图根据用户选择过滤数据。
例如,如果用户选择一个名称“Smith” 和“Type(女性是男性)” ,则实际上可以正常工作。
问题是,如果用户不选择任何名称,而只是选择类型,则将基于该类型来查询数据,这意味着它应选择所有“名称”,而不是选择单个名称。
现在,如果用户不选择任何名称,它将在查询中返回null值,因此如何使查询的行为像什么都不是“post”时应“全选”一样。
有没有人知道这个问题的解决方案!
if ($request->getMethod() == 'POST') {
$name = $request->request->get('name'); // get requested name
$type = $request->request->get('type'); // Which is male of female
$params = array(
'index' => "myIndex",
'type' => "myType",
'body' => array(
'query' => array(
'bool' => array(
'should' => array(
'query_string' => array(
'default_field' => 'name',
'query' => $name
)
)
)
),
'term' => array(
"type" => $type
)
)
);
$docs = $client->search($params);
为了更加清楚如何在post值为null的情况下为elasticserch 创造条件,请选择所有
最佳答案
我认为您应该只是有条件地构建查询,即,仅在请求中存在相关参数时,才添加每个约束。此外,查询中还存在另一个问题,即term
查询放错了位置,它应该位于bool/should
内部而不是直接在body
中。所以这是我的做法:if ($request->getMethod() == 'POST') {
$name = $request->request->get('name'); // get requested name
$type = $request->request->get('type'); // Which is male of female
// create the base skeleton of your query
$params = array(
'index' => "myIndex",
'type' => "myType",
'body' => array(
'query' => array(
'bool' => array(
'should' => array(
// empty should clause for starters
)
)
)
)
);
// add each constraint in turn depending on whether the param is specified
if (!empty($name)) {
$params['body']['query']['bool']['should'] = array(
'query_string' => array(
'default_field' => 'name',
'query' => $name
)
);
}
if (!empty($type)) {
$params['body']['query']['bool']['should'] = array(
'term' => array(
"type" => $type
)
);
}
// special case if none is present, just match everything
if (count($params['body']['query']['bool']['should']) == 0) {
$params['body']['query'] => array(
'match_all' => array()
);
}
$docs = $client->search($params);
关于php - 如果未选择任何内容,则 Elasticsearch 发布值全选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32232769/