Some of my indexed fields use a Greek analyzer and I want to use an English analyzer for some other fields. My problem is: When searching for results (with a MultiFieldQueryParser currently开发者_Go百科), how can I use a different analyzer per field, so that a Greek analyzer is used for Greek-indexed fields and an English analyzer is used for English-indexed fields?
Here is the solution I found. Please comment.
transaction.begin();
PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Version.LUCENE_30));
wrapper.addAnalyzer("greekTitle", new GreekAnalyzer(Version.LUCENE_30));
wrapper.addAnalyzer("greekDescription", new GreekAnalyzer(Version.LUCENE_30));
String[] fields = {"greekTitle", "greekDescription", "englishTitle", "englishDescription"};
QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_30, fields, wrapper);
queryParser.setDefaultOperator(QueryParser.AND_OPERATOR);
org.apache.lucene.search.Query query = queryParser.parse(QueryParser.escape(queryString));
javax.persistence.Query persistenceQuery =
fullTextEntityManager.createFullTextQuery(query, Item.class);
@SuppressWarnings("unchecked")
List<Item> result = persistenceQuery.getResultList();
transaction.commit();
return result;
You could build your query parser like this:
Analyzer analyzer = fullTextSession.getSearchFactory().getAnalyzer(Item.class);
QueryParser parser = new MultiFieldQueryParser(Version.LUCENE_31, fields, analyzer);
which would use the proper analyzer, as defined in the annotations of your Item class:
@Field(name = "greekTitle" analyzer = @Analyzer(impl = GreekAnalyzer.class))
public void getGreekTitle(){
//...
}
@Field(name = "englishTitle" analyzer = @Analyzer(impl = StandardAnalyzer.class))
public void getEnglishTitle(){
//...
}
精彩评论