001    /**
002     * Copyright (c) 2000-present 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.hits;
016    
017    import com.liferay.portal.kernel.search.FacetedSearcher;
018    import com.liferay.portal.kernel.search.Hits;
019    import com.liferay.portal.kernel.search.Indexer;
020    import com.liferay.portal.kernel.search.QueryConfig;
021    import com.liferay.portal.kernel.search.SearchContext;
022    import com.liferay.portal.kernel.search.SearchEngineUtil;
023    import com.liferay.portal.kernel.search.SearchException;
024    import com.liferay.portal.kernel.util.ArrayUtil;
025    
026    import java.util.List;
027    import java.util.Map;
028    
029    /**
030     * @author Michael C. Han
031     */
032    public class AlternateKeywordQueryHitsProcessor implements HitsProcessor {
033    
034            @Override
035            public boolean process(SearchContext searchContext, Hits hits)
036                    throws SearchException {
037    
038                    if (hits.getLength() > 0) {
039                            return true;
040                    }
041    
042                    Map<String, List<String>> spellCheckResults =
043                            hits.getSpellCheckResults();
044    
045                    if (spellCheckResults == null) {
046                            return true;
047                    }
048    
049                    String spellCheckedKeywords = hits.getCollatedSpellCheckResult();
050    
051                    searchContext.overrideKeywords(spellCheckedKeywords);
052    
053                    String[] querySuggestions = SearchEngineUtil.suggestKeywordQueries(
054                            searchContext, 5);
055    
056                    if (ArrayUtil.isNotEmpty(querySuggestions)) {
057                            searchContext.setKeywords(querySuggestions[0]);
058                    }
059    
060                    QueryConfig queryConfig = searchContext.getQueryConfig();
061    
062                    queryConfig.setHitsProcessingEnabled(false);
063    
064                    Indexer indexer = FacetedSearcher.getInstance();
065    
066                    Hits alternateResults = indexer.search(searchContext);
067    
068                    hits.copy(alternateResults);
069    
070                    return true;
071            }
072    
073    }