×



















    Get a Free Consultation

    Search for:

    What is Magento 2 Search Criteria Builder?

    Last Updated | September 19, 2023

    What is the Search Criteria?

    Before you start worrying and diving into Magento development deep sea after knowing about this term please keep it simple. This is nothing but literally just a “Search Criteria” to search/filter the desired result from a repository.

    Magento development

    What is a Search Criteria Builder?

    As its name describes it is a search criteria builder that helps you to build your search criteria. The Magento 2 Search Criteria Builder is new in Magento 2.

    Basically, Search Criteria Builder is a class instance of what you need to search for. In order to use it, you need a Search Criteria Interface. For that add its dependency in your class

    <?php
    
    namespace Folio3\SearchBuilderExample\Controller\Index;
    
    use Magento\Framework\Api\SearchCriteriaBuilder;
    
    class SearchProduct extends Action
    {
    
    protected $searchCriteriaBuilder;
    
    public function __construct(
    SearchCriteriaBuilder $searchCriteriaBuilder
    )
    {
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    
    }
    
    }
    

    Filter

    Filters help to create search criteria by filters you can set field, its condition and its value on the basis of which you want to filter/search repository. To use builder you need to add its dependency in class.

    <?php
    
    namespace Folio3\SearchBuilderExample\Controller\Index;
    
    use Magento\Framework\Api\SearchCriteriaBuilder;
    use Magento\Framework\Api\FilterBuilder;
    
    class SearchProduct extends Action
    {
    
    protected $searchCriteriaBuilder;
    protected $filterBuilder;
    
    public function __construct(
    SearchCriteriaBuilder $searchCriteriaBuilder,
    FilterBuilder $filterBuilder
    
    )
    {
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->filterBuilder = $filterBuilder;
    
    }
    
    }
    

    Now, let’s see an example how to pass search criteria directly to the repository. We take product repository to filter it with our search criteria that is to search product with SKU

    <?php
    
    namespace Folio3\SearchBuilderExample\Controller\Index;
    
    use Magento\Framework\Api\SearchCriteriaBuilder;
    use Magento\Framework\Api\FilterBuilder;
    use Magento\Catalog\Model\ProductRepository;
    
    class SearchProduct extends Action
    {
    
    protected $searchCriteriaBuilder;
    protected $filterBuilder;
    protected $productRepository;
    
    public function __construct(
    SearchCriteriaBuilder $searchCriteriaBuilder,
    FilterBuilder $filterBuilder,
    ProductRepository $productRepository
    )
    {
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->filterBuilder = $filterBuilder;
    $this->productRepository = $productRepository;
    
    }
    
    public function getProducts()
    {
    $filters[] = $this->filterBuilder
    ->setField('sku')
    ->setConditionType('eq')
    ->setValue('something')
    ->create();
    $this->searchCriteriaBuilder->addFilters($filters);
    
    $searchCriteria = $this->searchCriteriaBuilder->create();
    $searchResults = $this->productRepository->getList($searchCriteria);
    return $searchResults->getItems();
    }
    }

    Magento integration

    How to Implement Basic Search Filters in Magento 2

    How to use AND/OR condition in search criteria

    Time to add some more spices. Assume there is a case where you want to filter using AND/OR conditions. Lets take an example where you want to search the product by name or by sku and store.

    <?php
    
    namespace Folio3\SearchBuilderExample\Controller\Index;
    
    use Magento\Framework\Api\SearchCriteriaBuilder;
    use Magento\Framework\Api\FilterBuilder;
    use Magento\Catalog\Model\ProductRepository;
    use Magento\Framework\Api\Search\FilterGroupBuilder;
    
    class SearchProduct extends Action
    {
    
    protected $searchCriteriaBuilder;
    protected $filterBuilder;
    protected $productRepository;
    protected $filterGroupBuilder;
    
    public function __construct(
    SearchCriteriaBuilder $searchCriteriaBuilder,
    FilterBuilder $filterBuilder,
    ProductRepository $productRepository,
    FilterGroupBuilder $filterGroupBuilder
    )
    {
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->filterBuilder = $filterBuilder;
    $this->productRepository = $productRepository;
    $this->filterGroupBuilder = $filterGroupBuilder;
    
    }
    
    public function getProducts()
    {
    $filter_sku = $this->filterBuilder
    ->setField('sku')
    ->setConditionType('like')
    ->setValue('%test%')
    ->create();
    
    $filter_name = $this->filterBuilder
    ->setField('name')
    ->setConditionType('like')
    ->setValue('%test%')
    ->create();
    
    $filter_store = $this->filterBuilder
    ->setField("store")
    ->setValue('5')
    ->setConditionType("eq")
    ->create();
    
    $filter_group_1 = $this->filterGroupBuilder
    ->addFilter($filter_sku)
    ->addFilter($filter_name)
    ->create();
    
    $filter_group_2 = $this->filterGroupBuilder
    ->addFilter($filter_store)
    ->create();
    
    $search_criteria = $this->searchCriteriaBuilder
    ->setFilterGroups([$filter_group_1, $filter_group_2])
    ->create();
    
    $searchResults = $this->productRepository->getList($searchCriteria);
    
    $products = $searchResults->getItems();
    
    }
    
    }

    In the above example of magento devlopment, there is the addition of FilterGroupBuilder. Now, FilterGroupBuilder is used when you have multiple AND or OR conditions. Filters are combined with “OR” inside one filter group, and each group is combined with “AND” on the level of search criteria. In our case

    $filter_group_1 = $this->filterGroupBuilder
    ->addFilter($filter_sku)
    ->addFilter($filter_name)
    ->create();
    
    $filter_group_2 = $this->filterGroupBuilder
    ->addFilter($filter_store)
    ->create();
    

    Here OR condition is applied in $filter_group_1 which means product SKU or Name can be like “test”. While $filter_group_2 is used as AND condition. Now search criteria is like “Search * from some table where sku like ‘%test%’ or a name like ‘%test%’ AND store = 5”.

    Read Also Search Solution for My Website on Shopify

    Sorting

    Field and direction make up the two parameters that define a Sort Order object. The field is the name of the field to sort. The direction is the method of sorting whose value can be ASC or DESC.

    $sortOrder
    ->setField("name")
    ->setDirection("ASC");
    
    $searchCriteria->setSortOrders([$sortOrder]);

    Pagination

    You can limit your result by defining page limit in your search criteria for this we use setPageSize function.

    $searchCriteria->setPageSize(10); //retrieve 10 or less entities

    The setCurrentPage function sets the current page:

    $searchCriteria
    ->setPageSize(10)
    ->setCurrentPage(2); //show the 11th to 20th entity.

    Now, let us take a look to our complete code

    <?php
    
    namespace Folio3\SearchBuilderExample\Controller\Index;
    
    use Magento\Framework\Api\SearchCriteriaBuilder;
    use Magento\Framework\Api\FilterBuilder;
    use Magento\Catalog\Model\ProductRepository;
    use Magento\Framework\Api\Search\FilterGroupBuilder;
    
    class SearchProduct extends Action
    {
    
    protected $searchCriteriaBuilder;
    protected $filterBuilder;
    protected $productRepository;
    protected $filterGroupBuilder;
    
    public function __construct(
    SearchCriteriaBuilder $searchCriteriaBuilder,
    FilterBuilder $filterBuilder,
    ProductRepository $productRepository,
    FilterGroupBuilder $filterGroupBuilder
    )
    {
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->filterBuilder = $filterBuilder;
    $this->productRepository = $productRepository;
    $this->filterGroupBuilder = $filterGroupBuilder;
    
    }
    
    public function getProducts()
    {
    $filter_sku = $this->filterBuilder
    ->setField('sku')
    ->setConditionType('like')
    ->setValue('%test%')
    ->create();
    
    $filter_name = $this->filterBuilder
    ->setField('name')
    ->setConditionType('like')
    ->setValue('%test%')
    ->create();
    
    $filter_store = $this->filterBuilder
    ->setField("store")
    ->setValue('5')
    ->setConditionType("eq")
    ->create();
    
    $filter_group_1 = $this->filterGroupBuilder
    ->addFilter($filter_sku)
    ->addFilter($filter_name)
    ->create();
    
    $filter_group_2 = $this->filterGroupBuilder
    ->addFilter($filter_store)
    ->create();
    
    $search_criteria = $this->searchCriteriaBuilder
    ->setFilterGroups([$filter_group_1, $filter_group_2])
    ->create();
    
    $sortOrder
    ->setField("name")
    ->setDirection("ASC");
    
    $searchCriteria->setSortOrders([$sortOrder]);
    
    $searchCriteria->setPageSize(10);
    
    $searchResults = $this->productRepository->getList($searchCriteria);
    
    $products = $searchResults->getItems();
    
    }
    
    }

    That’s all! hope you guys find it easier to understand Search Criteria.

    Magento Migration

     

    How to Mastering the Art of Precision Search in Magento 2 with Criteria Builder?

    This table format should make it easier to reference and follow the steps for mastering precision search in Magento 2 with the Criteria Builder.
     
    Steps Description
    Step 1 Understand the Basics
    Step 2 Install and Configure Elasticsearch
    Step 3 Enable Search Engine
    Step 4 Explore Criteria Builder
    Step 5 Attribute Configuration
    Step 6 Create a Search Query
    Step 7 Optimize Product Data
    Step 8 Use Synonyms and Stop Words
    Step 9 Monitor Search Analytics
    Step 10 Implement Auto-Suggestions
    Step 11 Test and Refine
    Step 12 Consider Third-Party Extensions
       
    Details  
    Understand the Before diving into Criteria Builder, it’s essential to have a solid understanding of
    Basics how Magento 2’s search functionality works. Learn about indexing, search engines
      (like Elasticsearch), and how product data is structured in Magento.
    Install and Elasticsearch is a powerful search engine that greatly enhances search capabilities in
    Configure Elasticsearch Magento 2. Install Elasticsearch and configure it properly within your Magento 2 store.
    Enable Search Engine In your Magento 2 admin panel, go to Stores > Configuration > Catalog > Catalog Search.
      Select Elasticsearch as the search engine. Configure Elasticsearch settings such as
      host, port, and index name.
    Explore Criteria Magento 2 introduced the Criteria Builder as part of its advanced search features. Go
    Builder to Stores > Attributes > Product > Add New Attribute. Create custom attributes to refine
      your search criteria. These attributes can include product properties like size, color,
      brand, etc.
    Attribute Configure your custom attributes by setting their properties, values, and making them
    Configuration searchable.
    Create a Search Now, navigate to Marketing > Search Terms and create custom search terms based on your
    Query product attributes. This will help users find products using natural language queries.
    Optimize Product Ensure your product data is complete, accurate, and well-structured. This includes
    Data product names, descriptions, images, and any custom attributes you’ve created.
    Use Synonyms and Implement synonyms and stop words to improve search results. Synonyms allow you to map
    Stop Words similar words (e.g., “hoodie” and “sweatshirt”), while stop words exclude common words
      from searches (e.g., “and,” “the”).
    Monitor Search Magento 2 provides search analytics tools. Monitor what users are searching for and
    Analytics whether they find relevant results. Adjust your criteria and attributes accordingly.
    Implement Auto- Enable auto-suggestions and autocomplete in the search bar to help users find products
    Suggestions faster. Magento 2 offers this feature out of the box.
    Test and Refine Regularly test your search functionality from a user’s perspective. Try various search
      queries and see if the results are accurate and relevant. Continuously refine your
      criteria and attributes based on user feedback and data.
    Consider Third- Magento 2 has a thriving marketplace with various search optimization extensions.
    Party Extensions Explore these extensions to further enhance your search functionality.

     

    FAQs:

    What is Magento 2 Search Criteria Builder?

    Search criteria builder that helps you to build your search criteria. The Magento 2 Search Criteria Builder is new in Magento 2.

    Why is Folio3 good for Magento Development?

    We have many years of experience in e-commerce design and development and we are the leading e-commerce development company in the USA.

    Folio3 provides extremely customizable, visually striking, creative and innovative ecommerce solutions and more.

    How to Hire Magento Developers from Folio3?

    If you want to hire Magento developers with Folio3 then visit our website or contact our support team for a free consultation by filling the contact us form.

    Shopify wholesale app development company vs. Magento 2 Development Company: How to compare with each other by Price and extra costs?

    When it comes down to the app development of Magento and Shopify, there are various factors to consider that influence the final cost of wholesale app development. The Shopify app development considers the platform fee, credit card processing fees, hosting, development, and customization costs.

    On the other hand, Magento 2 cost for development is decided according to the annual revenue of the store, platform fee, hosting, and development factors.

    Related Blogs:

    How to Configure ElasticSearch in Magento 2?

    What is ElasticSearch? How does it work in Magento 2?

    Magento Sphinx Search vs Magento Elasticsearch


    folio-social-logo
    About