I am trying to add the custom condition for the product collection using the below plugin for elastic search.


   <type name="Magento\Elasticsearch7\Model\Client\Elasticsearch">
       <plugin name="elastcisearch_filter_plugin" type="Vendor\Module\Plugins\ElasticLayerPlugin" />


 namespace Vendor\Module\Plugins;
 class ElasticLayerPlugin
   protected $helperObj;    
    public function __construct(
        \Vendor\Module\Helper\Data $helperObj
       $this->helperObj = $helperObj;

   public function beforeQuery($subject,$query) 
      $filteredIds   = $this->helperObj->filterCollectionIds();
      if(!$filteredIds || count($filteredIds) < 1)  {
        return [$query]; 

     // Add the product ids to filter the Elasticsearch product collection      
      $query['body']['query']['bool']['filter'] = ['ids' => [ 'values' => $filteredIds]];
      return [$query];


namespace Vendor\Module\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
 public $listProductBlock;
  public function __construct(
    Context $context,
    \Magento\Catalog\Block\Product\ListProduct $listProductBlock
) {       
    $this->listProductBlock  = $listProductBlock;     
public function filterCollectionIds(){
    $productCollection = $this->listProductBlock->getLoadedProductCollection();
    $productCollection->addAttributeToFilter('custom_attribute', array('eq' => "No"));
   $filteredIds = array();
    foreach($productCollection as $product){
        $productId = $product->getId();
       $filteredIds[] = $productId;
    return $filteredIds;


I am using custom layered navigation which is causing the count mismatch in the toolbar and filters. The above code not working for me.

how can we add the filter to the collection with a custom attribute?

Can anyone suggest this issue? Thanks

  • Make Sure to have reindexed all your indexers. Jan 3, 2022 at 11:04
  • Reindex done, what is the correct answer for the issue?
    – Manjunath
    Jan 3, 2022 at 11:34
  • you are using right way to achive this, I have used the same method and it working for me. can you check which ES version you are on? Jan 3, 2022 at 12:35
  • Mine is elastic search 7.0
    – Manjunath
    Jan 4, 2022 at 12:50
  • It's same Mine is also 7.0 and I have done the same thing and it's working fine for me. double-check if your ES is indexing properly / your plugin is calling or not etc Jan 5, 2022 at 8:00

1 Answer 1


Look at this plug in and try with you filter condition.


  • hello @rex, The above plugin is not working. I tried this before i am posting the question
    – Manjunath
    Jan 3, 2022 at 6:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.