001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.search;
016    
017    import com.liferay.portal.kernel.util.ArrayUtil;
018    
019    import java.util.List;
020    import java.util.Map;
021    
022    /**
023     * @author Michael C. Han
024     */
025    public class AlternateKeywordQueryHitsProcessor implements HitsProcessor {
026    
027            @Override
028            public boolean process(SearchContext searchContext, Hits hits)
029                    throws SearchException {
030    
031                    if (hits.getLength() > 0) {
032                            return true;
033                    }
034    
035                    Map<String, List<String>> spellCheckResults =
036                            hits.getSpellCheckResults();
037    
038                    if (spellCheckResults == null) {
039                            return true;
040                    }
041    
042                    String spellCheckedKeywords = hits.getCollatedSpellCheckResult();
043    
044                    searchContext.overrideKeywords(spellCheckedKeywords);
045    
046                    String[] querySuggestions = SearchEngineUtil.suggestKeywordQueries(
047                            searchContext, 5);
048    
049                    if (ArrayUtil.isNotEmpty(querySuggestions)) {
050                            searchContext.setKeywords(querySuggestions[0]);
051                    }
052    
053                    QueryConfig queryConfig = searchContext.getQueryConfig();
054    
055                    queryConfig.setHitsProcessingEnabled(false);
056    
057                    Indexer indexer = FacetedSearcher.getInstance();
058    
059                    Hits alternateResults = indexer.search(searchContext);
060    
061                    hits.copy(alternateResults);
062    
063                    return true;
064            }
065    
066    }