PHP code example of josbeir / cakephp-elastickit

1. Go to this page and download the library: Download josbeir/cakephp-elastickit 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/ */

    

josbeir / cakephp-elastickit example snippets


$this->addPlugin('ElasticKit');

use Cake\Datasource\ConnectionManager;
use ElasticKit\Datasource\Connection;

ConnectionManager::setConfig('elasticsearch', [
	'className' => Connection::class,
	'hosts' => [
		// Use your cluster endpoints
		'http://localhost:9200',
	],
	// Optional: any PSR-3 logger name registered with Cake\Log\Log or a LoggerInterface instance
	'logger' => 'elasticsearch',
	
    // All extra arguments are passed to \Elasticsearch\ClientBuilder
]);

use Cake\Datasource\ConnectionManager;
use ElasticKit\Datasource\Connection;

ConnectionManager::setConfig('elasticsearch', [
	'className' => Connection::class,
	'hosts' => ['http://localhost:9200'],
	
	// Optional: Use a different HTTP client
	// Default: Uses CakePHP's Http Client (great for testing/mocking, hijacking the request/response)
	// 'httpClient' => new YourPsr18HttpClient(), // Any PSR-18 compatible client
	// 'httpClient' => new Elastic\Transport\Client\Curl, // Use the default cURL client from elasticsearch/elasticsearch
]);

namespace App\Model\Index;

use ElasticKit\Index;

class ArticlesIndex extends Index
{
	public function initialize(): void
	{
		// Optional: set index alias/name explicitly; otherwise class name is underscored
		// $this->setIndexName('articles');

		// Optional: provide settings/mappings used by createIndex()/updateIndex()
		$this->setSettings([
			'number_of_shards' => 1,
			'number_of_replicas' => 0,
		]);

		$this->setMappings([
			'properties' => [
				'title' => ['type' => 'text'],
				'created' => ['type' => 'date'],
			],
		]);
	}
}

namespace App\Model\Document;

use ElasticKit\Document;

class Article extends Document
{
	// Add accessors/mutators/virtuals as you like.
}

$doc = $Articles->get('some-id');
$id = $doc->getDocumentId();     // Gets the Elasticsearch document ID
$score = $doc->getScore();       // Gets the search score (if from a search result)

use Spatie\ElasticsearchQueryBuilder\Builder;
use Spatie\ElasticsearchQueryBuilder\Aggregations\MaxAggregation;
use Spatie\ElasticsearchQueryBuilder\Queries\MatchQuery;

$Articles = $this->fetchIndex('Articles');

// Using a closure
$results = $Articles->find(function (Builder $builder) {
	return $builder
		->addQuery(MatchQuery::create('name', 'elastickit', fuzziness: 'AUTO'))
		->addAggregation(MaxAggregation::create('score'))
});

// Or by creating a builder instance and passing it to the find() function.
$query = $Articles->createBuilder()
	->addQuery(MatchQuery::create('name', 'elastickit', fuzziness: 3));

$results = $Articles->find($query);

// Index's get() - returns a Document|null
$doc = $Articles->get('document_id');

// Client's get() - returns raw Elasticsearch response
$response = $Articles->getClient()->get([
	'index' => $Articles->getIndexName(),
	'id' => 'document_id'
]);

$response = $Articles->search([
	'index' => $Articles->getIndexName(),
	'body' => [
		'query' => ['match_all' => ...],
		'size' => 10,
	],
]);

// Convert as needed
$resultset = $Articles->resultSet($response);
$array = $response->asArray();
$object = $response->asObject();
$ok = $response->asBool();

foreach ($results as $doc) {
	// $doc is \App\Model\Document\YourEntity (if present) or the base Document
}

use App\Model\Document\Article;

$results->setDocumentClass(Article::class);

use ElasticKit\Locator\IndexLocatorAwareTrait;

class ArticlesService
{
	use IndexLocatorAwareTrait;

	public function searchByTitle(string $q)
	{
		$Articles = $this->fetchIndex('Articles');

		return $Articles->get(1234);
	}
}

Configure::write('DebugKit.panels', ['ElasticKit.Elasticsearch']);