Elasticsearch. Search, filters - Query DSL

June 21, 2016 15 Yehor Rykhnov

Elasticsearch. Part 4, use the filter to search Elasticsearch. Previous part: Elasticsearch. Retrieving data.

An example of the use of filters to search in Elasticsearch with help CURL, PHP и Yii2.

Elasticsearch. Using filters in search (Query DSL)

Elasticsearch It provides a rich, flexible, query language, called DSL (domain-specific language) - query, which allows you to build much more sophisticated, robust queries.

Command:

GET /megacorp/employee/_search {
    "query" : {    
        "filtered" : {
            "filter" : {    
                "range" : {
                    "age" : { "gt" : 20 } 
                }
            },
            "query" : {
                "match" : {
                    "last_name" : "smith"
                }
            }
        }
    }
}
"filter" : {
    "range" : {   - range filter
        "age" : { "gt" : 20 }  - looking for staff by the surname of smith older than 20 years (parametr - gt)
    }
}

CURL:

pretty -returns data in JSON format and formatted view (with spaces and tabs)

$curl -XPOST 'localhost:9200/megacorp/employee/_search?pretty' -d '
{
    "query" : 
    {
        "filtered" : 
        {
            "filter" : 
            {
                "range" : 
                {
                    "age" : { "gt" : 20 } 
                }
            },
        "query" : 
        {
            "match" : {"last_name" : "smith"}
        }
      }
   }
}'

PHP:

require 'vendor/autoload.php';
$client = Elasticsearch\ClientBuilder::create()->build();
$params = [
            'index' => 'megacorp',
            'type'  => 'employee',
            'body'  => [
                'query' => [
                    'filtered' => [
                        'filter' => [
                            'range' => [
                                'age' => [ 
                                   'gt'=> 20
                                ]
                            ]
                        ],
                        'query'  => [ 
                           'match' => [
                                'last_name' => 'smith'
                            ]
                        ],
                    ],
                ]
            ]
        ];
try {
    $response = $client->search($params);
} catch (Exception $e) {
    var_dump($e->getMessage());        
}
print_r($response);

Yii2:

$params = [
    'filtered' => [
        'filter' => [
            'range' => [
                'age' => [
                    'gt'=> 20
                ]
            ]
        ],
        'query'  => [
            'match' => [
                'last_name' => 'smith'
            ]
         ],
       ],
];
$model = Megacorp::find()->query($params)->all();
var_dump($model);

Additionally

Previous part: Elasticsearch. Retrieving data