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
- Elasticsearch. What is Elasticsearch and how to install it
- Elasticsearch. Adding data (indexing)
- Elasticsearch. Retrieving data
- Elasticsearch. Search, filters - Query DSL
Previous part: Elasticsearch. Retrieving data