logo

Magento Search Query Builder

REST API search query builder for magento

A typical search query in magento rest api looks like this:

GET <host>/rest/<store_code>/V1/products/?
  searchCriteria[filter_groups][0][filters][0][field]=sku&
  searchCriteria[filter_groups][0][filters][0][value]=ABC&
  searchCriteria[filter_groups][0][filters][0][condition_type]=in

Snippet

// The following function will convert array of searchCriteria to query string.
function searchArrayToQuery(fields, searchCriteria) {
  const query = [];
  const filterGroups = searchCriteria.filter_groups;
  const sortOrders = searchCriteria.sort_orders;
  const pageSize = searchCriteria.page_size;
  const currentPage = searchCriteria.current_page;

  // query for filter groups.
  if (Array.isArray(filterGroups) && filterGroups.length) {
    filterGroups.forEach((it, i) => {
      let filters = it.filters;
      filters.forEach((filter, j) => {
        let field = `searchCriteria[filterGroups][${i}][filters][${j}][field]=${filter.field}`;
        let value = `searchCriteria[filterGroups][${i}][filters][${j}][value]=${filter.value}`;
        let condition_type = `searchCriteria[filterGroups][${i}][filters][${j}][conditionType]=${filter.condition_type}`;
        query.push(field, value, condition_type);
      });
    });
  }
  // query for sort orders. (optional)
  if (Array.isArray(sortOrders) && sortOrders.length) {
    sortOrders.forEach((it, i) => {
      query.push(`searchCriteria[sortOrders][${i}][field]=${it.field}`);
      query.push(`searchCriteria[sortOrders][${i}][direction]=${it.direction}`);
    });
  }

  // query for pageSize
  if (typeof pageSize === "number") {
    query.push(`searchCriteria[pageSize]=${pageSize}`);
  }

  if (typeof currentPage === "number") {
    query.push(`searchCriteria[currentPage]=${currentPage}`);
  }

  if (typeof fields === "string" && fields.length > 0) {
    query.push(`fields=${fields}`);
  }

  return query.join("&");
}

Usage

  1. There are two params in the above function, fields and searchCriteria. Using the fields param is optional and can be null. If provided, it will be comma-separated fields which will be produced in the final response, otherwise will return full. Example call:
const searchCriteria = {
  filter_groups: [
    {
      filters: [
        {
          field: "sku",
          value: skus.join(","),
          condition_type: "in",
        },
      ],
    },
  ],
  page_size: 10,
};

searchArrayToQuery(null, searchCriteria);
// or
searchArrayToQuery("name,sku", searchCriteria);

Reference


Last updated at: