Searchcriteria Magento 2: Key Components and Advantages
Ready to optimize your store's search functionality? Searchcriteria Magento 2 helps fine-tune how data is retrieved from your database.
In this article, we will explore the key components and advantages of Search Criteria Magento 2.
Key Takeaways
-
Search Criteria in Magento 2 optimizes data retrieval with filters, sorting, and pagination.
-
Add multiple filters to retrieve specific products, customers, or orders.
-
Sorting and pagination can enhance the performance and user experience.
-
Grouping filters allow for creating advanced queries using AND/OR logic.
-
SearchCriteriaBuilder simplifies query creation and improves code maintainability.
What is Searchcriteria Magento 2?
SearchCriteria in Magento 2 is a framework that enables developers to filter, sort, and paginate collections of data when retrieving records from the database.
Search criteria are used primarily in API calls to fetch specific data like:
-
Products
-
Customers
-
Orders
It is based on defined conditions. Search Criteria can apply filters to:
-
Retrieve records matching certain criteria
-
Sort results in ascending or descending order
-
Limit the number of records returned for pagination
The powerful tool allows for efficient data management and performance optimization. It ensures that only relevant information is retrieved during query execution.
Key Components of Searchcriteria Builder
1. Add Filters
-
Filters allow you to retrieve records that meet specific criteria by adding conditions to your query.
-
You can add multiple filters to narrow down the dataset based on field values.
-
For example, if you want to retrieve only products in a certain category or orders within a particular date range. You can use the addFilter() method.
-
You can also combine multiple filters using logical operators like AND or OR.
Example:
$searchCriteriaBuilder-\>addFilter('status', 'pending');
It retrieves all orders with a pending status. You can further refine filters using comparison operators like:
-
Equals
-
Greater than
-
Less than
2. Set Sort Order
-
Sorting allows you to control the order in which records are returned, either in ascending or descending order.
-
The setSortOrder() method helps structure the query so that the search result is returned in the desired order.
-
You can sort results based on any field, such as:
1. Price
2. Creation date
3. Product name
Example:
$sortOrderBuilder \= $this-\>sortOrderBuilder
\-\>setField('price')
\-\>setDirection(SortOrder::SORT\_ASC)
\-\>create();
$searchCriteriaBuilder-\>setSortOrders(\[$sortOrderBuilder\]);
The example sorts the products by price in ascending order.
3. Set Page Size and Current Page
-
Pagination helps deal with large datasets. It allows you to break up the results into smaller, more manageable chunks.
-
Using setPageSize() lets you define how many records should be displayed per page. setCurrentPage() specifies which page of the results to display.
-
It is useful when you want to display a certain number of records per page on the front end. It fetches large datasets from the backend without pressurizing the system.
Example:
$searchCriteriaBuilder-\>setPageSize(10)-\>setCurrentPage(1);
It limits the query to return 10 results per page, starting from the first page.
4. Group Filters
-
Filters can also be grouped together to allow complex queries using both AND and OR conditions.
-
By grouping filters, you can create more advanced queries to meet specific business needs.
Example:
$filterGroup \= $this-\>filterGroupBuilder
\-\>setFilters(\[$filter1, $filter2\])
\-\>create();
$searchCriteriaBuilder-\>setFilterGroups(\[$filterGroup\]);
The method groups multiple filters. It allows for more flexible query configurations.
How Does SearchCriteria Work?
1. Filtering Data with Filters
-
SearchCriteria allows you to apply filters to retrieve specific sets of data. For example, you can filter products by category, price, or any other attribute.
-
Filters define conditions that data must meet to be included in the results.
Available Filter Conditions:
You can use different conditions to refine your search. Commonly used ones include:
-
eq: Equals
-
neq: Not equal
-
gt: Greater than
-
lt: Less than
-
gteq: Greater than or equal to
-
lteq: Less than or equal to
-
like: Partial matching (useful for searching text)
-
in: Values in a given list (array)
-
nin: Values not in a given list
2. Sorting Data with Sort Orders
-
Sorting lets you control the order in which results are returned.
-
SearchCriteria allows you to sort the data by one or more fields. You can specify one or more fields to sort by and define the sort order (ascending or descending).
-
For example, you could sort products by name or price in ascending order.
-
You can also sort by multiple fields if needed. For example, you could first sort by price and then by name.
3. Pagination
-
If you need to handle large sets of data, SearchCriteria supports pagination.
-
Pagination helps manage the number of results returned in one request.
-
You can define the page size (number of results per page), current page (which page of results to retrieve), and page size to retrieve a limited set of results.
-
It helps deal with large databases as it helps manage performance and load times.
4. Logical Operations (AND/OR)
-
Filters in SearchCriteria can be combined using logical operations like
AND
orOR
. All conditions must be met for an item to be included in the results. -
If you want to use an OR operation (i.e., results meet one or more of the conditions), you can group filters logically.
-
It helps create more complex search queries.
Example Code:
$searchCriteriaBuilder = $this->searchCriteriaBuilder;
$searchCriteria = $searchCriteriaBuilder
->addFilter('status', 'enabled')
->addSortOrder('created_at', 'DESC')
->setPageSize(10)
->setCurrentPage(1)
->create();
$products = $productRepository->getList($searchCriteria);
In this example:
- Filters are applied to get products with
status = enabled
. - Products are sorted by
created_at
in descending order. - The page size is set to 10, and it's fetching results for the first page.
Key Features of Searchcriteria Magento 2
1. Dynamic Filters for Flexible Data Queries
-
SearchCriteria in Magento2 enables you to create dynamic filters.
-
This means you can tailor your database queries to specific needs by filtering data based on various attributes, such as:
1. Product name
2. SKU
3. Price
4. Customer information
5. Order Status
-
Developers can apply multiple filters at once. It allows for highly customized data retrieval.
-
For example, you can query all products in a particular category. Then, filter them by price range and only retrieve items that are in stock.
2. Pagination for Large Data Sets
-
Performance can become an issue if all records are loaded at once for large volumes of data.
-
SearchCriteria provides pagination. It allows you to limit the number of results returned in each query.
-
By setting the
page_size
andcurrent_page
, you can retrieve data in chunks. It will not pressurize the system. -
The feature improves load times. It also ensures a smooth user experience when browsing large product catalogs or customer databases.
3. Sorting for Custom Data Organization
-
SearchCriteria supports sorting data by any attribute in ascending or descending order.
-
It means you can order product lists by:
1. Price
2. Name
3. Creation date
-
The sorting functionality is useful for front-end customer interactions. These include sorting product listings by price. It is also useful for backend operations like organizing order histories by date.
-
It allows more control over how data is presented to the user or organized in reports.
4. Condition Groups for Complex Queries
-
SearchCriteria allows developers to build complex queries using condition groups. It combines different filters using AND/OR logic.
-
The feature is particularly useful when you need to retrieve data that meets multiple, specific conditions.
-
For example, you can create a condition to find all products that are in stock. It might be a price over $50 or a particular category.
-
The flexibility helps create highly tailored data sets in reports or specialized product searches.
5. Efficient Data Retrieval
-
SearchCriteria can be used to optimize data retrieval. It eliminates the need to pull all data from the database and then filter it at the application level.
-
SearchCriteria object applies filters and conditions directly to the SQL queries.
-
This means that only the necessary data is fetched. It reduces memory usage and improves performance.
6. API Integration for Flexible Queries
-
SearchCriteria is deeply integrated into Magento’s REST API and SOAP APIs. It helps advanced queries perform easily through external systems.
-
Developers can use Search Criteria to retrieve data efficiently. It can be used consistently across various API endpoints. It is done while integrating with third-party platforms or building custom mobile apps,
-
The standardization ensures that API queries follow the same logic and structure as internal database queries. It makes Magento’s API more powerful and versatile.
7. Customizable Search Logic
-
Magento 2’s SearchCriteria also allows for customizable search logic. It gives developers full control over how data is fetched and displayed.
-
You can customize the conditions and filters used to:
1. Retrieve data
2. Adjust sorting options
3. Apply custom logic for more complex use cases
-
The flexibility helps create custom reports and build advanced product filters. It also helps implement unique search functionalities in your Magento store.
Advantages of Using Searchcriteriabuilder
1. Simplifies Query Creation
-
The SearchCriteriaBuilder provides a structured and intuitive way to create queries.
-
Developers can easily build complex search criteria using simple, reusable methods. It eliminates the need to write SQL statements or construct raw queries manually,
-
It leads to:
1. Fewer errors
2. Faster development
3. More maintainable code
Example:
Developers can apply filters like:
$searchCriteriaBuilder-\>addFilter('status', 'pending');
It eliminates the need to join tables or add conditional SQL clauses manually. It creates a structured search that is easy to read and modify. This is especially true when multiple filters and conditions are involved.
2. Enhances Performance
-
SearchCriteriaBuilder reduces the load on the system and optimizes query performance. It is by allowing developers to retrieve only the data they need,
-
It helps:
1. Minimize the amount of data retrieved
2. Prevent excessive memory usage
3. Improve the overall performance of Magento2 applications
Example:
The SearchCriteriaBuilder limits results with pagination and filters:
$searchCriteriaBuilder-\>setPageSize(20)-\>setCurrentPage(1);
It eliminates the need to fetch an entire collection of products or orders. It ensures only 20 records are loaded at a time. It reduces the load on the database and improves response times.
3. Improves Code Reusability
-
The SearchCriteriaBuilder promotes modular and reusable code.
-
The logic for filtering, sorting, and paginating data can be applied through standard methods. Developers can easily reuse this logic across different parts of the application.
-
The builder pattern makes it simple to apply the same filters and sorting options to different queries.
Example:
A predefined set of filters for customer records can be reused in multiple repositories. It helps simplify development:
$searchCriteria \= $searchCriteriaBuilder
\-\>addFilter('group\_id', 1\)
\-\>addFilter('is\_active', 1\)
\-\>create();
4. Supports Complex Queries
-
With SearchCriteriaBuilder, developers can easily handle complex queries. It is done using a combination of:
1. Filters
2. Sorting
3. Pagination
-
You can chain multiple filters together or group filters with AND/OR logic. It helps craft sophisticated queries that would otherwise be cumbersome with raw SQL.
Example:
$searchCriteriaBuilder
\-\>addFilter('price', 100, 'gteq')
\-\>addFilter('status', 'enabled')
\-\>setSortOrder('created\_at', 'DESC')
\-\>setPageSize(10)
\-\>create();
The query retrieves products with a price greater than or equal to 100 and a status of "enabled." It sorts them by creation date in descending order.
5. Boosts Maintainability and Readability
-
Using SearchCriteriaBuilder ensures that the code is clear, readable, and maintainable.
-
Developers can understand the logic behind data retrieval at a glance. They don’t need to deal with complex raw queries.
-
It makes maintaining and extending the functionality easier. This is especially true for large projects where query logic changes over time.
Example:
$searchCriteriaBuilder-\>addFilter('visibility', 4)-\>setPageSize(10);
The code is easy to understand and modify. It helps new developers join the project easily.
6. Increases Flexibility
-
The SearchCriteriaBuilder allows for a dynamic and flexible query-building process.
-
Developers can build queries easily by adjusting:
1. Filters
2. Pagination
3. Sorting options
-
It is based on user input or system conditions. It eliminates the need to re-write significant portions of code.
Example:
If a user wants to filter products based on dynamic criteria from a form, developers can easily adjust the filters dynamically:
$searchCriteriaBuilder-\>addFilter($field, $value, $conditionType);
7. Compatibility with Magento's Repository Pattern
-
SearchCriteriaBuilder is tightly integrated with Magento’s Repository Pattern.
-
It is the framework’s preferred way of accessing data.
-
It ensures a smooth interaction with repositories. It is the best tool for retrieving data in Magento2.
Example:
$products \= $productRepository-\>getList($searchCriteriaBuilder-\>create());
The approach ensures compatibility and consistency with Magento 2’s architecture and best practices. It enables efficient data retrieval.
FAQs
1. What is SearchCriteria Magento used for?
SearchCriteria helps filter collections by applying conditions like finset and condition_type. It is used with getlist to retrieve data from repositories efficiently.
2. How does the SearchCriteriaInterface work in Magento?
The SearchCriteriaInterface allows developers to specify filters, sorting (like asc or desc), and pagination for fetching data. It makes data queries flexible by defining criteria with parameters such as condition_type and eq.
3. Can SearchCriteria be used in the URL in Magento?
You can apply SearchCriteria through URL filters. It is done by using filters such as eq or finset. It helps control the search results based on specific criteria.
4. What is the maximum number of items you can fetch using getlist in Magento?
When using getlist with SearchCriteria, the maximum number of results can be controlled by defining a limit in the query. You can also sort the results in asc or desc order using search parameters.
Summary
SearchCriteria Magento 2 allows developers to filter, sort, and paginate data efficiently when querying the database. The article explores the several components of Search Criteria, including:
-
Filters apply conditions to retrieve specific records.
-
Sort order organizes results in ascending or descending order.
-
Pagination breaks large datasets into manageable chunks.
-
Group filters combine multiple conditions for complex queries.
Boost your store’s efficiency with Managed Magento Hosting and optimize your data queries using Search Criteria Magento 2.