我有以下代码:
CompassQuery suggested = hits.getSuggestedQuery()
String displayedSuggestion = suggested.toString();
如果这样做,我会得到带有别名和查询运算符的讨厌字符串:+(alias:item) field:keyword1 OR field:keyword2
keyword1 keyword2
答案 0 :(得分:1)
我最近也遇到过同样的问题。我可以让它可靠运行的唯一方法是这样的代码:
import static org.apache.commons.lang.StringUtils.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.compass.core.CompassQuery;
import org.compass.core.engine.SearchEngineException;
import org.compass.core.engine.SearchEngineQuery;
import org.compass.core.impl.DefaultCompassQuery;
import org.compass.core.lucene.engine.LuceneSearchEngineQuery;
import org.compass.core.lucene.engine.queryparser.QueryParserUtils;
public class SearchTermExtractor {
public String extract(CompassQuery compassQuery, final String fieldName) {
SearchEngineQuery searchEngineQuery = ((DefaultCompassQuery)compassQuery).getSearchEngineQuery();
Query luceneQuery = ((LuceneSearchEngineQuery)searchEngineQuery).getQuery();
final List<String> suggestedTerms = new ArrayList<String>();
// Use a visitor to extract the terms
QueryParserUtils.visit(luceneQuery, new QueryParserUtils.QueryTermVisitor() {
@Override
public Term replaceTerm(Term term) throws SearchEngineException {
if (fieldName.equals(term.field())) {
suggestedTerms.add(term.text());
}
// Just return the original term, we're not trying to modify the query itself
return term;
}
});
return join(suggestedTerms, ' '); // join is from Commons Lang StringUtils
}
}
fieldName
参数是您要提取的字词所用的字段(示例中为field
)。