PHP code example of phoenix-lib / elasticsearch-model
1. Go to this page and download the library: Download phoenix-lib/elasticsearch-model library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
phoenix-lib / elasticsearch-model example snippets
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
});
class Article extends Eloquent
{
}
Article::create([ 'title' => 'Quick brown fox' ]);
Article::create([ 'title' => 'Fast black dogs' ]);
Article::create([ 'title' => 'Swift green frogs' ]);
use Datashaman\Elasticsearch\Model\ElasticsearchModel;
class Article extends Eloquent
{
use ElasticsearchModel;
protected static $elasticsearch;
}
$response->results()
->map(function ($r) { return $r->title; })
->all();
=> ["Fast black dogs", "Quick brown fox"]
$response->getCollection()
->map(function ($r) { return $r->title; })
->all();
=> ["Fast black dogs", "Quick brown fox"]
$response->filter(function ($r) { return preg_match('/^Q/', $r->title); })
->map(function ($r) { return $r->title; })
->all();
=> ["Quick brown fox"]
$response->records()
->map(function ($article) { return $article->title; })
->all();
=> ["Fast black dogs", "Quick brown fox"]
$lines = [];
$response->records()->eachWithHit(function ($record, $hit) {
$lines[] = "* {$record->title}: {$hit->_score}";
});
$lines;
=> [ "* Fast black dogs: 0.01125201", "* Quick brown fox: 0.01125201" ]
$lines = $response->records()->mapWithHit(function ($record, $hit) {
return "* {$record->title}: {$hit->_score}";
})->all();
$lines;
=> [ "* Fast black dogs: 0.01125201", "* Quick brown fox: 0.01125201" ]
$response
->records([], function ($query) {
$query->orderBy('title', 'desc');
})
->map(function ($article) { return $article->title; })
->all();
=> [ 'Quick brown fox', 'Fast black dogs' ]
# Delegates to the results on page 2 with 20 per page
$response->perPage(20)->page(2);
# Records on page 2 with 20 per page; records ordered the same as results
# Order of the `page` and `perPage` calls doesn't matter
$response->page(2)->perPage(20)->records();
# Results on page 2 with (default) 15 results per page
$response->page(2)->results();
# Records on (default) page 1 with 10 records per page
$response->perPage(10)->records();
Article::first()->indexDocument();
=> [ 'ok' => true, ... "_version" => 2 ]
Note that this implementation differs from the Ruby one, where the instance has an elasticsearch() method and proxy object. In this package, the instance methods are added directly to the model. Implementing the same pattern in PHP is not easy to do cleanly.
### Automatic callbacks
You can auomatically update the index whenever the record changes, by using the `Datashaman\\Elasticsearch\\Model\\Callbacks` trait in your model: