PHP code example of ggbb / api-platform-elasticsearch-integration

1. Go to this page and download the library: Download ggbb/api-platform-elasticsearch-integration 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/ */

    

ggbb / api-platform-elasticsearch-integration example snippets


use Ggbb\ApiPlatformElasticsearchIntegrationBundle\Provider\ElasticsearchProvider;

#[ApiResource(
    operations: [
        new GetCollection(
            provider: ElasticsearchProvider::class,
        ),
    ],
    paginationEnabled: false,
)]
#[ORM\Entity(repositoryClass: PostRepository::class)]
#[ElasticsearchEntity(
    index: 'post',
    settings: [
        "analysis" => [
            ...
        ]
    ],
    mappings: [
        "properties" => [
            ...
        ]
    ]
)]
class Post
{
    ... // Implementation of the entity
}

#[ApiFilter(ElasticsearchFilter::class, properties: [
    RangeElasticsearchFilter::class => [
        'price',
        'area',
        'floor',
    ],
    SortElasticsearchFilter::class => [
        'created_at' => 'desc',
        'id' => 'desc',
    ],
    PaginationElasticsearchFilter::class => [
        '_page'
    ],
])]
#[ElasticsearchEntity()
class Post
{
    ... // Implementation of the entity
}

#[ElasticsearchEntity()
class Post
{
    ... // Implementation of the entity
    
    #[ORM\Column(nullable: true)]
    #[ElasticsearchField]
    private ?int $regionCodeAlt = null;
    
    #[ElasticsearchField(name: 'user')]
    public function getUserId(): ?int
    {
        return $this->getUser()?->getId();
    }
}



namespace App\Filter;

use App\Service\User\UserService;
use Ggbb\ApiPlatformElasticsearchIntegrationBundle\Filter\AbstractElasticsearchFilter;
use Ggbb\ApiPlatformElasticsearchIntegrationBundle\Filter\Interface\IgnoreFieldNameInterface;
use Ggbb\ApiPlatformElasticsearchIntegrationBundle\Filter\Query\QueryBuilder;

final class OrganizationElasticsearchFilter extends AbstractElasticsearchFilter implements IgnoreFieldNameInterface
{
    public function __construct(private UserService $userService)
    {
    }

    public function filterProperty(?string $property, mixed $value, QueryBuilder &$queryBuilder): void
    {
        $organization = $this->userService->getOrganization();
        $queryBuilder->addFilterTerm('organization', (int) $organization->getId());
    }
}

#[ApiFilter(ElasticsearchFilter::class, properties: [
    OrganizationElasticsearchFilter::class,
])]
class Post
{
    ... // Implementation of the entity
}