PHP code example of bardex / elastic-query

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');

$postsQuery = $client->createSearchQuery()
    ->setIndex('blog', 'posts')
    ->where('userId')->equal(1)
    ->where('status')->equal('published')
    ->setOrderBy('dateCreation', 'desc')
    ->limit(10, 0);

$userQuery = $client->createSearchQuery()
    ->setIndex('blog', 'users')
    ->where('id')->equal(1);

$results = $client->createMultiQuery()
    ->addQuery('posts', $postsQuery)
    ->addQuery('user', $userQuery)
    ->fetchAll();

$user  = $results['user'];
$posts = $results['posts'];
$totalPosts = $posts->getTotalFound();

// OR

$multi = $client->createMultiQuery();

$multi->createSearchQuery('posts')
    ->setIndex('blog', 'posts')
    ->where('userId')->equal(1)
    ->where('status')->equal('published')
    ->setOrderBy('dateCreation', 'desc')
    ->limit(10, 0);

$multi->createSearchQuery('user')
    ->setIndex('blog', 'users')
    ->where('id')->equal(1);
    
$results = $multi->fetchAll();
$user  = $results['user'];
$posts = $results['posts'];


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 


use Bardex\Elastic\Query;

$query->where('id')->equal(10)
       ->where('category', Query::CONTEXT_FILTER)->equal(1)
       ->where('status', Query::CONTEXT_FILTER)->equal('published')
       ->where('title', Query::CONTEXT_SHOULD)->match('game') 
       ->where('tags', Query::CONTEXT_SHOULD)->in(['game', 'gamebox']) 
       ->setOrderBy(Query::ORDER_BY_SCORE, 'desc');
         


    $query->select(['id', 'title', 'comments.*', 'categories.*'])
          ->exclude(['description', '*.description']);


    $query->limit($limit, $offset);


    $query->setOrderBy('date_creation', 'desc'); // clear old order and set new order
    $query->addOrderBy('rating', 'desc'); // add order

 
    // script return scalar
    $script = new \Bardex\Elastic\Script();
    $script->addLine('def a = 100;');
    $script->addLine('return a;'); // return scalar

    $query->addScriptField('fieldName', $script);
    $result = $query->fetchAll()->getFirst();
    echo $result['fieldName']; // 100
    
    // script return array
    $script = new \Bardex\Elastic\Script();
    $script->addLine('def a = 100;');
    $script->addLine('def b = 200;');
    $script->addLine('return [a,b];'); // return array
    
    $query->addScriptField('fieldName', $script);
    $result = $query->fetchAll()->getFirst();
    print_r($result['fieldName']); // [100, 200]


    $script = new Script();
    $script->addLine("return  doc['id'].value * params.power;");
    $script->addParam('power', 1000);
    $query->addScriptField('pid', $script);
    $row = $query->fetchAll()->getFirst();
    echo $row['id']; // 2
    echo $row['pid']; // 2000


    $script = new Script();
    $script->addLine("return doc['price'].value * (1 + doc['tax'].value / 100) < params.max_price;");
    $script->addParam('max_price', 10000);
    $query->whereScript($script);
    $rows = $query->fetchAll();


    $query->getQuery();


    $query->fetchAll(false);