1. Go to this page and download the library: Download bardex/elastic-query 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/ */
bardex / elastic-query example snippets
use Bardex\Elastic\Client;
// 1. Create client:
$client = Client::create('localhost');
// OR
$elastic = \Elasticsearch\ClientBuilder::create()
->setHosts(['localhost'])
->build();
$client = new Client($elastic);
// 2. Create search query
// this is instance of \Bardex\Elastic\SearchQuery
$query = $client->createSearchQuery();
$query->setIndex('shop', 'products')
->where('rubric')->in([1,5,7])
->where('price')->greater(0)
->where(['title','anons'])->match('game')
->exclude(['anons', 'comments']) // exclude fields
->setOrderBy('rating', 'desc')
->addOrderBy('dateCreation', 'desc')
->limit(30, 0);
// this is instance of \Bardex\Elastic\SearchResult
$results = $query->fetchAll();
// count of fetched results
$countResults = count($results);
// count of total found results
$totalFound = $results->getTotalFound();
// iterate results
foreach ($results as $result) {
echo $result['id'] . ':' . $result['title'] . '<br>';
}
//Fetch one column as array
$result->fetchColumn('id'); // ex. return [1,2,3] or []
// get first result (or null if empty)
$first = $results->getFirst();
// nothing found ?
$results->isEmpty();
use Bardex\Elastic\Client;
$client = Client::create('localhost');
// some logger implemented \Psr\Log\LoggerInterface, like Monolog.
$logger = new Logger;
$logger->setFacility('elastic-query');
$log = new \Bardex\Elastic\Listener\Logger($logger);
$log->setLogAllQueries(true); // debug log-level
$log->setLogErrorQueries(true); // error log-level
$log->setLogSlowQueries(true); // warning log-level
$log->setSlowQueryLimitMs(100);
$client->addListener($log);
use Bardex\Elastic\Client;
$client = Client::create('localhost');
// hydrator must implements interface \Bardex\Elastic\IHydrator or extends \Bardex\Elastic\Hydrator
$hydrator = new CustomHydrator;
$client->setHydrator($hydrator);
$query->where('id')->equal(10)
->where('category')->in([1,5,3])
->where(['title','anons'])->match('game') // full-text search by multi fields
->where('price')->between(100,1000) // min and max values