|
20 | 20 | package org.elasticsearch.index.search;
|
21 | 21 |
|
22 | 22 | import org.apache.lucene.analysis.Analyzer;
|
| 23 | +import org.apache.lucene.analysis.miscellaneous.DisableGraphAttribute; |
| 24 | +import org.apache.lucene.analysis.TokenStream; |
23 | 25 | import org.apache.lucene.index.Term;
|
24 | 26 | import org.apache.lucene.queries.ExtendedCommonTermsQuery;
|
25 | 27 | import org.apache.lucene.search.BooleanClause;
|
|
49 | 51 | import org.elasticsearch.common.lucene.search.MultiPhrasePrefixQuery;
|
50 | 52 | import org.elasticsearch.common.lucene.search.Queries;
|
51 | 53 | import org.elasticsearch.common.unit.Fuzziness;
|
| 54 | +import org.elasticsearch.index.analysis.ShingleTokenFilterFactory; |
52 | 55 | import org.elasticsearch.index.mapper.MappedFieldType;
|
53 | 56 | import org.elasticsearch.index.query.QueryShardContext;
|
54 | 57 | import org.elasticsearch.index.query.support.QueryParsers;
|
@@ -320,6 +323,32 @@ protected Query newSynonymQuery(Term[] terms) {
|
320 | 323 | return blendTermsQuery(terms, mapper);
|
321 | 324 | }
|
322 | 325 |
|
| 326 | + /** |
| 327 | + * Checks if graph analysis should be enabled for the field depending |
| 328 | + * on the provided {@link Analyzer} |
| 329 | + */ |
| 330 | + protected Query createFieldQuery(Analyzer analyzer, BooleanClause.Occur operator, String field, |
| 331 | + String queryText, boolean quoted, int phraseSlop) { |
| 332 | + assert operator == BooleanClause.Occur.SHOULD || operator == BooleanClause.Occur.MUST; |
| 333 | + |
| 334 | + // Use the analyzer to get all the tokens, and then build an appropriate |
| 335 | + // query based on the analysis chain. |
| 336 | + try (TokenStream source = analyzer.tokenStream(field, queryText)) { |
| 337 | + if (source.hasAttribute(DisableGraphAttribute.class)) { |
| 338 | + /** |
| 339 | + * A {@link TokenFilter} in this {@link TokenStream} disabled the graph analysis to avoid |
| 340 | + * paths explosion. See {@link ShingleTokenFilterFactory} for details. |
| 341 | + */ |
| 342 | + setEnableGraphQueries(false); |
| 343 | + } |
| 344 | + Query query = super.createFieldQuery(source, operator, field, quoted, phraseSlop); |
| 345 | + setEnableGraphQueries(true); |
| 346 | + return query; |
| 347 | + } catch (IOException e) { |
| 348 | + throw new RuntimeException("Error analyzing query text", e); |
| 349 | + } |
| 350 | + } |
| 351 | + |
323 | 352 | public Query createPhrasePrefixQuery(String field, String queryText, int phraseSlop, int maxExpansions) {
|
324 | 353 | final Query query = createFieldQuery(getAnalyzer(), Occur.MUST, field, queryText, true, phraseSlop);
|
325 | 354 | return toMultiPhrasePrefix(query, phraseSlop, maxExpansions);
|
|
0 commit comments