PHP code example of ph2m / magento2-elasticsearch

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

    

ph2m / magento2-elasticsearch example snippets


 echo $block->getChildHtml('ph2m.elasticsearch.search.form') 


declare(strict_types=1);

namespace Vendor\Brand\Model\Adapter\FieldMapper;

use Magento\Elasticsearch\Model\Adapter\FieldMapperInterface;

class BrandFieldMapper implements FieldMapperInterface
{
    public function getFieldName($attributeCode, $context = [])
    {
        return $attributeCode;
    }

    public function getAllAttributesTypes($context = [])
    {
        return [
            'name' => [
                'type' => 'text',
                'fields' => [
                    'keyword' => [
                        'type' => 'keyword',
                    ],
                ]
            ],
            'url_key' => [
                'type' => 'text',
            ],
        ];
    }
}


declare(strict_types=1);

namespace Vendor\Brand\Model\Indexer;

use Magento\AdvancedSearch\Model\Client\ClientResolver;
use Magento\Elasticsearch\Model\Adapter\Elasticsearch;
use Magento\Elasticsearch\Model\Adapter\Index\IndexNameResolver;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Vendor\Brand\Api\Data\BrandInterface;
use Vendor\Brand\Query\Brand\GetListQuery;
use Psr\Log\LoggerInterface;

class Fulltext implements \Magento\Framework\Indexer\ActionInterface, \Magento\Framework\Mview\ActionInterface
{
    public function __construct(
        protected ClientResolver $clientResolver,
        protected GetListQuery $getListQuery,
        protected SearchCriteriaBuilder $searchCriteriaBuilder,
        protected Elasticsearch $elasticsearchAdapter,
        protected LoggerInterface $logger,
        protected IndexNameResolver $indexNameResolver
    ) {
    }

    public function execute($ids)
    {
        $this->executeList($ids);
    }

    public function executeFull(): void
    {
        $this->elasticsearchAdapter->cleanIndex(1, 'brand');
        $this->executeList([]);
        $this->elasticsearchAdapter->updateAlias(1, 'brand');
    }

    public function executeList(array $ids): void
    {
        $searchCriteria = $this->searchCriteriaBuilder;

        if (!empty($ids)) {
            $searchCriteria->addFilter(BrandInterface::BRAND_ID, $ids, 'in');
        }

        $brands = $this->getListQuery->execute($searchCriteria->create())->getItems();

        $brandsToReindex = [];
        foreach ($brands as $brand) {
            $brandsToReindex[] = [
                'name' => $brand->getName(),
                'url_key' => $brand->getUrlKey(),
            ];
        }

        try {
            $this->elasticsearchAdapter->addDocs($brandsToReindex, 1, 'brand');
        } catch (\Throwable $e) {
            $this->logger->error($e->getMessage());
        }
    }

    public function executeRow($id)
    {
        $this->executeList([$id]);
    }
}

 declare(strict_types=1);

namespace Vendor\Brand\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Indexer\StateInterface;
use Magento\Indexer\Model\IndexerFactory;

class SaveAfter implements ObserverInterface
{
    public function __construct(
        protected IndexerFactory $indexerFactory,
        protected \Vendor\Brand\Model\Indexer\Fulltext $fulltextIndexer
    ) {
    }

    public function execute(Observer $observer): void
    {
        $index = $this->indexerFactory->create()->load('brandsearch_fulltext');

        if ($index->isScheduled()) {
            $index->invalidate();
        } else {
            $this->fulltextIndexer->executeRow($observer->getData('object')->getBrandId());

            $state = $index->getState();
            $state->setStatus(StateInterface::STATUS_VALID);
            $state->save();
            $index->setState($state);
        }
    }
}

cp vendor/ph2m/magento2-elasticsearch/etc/es.php.sample pub/es.php

php bin/magento indexer:reindex
xml
<type name="Magento\Elasticsearch\Model\Adapter\FieldMapper\FieldMapperResolver">
    <arguments>
        <argument name="fieldMappers" xsi:type="array">
            <item name="brand" xsi:type="string">Vendor\Brand\Model\Adapter\FieldMapper\BrandFieldMapper</item>
        </argument>
    </arguments>
</type>