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            public boolean process(SearchContext searchContext, Hits hits)
026                    throws SearchException {
027    
028                    if (hits.getLength() > 0) {
029                            return true;
030                    }
031    
032                    Map<String, List<String>> spellCheckResults =
033                            hits.getSpellCheckResults();
034    
035                    if (spellCheckResults == null) {
036                            return true;
037                    }
038    
039                    String spellCheckedKeywords = hits.getCollatedSpellCheckResult();
040    
041                    searchContext.overrideKeywords(spellCheckedKeywords);
042    
043                    String[] additionalQuerySuggestions =
044                            SearchEngineUtil.suggestKeywordQueries(searchContext, 5);
045    
046                    if ((additionalQuerySuggestions != null) &&
047                            (additionalQuerySuggestions.length > 0)) {
048    
049                            searchContext.setKeywords(additionalQuerySuggestions[0]);
050                    }
051    
052                    QueryConfig queryConfig = searchContext.getQueryConfig();
053    
054                    queryConfig.setHitsProcessingEnabled(false);
055    
056                    Indexer indexer = FacetedSearcher.getInstance();
057    
058                    Hits alternateResults = indexer.search(searchContext);
059    
060                    hits.copy(alternateResults);
061    
062                    return true;
063            }
064    
065    }