Elasticsearch. Retrieving data

June 14, 2016 14 Yehor Rykhnov

Elasticsearch. Part 3, how to get the data in Elasticsearch. Previous part: Elasticsearch. Adding data (indexing).

Example of get data Elasticsearch with help CURL, PHP and Yii2. This article will be reviewed example of retrieving of data with help Id, search data and getting data over the filter, search and getting of all data.

Elasticsearch. Retrieve data

Command:

Get data by a particular Id:

GET /megacorp/employee/1

Get all data:

GET /megacorp/employee/_search

Get data by parameters:

GET /megacorp/employee/_search?q=last_name:Smith

CURL:

Get data by a particular Id:

$curl -XGET 'http://localhost:9200/megacorp/employee/1'

Get all data:

$curl -XGET 'http://localhost:9200/megacorp/employee/_search'

Get data by parameters:

$curl -XGET 'http://localhost:9200/megacorp/employee/_search?q=last_name:Smith'

PHP:

Get data by a particular Id:

require 'vendor/autoload.php';
$client = Elasticsearch\ClientBuilder::create()->build();
$params = [
    'index' => 'megacorp',
    'type'  => 'employee',
     'id'    => '1'
];
$response = $client->get($params);
print_r($response);

Get all data:

require 'vendor/autoload.php';
$client = Elasticsearch\ClientBuilder::create()->build();
$response = $client->search();        
print_r($response);

Get data by parameters:

require 'vendor/autoload.php';

$client = Elasticsearch\ClientBuilder::create()->build();
$params = [
    'index' => 'megacorp',
    'type'  => 'employee',
    'body'  => [
        'query' => [
            'match' => [
                'last_name' => 'Smith'
            ]
        ]
    ]
];
$response = $client->search($params);

Get the array where:

took – execution time of query.

timed_out – return true If the query execution time has passed.

_shards – by default, Elasticsearch places data in 5 segments. If the value is 5 in total and successful then each segment is working correctly .

hits - search results.

Yii2:

Get data by a particular Id:

$model = Megacorp::get(1);
var_dump($model->last_name);

Get all data:

$model = Megacorp::find()->all();    
var_dump($model);

Get data by parameters:

$params = [
    'match' => [
        'last_name' => 'Smith'
    ]
];
$model = Megacorp::find()->query($params)->all();

var_dump($model);

Additionally

Previous part: Elasticsearch. Adding data (indexing)