PHP code example of sexlog / elasticsearch-query-builder

1. Go to this page and download the library: Download sexlog/elasticsearch-query-builder 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/ */

    

sexlog / elasticsearch-query-builder example snippets



    $hosts = ['10.0.0.10:9200'];
    $index = 'products';
    
    $client = \Elasticsearch\ClientBuilder::fromConfig(['hosts' => $hosts]);
    $elasticSearch = new ElasticSearch\ElasticSearch($index, $client);

    // SELECT * FROM products WHERE product_name = 'ElasticSearch' LIMIT 4
    $query = new ElasticSearch\Query();
    $query->where('product_name', 'ElasticSearch');

    $elasticSearch->setQuery($query)
                  ->take(4)
                  ->get();

    // Paging results
    $results = $elasticSearch->page(1)
                             ->get();
                  
    $results = $elasticSearch->page(2)
                             ->get();
                             


    /*
     * SELECT id, product_name, price, updated_at 
     * FROM products 
     * WHERE product_name LIKE 'car%' AND category = 3 LIMIT 20 OFFSET 0
     */ 
    $query = new ElasticSearch\Query();
    $query->wildcard('product_name', 'car*');

    $filter = new ElasticSearch\Filter();
    $filter->where('category', 3);

    // You should always use the take method before paging
    $elasticSearch->select('id, product_name, price, updated_at')
                  ->setQuery($query)
                  ->setFilter($filter)
                  ->take(20)
                  ->page(0)
                  ->get();
    
    // Paging
    $results = $elasticSearch->page(1)
                             ->get(); 
                             


    $hosts = ['10.0.0.10:9200'];
    $index = 'products';
    
    $client = \Elasticsearch\ClientBuilder::fromConfig(['hosts' => $hosts]);
    $elasticSearch = new ElasticSearch\ElasticSearch($index, $client);
    
    $errorHandler = new \Monolog\Handler\StreamHandler('elastic.log', \Monolog\Logger::ERROR);

    $logger = new \Monolog\Logger('elastic'); 
    $logger->pushHandler($errorHandler); 
    
    $elasticSearch->setLogger($logger);