Search in sources :

Example 1 with SearchResult

use of org.broadleafcommerce.core.search.domain.SearchResult in project BroadleafCommerce by BroadleafCommerce.

the class BroadleafCategoryController method handleRequest.

@Override
@SuppressWarnings("unchecked")
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ModelAndView model = new ModelAndView();
    if (request.getParameterMap().containsKey("facetField")) {
        // If we receive a facetField parameter, we need to convert the field to the
        // product search criteria expected format. This is used in multi-facet selection. We
        // will send a redirect to the appropriate URL to maintain canonical URLs
        String fieldName = request.getParameter("facetField");
        List<String> activeFieldFilters = new ArrayList<String>();
        Map<String, String[]> parameters = new HashMap<String, String[]>(request.getParameterMap());
        for (Iterator<Entry<String, String[]>> iter = parameters.entrySet().iterator(); iter.hasNext(); ) {
            Map.Entry<String, String[]> entry = iter.next();
            String key = entry.getKey();
            if (key.startsWith(fieldName + "-")) {
                activeFieldFilters.add(key.substring(key.indexOf('-') + 1));
                iter.remove();
            }
        }
        parameters.remove(SearchCriteria.PAGE_NUMBER);
        parameters.put(fieldName, activeFieldFilters.toArray(new String[activeFieldFilters.size()]));
        parameters.remove("facetField");
        String newUrl = ProcessorUtils.getUrl(request.getRequestURL().toString(), parameters);
        model.setViewName("redirect:" + newUrl);
    } else {
        // Else, if we received a GET to the category URL (either the user clicked this link or we redirected
        // from the POST method, we can actually process the results
        Category category = (Category) request.getAttribute(CategoryHandlerMapping.CURRENT_CATEGORY_ATTRIBUTE_NAME);
        assert (category != null);
        SearchCriteria searchCriteria = facetService.buildSearchCriteria(request);
        SearchResult result = getSearchService().findSearchResults(searchCriteria);
        facetService.setActiveFacetResults(result.getFacets(), request);
        model.addObject(CATEGORY_ATTRIBUTE_NAME, category);
        model.addObject(PRODUCTS_ATTRIBUTE_NAME, result.getProducts());
        model.addObject(SKUS_ATTRIBUTE_NAME, result.getSkus());
        model.addObject(FACETS_ATTRIBUTE_NAME, result.getFacets());
        model.addObject(PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME, result);
        if (request.getParameterMap().containsKey("q")) {
            model.addObject(ORIGINAL_QUERY_ATTRIBUTE_NAME, request.getParameter("q"));
        }
        model.addObject("BLC_PAGE_TYPE", "category");
        if (result.getProducts() != null) {
            model.addObject(ALL_PRODUCTS_ATTRIBUTE_NAME, new HashSet<Product>(result.getProducts()));
        }
        if (result.getSkus() != null) {
            model.addObject(ALL_SKUS_ATTRIBUTE_NAME, new HashSet<Sku>(result.getSkus()));
        }
        addDeepLink(model, deepLinkService, category);
        String templatePath = null;
        // Use the categories custom template if available
        if (StringUtils.isNotBlank(category.getDisplayTemplate())) {
            templatePath = category.getDisplayTemplate();
        } else {
            // Otherwise, use the controller default.
            templatePath = getDefaultCategoryView();
        }
        // Allow extension managers to override.
        ExtensionResultHolder<String> erh = new ExtensionResultHolder<String>();
        ExtensionResultStatusType extResult = templateOverrideManager.getProxy().getOverrideTemplate(erh, category);
        if (extResult != ExtensionResultStatusType.NOT_HANDLED) {
            templatePath = erh.getResult();
        }
        model.setViewName(templatePath);
    }
    return model;
}
Also used : Category(org.broadleafcommerce.core.catalog.domain.Category) ModelAndView(org.springframework.web.servlet.ModelAndView) Product(org.broadleafcommerce.core.catalog.domain.Product) SearchResult(org.broadleafcommerce.core.search.domain.SearchResult) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) SearchCriteria(org.broadleafcommerce.core.search.domain.SearchCriteria) Entry(java.util.Map.Entry) Sku(org.broadleafcommerce.core.catalog.domain.Sku) ExtensionResultHolder(org.broadleafcommerce.common.extension.ExtensionResultHolder)

Example 2 with SearchResult

use of org.broadleafcommerce.core.search.domain.SearchResult in project BroadleafCommerce by BroadleafCommerce.

the class BroadleafSearchController method search.

public String search(Model model, HttpServletRequest request, HttpServletResponse response, String query) throws ServletException, IOException, ServiceException {
    if (request.getParameterMap().containsKey("facetField")) {
        // If we receive a facetField parameter, we need to convert the field to the
        // product search criteria expected format. This is used in multi-facet selection. We
        // will send a redirect to the appropriate URL to maintain canonical URLs
        String fieldName = request.getParameter("facetField");
        List<String> activeFieldFilters = new ArrayList<String>();
        Map<String, String[]> parameters = new HashMap<String, String[]>(request.getParameterMap());
        for (Iterator<Entry<String, String[]>> iter = parameters.entrySet().iterator(); iter.hasNext(); ) {
            Map.Entry<String, String[]> entry = iter.next();
            String key = entry.getKey();
            if (key.startsWith(fieldName + "-")) {
                activeFieldFilters.add(key.substring(key.indexOf('-') + 1));
                iter.remove();
            }
        }
        parameters.remove(SearchCriteria.PAGE_NUMBER);
        parameters.put(fieldName, activeFieldFilters.toArray(new String[activeFieldFilters.size()]));
        parameters.remove("facetField");
        String newUrl = ProcessorUtils.getUrl(request.getRequestURL().toString(), parameters);
        return "redirect:" + newUrl;
    } else {
        // Else, if we received a GET to the category URL (either the user performed a search or we redirected
        // from the POST method, we can actually process the results
        SearchRedirect handler = searchRedirectService.findSearchRedirectBySearchTerm(query);
        if (handler != null) {
            String contextPath = request.getContextPath();
            String url = UrlUtil.fixRedirectUrl(contextPath, handler.getUrl());
            response.sendRedirect(url);
            return null;
        }
        if (StringUtils.isNotEmpty(query)) {
            SearchCriteria searchCriteria = facetService.buildSearchCriteria(request);
            if (StringUtils.isEmpty(searchCriteria.getQuery())) {
                // if our query is empty or null, we want to redirect.
                return "redirect:/";
            }
            SearchResult result = getSearchService().findSearchResults(searchCriteria);
            facetService.setActiveFacetResults(result.getFacets(), request);
            model.addAttribute(PRODUCTS_ATTRIBUTE_NAME, result.getProducts());
            model.addAttribute(SKUS_ATTRIBUTE_NAME, result.getSkus());
            model.addAttribute(FACETS_ATTRIBUTE_NAME, result.getFacets());
            model.addAttribute(PRODUCT_SEARCH_RESULT_ATTRIBUTE_NAME, result);
            model.addAttribute(ORIGINAL_QUERY_ATTRIBUTE_NAME, query);
            if (result.getProducts() != null) {
                model.addAttribute(ALL_PRODUCTS_ATTRIBUTE_NAME, new HashSet<Product>(result.getProducts()));
            }
            if (result.getSkus() != null) {
                model.addAttribute(ALL_SKUS_ATTRIBUTE_NAME, new HashSet<Sku>(result.getSkus()));
            }
        }
    }
    updateQueryRequestAttribute(query);
    return getSearchView();
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SearchRedirect(org.broadleafcommerce.core.search.redirect.domain.SearchRedirect) Product(org.broadleafcommerce.core.catalog.domain.Product) SearchResult(org.broadleafcommerce.core.search.domain.SearchResult) SearchCriteria(org.broadleafcommerce.core.search.domain.SearchCriteria) Entry(java.util.Map.Entry) Sku(org.broadleafcommerce.core.catalog.domain.Sku) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with SearchResult

use of org.broadleafcommerce.core.search.domain.SearchResult in project BroadleafCommerce by BroadleafCommerce.

the class SolrSearchServiceImpl method findSearchResults.

/**
 * Given a qualified solr query string (such as "category:2002"), actually performs a solr search. It will
 * take into considering the search criteria to build out facets / pagination / sorting.
 *
 * @param searchCriteria
 * @param facets
 * @return the ProductSearchResult of the search
 * @throws ServiceException
 */
protected SearchResult findSearchResults(String qualifiedSolrQuery, List<SearchFacetDTO> facets, SearchCriteria searchCriteria, String defaultSort, String... filterQueries) throws ServiceException {
    Map<String, SearchFacetDTO> namedFacetMap = getNamedFacetMap(facets, searchCriteria);
    // Left here for backwards compatibility for this method signature
    if (searchCriteria.getQuery() == null && qualifiedSolrQuery != null) {
        searchCriteria.setQuery(qualifiedSolrQuery);
    }
    // Build the basic query
    // Solr queries with a 'start' parameter cannot be a negative number
    int start = (searchCriteria.getPage() <= 0) ? 0 : (searchCriteria.getPage() - 1);
    SolrQuery solrQuery = new SolrQuery().setQuery(searchCriteria.getQuery()).setRows(searchCriteria.getPageSize()).setStart((start) * searchCriteria.getPageSize()).setRequestHandler(searchCriteria.getRequestHandler());
    // This is for SolrCloud.  We assume that we are always searching against a collection aliased as "PRIMARY"
    if (solrConfiguration.isSiteCollections()) {
        solrQuery.setParam("collection", solrConfiguration.getSiteAliasName(BroadleafRequestContext.getBroadleafRequestContext().getNonPersistentSite()));
    } else {
        // This should be ignored if not using SolrCloud
        solrQuery.setParam("collection", solrConfiguration.getPrimaryName());
    }
    solrQuery.setFields(shs.getIndexableIdFieldName());
    if (filterQueries != null) {
        solrQuery.setFilterQueries(filterQueries);
    }
    // add category filter if applicable
    if (searchCriteria.getCategory() != null) {
        solrQuery.addFilterQuery(getCategoryFilter(searchCriteria));
    }
    solrQuery.addFilterQuery(shs.getNamespaceFieldName() + ":(\"" + solrConfiguration.getNamespace() + "\")");
    solrQuery.set("defType", "edismax");
    solrQuery.set("qf", buildQueryFieldsString(solrQuery, searchCriteria));
    // Attach additional restrictions
    attachActiveFacetFilters(solrQuery, namedFacetMap, searchCriteria);
    attachFacets(solrQuery, namedFacetMap, searchCriteria);
    modifySolrQuery(solrQuery, searchCriteria.getQuery(), facets, searchCriteria, defaultSort);
    // on child documents.
    if (StringUtils.isNotBlank(defaultSort) || StringUtils.isNotBlank(searchCriteria.getSortQuery())) {
        solrQuery.remove("bq");
        solrQuery.remove("bf");
        solrQuery.remove("boost");
    }
    attachSortClause(solrQuery, searchCriteria, defaultSort);
    solrQuery.setShowDebugInfo(shouldShowDebugQuery());
    if (LOG.isTraceEnabled()) {
        try {
            LOG.trace(URLDecoder.decode(solrQuery.toString(), "UTF-8"));
        } catch (Exception e) {
            LOG.trace("Couldn't UTF-8 URL Decode: " + solrQuery.toString());
        }
    }
    // Query solr
    QueryResponse response;
    List<SolrDocument> responseDocuments;
    int numResults = 0;
    try {
        response = solrConfiguration.getServer().query(solrQuery, getSolrQueryMethod());
        responseDocuments = getResponseDocuments(response);
        numResults = (int) response.getResults().getNumFound();
        if (LOG.isTraceEnabled()) {
            LOG.trace(response.toString());
            for (SolrDocument doc : responseDocuments) {
                LOG.trace(doc);
            }
        }
    } catch (SolrServerException e) {
        throw new ServiceException("Could not perform search", e);
    } catch (IOException e) {
        throw new ServiceException("Could not perform search", e);
    }
    // Get the facets
    setFacetResults(namedFacetMap, response);
    sortFacetResults(namedFacetMap);
    filterEmptyFacets(facets);
    SearchResult result = new SearchResult();
    result.setFacets(facets);
    result.setQueryResponse(response);
    setPagingAttributes(result, numResults, searchCriteria);
    if (useSku) {
        List<Sku> skus = getSkus(responseDocuments);
        result.setSkus(skus);
    } else {
        // Get the products
        List<Product> products = getProducts(responseDocuments);
        result.setProducts(products);
    }
    return result;
}
Also used : SolrServerException(org.apache.solr.client.solrj.SolrServerException) SearchFacetDTO(org.broadleafcommerce.core.search.domain.SearchFacetDTO) Product(org.broadleafcommerce.core.catalog.domain.Product) SearchResult(org.broadleafcommerce.core.search.domain.SearchResult) IOException(java.io.IOException) SolrQuery(org.apache.solr.client.solrj.SolrQuery) SolrServerException(org.apache.solr.client.solrj.SolrServerException) ServiceException(org.broadleafcommerce.common.exception.ServiceException) IOException(java.io.IOException) SolrDocument(org.apache.solr.common.SolrDocument) ServiceException(org.broadleafcommerce.common.exception.ServiceException) QueryResponse(org.apache.solr.client.solrj.response.QueryResponse) Sku(org.broadleafcommerce.core.catalog.domain.Sku)

Example 4 with SearchResult

use of org.broadleafcommerce.core.search.domain.SearchResult in project BroadleafCommerce by BroadleafCommerce.

the class DatabaseSearchServiceImpl method findSearchResultsByQuery.

@Override
public SearchResult findSearchResultsByQuery(String query, SearchCriteria searchCriteria) {
    SearchResult result = new SearchResult();
    setQualifiedKeys(searchCriteria);
    List<Product> products = catalogService.findFilteredActiveProductsByQuery(query, searchCriteria);
    List<SearchFacetDTO> facets = getSearchFacets();
    setActiveFacets(facets, searchCriteria);
    result.setProducts(products);
    result.setFacets(facets);
    result.setTotalResults(products.size());
    result.setPage(1);
    result.setPageSize(products.size());
    return result;
}
Also used : SearchFacetDTO(org.broadleafcommerce.core.search.domain.SearchFacetDTO) Product(org.broadleafcommerce.core.catalog.domain.Product) SearchResult(org.broadleafcommerce.core.search.domain.SearchResult)

Example 5 with SearchResult

use of org.broadleafcommerce.core.search.domain.SearchResult in project BroadleafCommerce by BroadleafCommerce.

the class DatabaseSearchServiceImpl method findSearchResultsByCategory.

@Override
public SearchResult findSearchResultsByCategory(Category category, SearchCriteria searchCriteria) {
    SearchResult result = new SearchResult();
    setQualifiedKeys(searchCriteria);
    List<Product> products = catalogService.findFilteredActiveProductsByCategory(category, searchCriteria);
    List<SearchFacetDTO> facets = getCategoryFacets(category);
    setActiveFacets(facets, searchCriteria);
    result.setProducts(products);
    result.setFacets(facets);
    result.setTotalResults(products.size());
    result.setPage(1);
    result.setPageSize(products.size());
    return result;
}
Also used : SearchFacetDTO(org.broadleafcommerce.core.search.domain.SearchFacetDTO) Product(org.broadleafcommerce.core.catalog.domain.Product) SearchResult(org.broadleafcommerce.core.search.domain.SearchResult)

Aggregations

Product (org.broadleafcommerce.core.catalog.domain.Product)5 SearchResult (org.broadleafcommerce.core.search.domain.SearchResult)5 Sku (org.broadleafcommerce.core.catalog.domain.Sku)3 SearchFacetDTO (org.broadleafcommerce.core.search.domain.SearchFacetDTO)3 Entry (java.util.Map.Entry)2 SearchCriteria (org.broadleafcommerce.core.search.domain.SearchCriteria)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 SolrQuery (org.apache.solr.client.solrj.SolrQuery)1 SolrServerException (org.apache.solr.client.solrj.SolrServerException)1 QueryResponse (org.apache.solr.client.solrj.response.QueryResponse)1 SolrDocument (org.apache.solr.common.SolrDocument)1 ServiceException (org.broadleafcommerce.common.exception.ServiceException)1 ExtensionResultHolder (org.broadleafcommerce.common.extension.ExtensionResultHolder)1 ExtensionResultStatusType (org.broadleafcommerce.common.extension.ExtensionResultStatusType)1 Category (org.broadleafcommerce.core.catalog.domain.Category)1 SearchRedirect (org.broadleafcommerce.core.search.redirect.domain.SearchRedirect)1 ModelAndView (org.springframework.web.servlet.ModelAndView)1