简体   繁体   English

使用ElasticSearch和Laravel进行动态搜索

[英]Dynamic search with ElasticSearch and Laravel

I'm creating an application with Laravel and ElasticSearch. 我正在使用Laravel和ElasticSearch创建一个应用程序。

I have a page that acts as a search filter to find vehicles with a form with various filter types (brand, year, and optional). 我有一个页面用作搜索过滤器,以查找具有各种过滤器类型(品牌,年份和可选)的表格的车辆。

The user can fill in all or just one of the fields. 用户可以填写所有字段或仅填写其中一个字段。

$where = [];

if( $request->brand ){ 
    $where[] = " `brand` => '{$request->brand}'"; 
}
if( $request->year )
    { $where[] = " `cidade` => '{$request->year}'"; 
}
if( $request->item ){ 
    $where[] = " `bairro` => '{$request->item}'"; 
}

So I can get the fields that have been chosen by the user. 这样我就可以获得用户选择的字段。

But I do not know how to do a dynamic query to query only the fields chosen by the user. 但是我不知道如何执行动态查询以仅查询用户选择的字段。

I can only search if the user fills in all the fields, like this: 我只能搜索用户是否填写了所有字段,例如:

    $this->elasticParams['body'] = [
        'query' => [
            'bool' => [
                'should' => [
                    ['match' => ['brand' => $request->brand]],
                    ['match' => ['year' => $request->year]],
                    ['match' => ['item' => $request->item]]
                ]
            ]
        ]
    ];

I would like to add only the fields that the user has filled out 我只想添加用户已填写的字段

I don't know much about Elastic, but you should be able to conditionally add each field to the 'should' part like this: 我对Elastic不太了解,但是您应该可以有条件地将每个字段添加到'should'部分,如下所示:

$should = [];

if ($request->brand) {
    $should[] = ['match' => ['brand' => $request->brand]];
}

if ($request->year) {
    $should[] = ['match' => ['year' => $request->year]];
}

if ($request->item) {
    $should[] = ['match' => ['item' => $request->item]];
}

// ...

$this->elasticParams['body'] = [
    'query' => [
        'bool' => [
            'should' => $should
        ]
    ]
];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM