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 java.util.List;
018    import java.util.Map;
019    
020    /**
021     * @author Michael C. Han
022     */
023    public class AlternateKeywordQueryHitsProcessor implements HitsProcessor {
024    
025            @Override
026            public boolean process(SearchContext searchContext, Hits hits)
027                    throws SearchException {
028    
029                    if (hits.getLength() > 0) {
030                            return true;
031                    }
032    
033                    Map<String, List<String>> spellCheckResults =
034                            hits.getSpellCheckResults();
035    
036                    if (spellCheckResults == null) {
037                            return true;
038                    }
039    
040                    String spellCheckedKeywords = hits.getCollatedSpellCheckResult();
041    
042                    searchContext.overrideKeywords(spellCheckedKeywords);
043    
044                    String[] additionalQuerySuggestions =
045                            SearchEngineUtil.suggestKeywordQueries(searchContext, 5);
046    
047                    if ((additionalQuerySuggestions != null) &&
048                            (additionalQuerySuggestions.length > 0)) {
049    
050                            searchContext.setKeywords(additionalQuerySuggestions[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    }