What is an alternative for Lucene Query's extr

2019-08-27 17:59发布

问题:

In Lucene 4.6.0 there was the method extractTerms that provided the extraction of terms from a query (Query 4.6.0). However, from Lucene 6.2.1, it does no longer exist (Query Lucene 6.2.1). Is there a valid alternative for it?

What I'd need is to parse terms (and corrispondent fields) of a Query built by QueryParser.

回答1:

Maybe not the best answer but one way is to use the same analyzer and tokenize the query string:

Analyzer anal = new StandardAnalyzer();
TokenStream ts = anal.tokenStream("title", query); // string query
CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
ts.reset();
while (ts.incrementToken()) {
    System.out.println(termAtt.toString());
}
anal.close();


回答2:

I have temporarely solved my problem with the following code. Smarter alternatives will be well accepted:

QueryParser qp = new QueryParser("title", a);
Query q = qp.parse(query);
Set<Term> termQuerySet = new HashSet<Term>();
Weight w = searcher.createWeight(q, true, 3.4f);
w.extractTerms(termQuerySet);