Merge pull request #12527 from cbuescher/feature/query-refactoring-queryCreationContext

Separating QueryParseContext and QueryShardContext
This commit is contained in:
Christoph Büscher 2015-08-05 16:24:50 +02:00
commit 07c2e48e96
148 changed files with 1204 additions and 969 deletions

View File

@ -22,7 +22,7 @@ package org.apache.lucene.queryparser.classic;
import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.Query; import org.apache.lucene.search.Query;
import org.elasticsearch.index.query.ExistsQueryBuilder; import org.elasticsearch.index.query.ExistsQueryBuilder;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
/** /**
* *
@ -32,7 +32,7 @@ public class ExistsFieldQueryExtension implements FieldQueryExtension {
public static final String NAME = "_exists_"; public static final String NAME = "_exists_";
@Override @Override
public Query query(QueryParseContext parseContext, String queryText) { public Query query(QueryShardContext context, String queryText) {
return new ConstantScoreQuery(ExistsQueryBuilder.newFilter(parseContext, queryText)); return new ConstantScoreQuery(ExistsQueryBuilder.newFilter(context, queryText));
} }
} }

View File

@ -20,12 +20,12 @@
package org.apache.lucene.queryparser.classic; package org.apache.lucene.queryparser.classic;
import org.apache.lucene.search.Query; import org.apache.lucene.search.Query;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
/** /**
* *
*/ */
public interface FieldQueryExtension { public interface FieldQueryExtension {
Query query(QueryParseContext parseContext, String queryText); Query query(QueryShardContext context, String queryText);
} }

View File

@ -39,7 +39,7 @@ import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.core.DateFieldMapper; import org.elasticsearch.index.mapper.core.DateFieldMapper;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.support.QueryParsers; import org.elasticsearch.index.query.support.QueryParsers;
import com.google.common.base.Objects; import com.google.common.base.Objects;
@ -70,7 +70,7 @@ public class MapperQueryParser extends QueryParser {
.build(); .build();
} }
private final QueryParseContext parseContext; private final QueryShardContext context;
private QueryParserSettings settings; private QueryParserSettings settings;
@ -85,15 +85,9 @@ public class MapperQueryParser extends QueryParser {
private String quoteFieldSuffix; private String quoteFieldSuffix;
public MapperQueryParser(QueryParseContext parseContext) { public MapperQueryParser(QueryShardContext context) {
super(null, null); super(null, null);
this.parseContext = parseContext; this.context = context;
}
public MapperQueryParser(QueryParserSettings settings, QueryParseContext parseContext) {
super(settings.defaultField(), settings.defaultAnalyzer());
this.parseContext = parseContext;
reset(settings);
} }
public void reset(QueryParserSettings settings) { public void reset(QueryParserSettings settings) {
@ -168,7 +162,7 @@ public class MapperQueryParser extends QueryParser {
public Query getFieldQuery(String field, String queryText, boolean quoted) throws ParseException { public Query getFieldQuery(String field, String queryText, boolean quoted) throws ParseException {
FieldQueryExtension fieldQueryExtension = fieldQueryExtensions.get(field); FieldQueryExtension fieldQueryExtension = fieldQueryExtensions.get(field);
if (fieldQueryExtension != null) { if (fieldQueryExtension != null) {
return fieldQueryExtension.query(parseContext, queryText); return fieldQueryExtension.query(context, queryText);
} }
Collection<String> fields = extractMultiFields(field); Collection<String> fields = extractMultiFields(field);
if (fields != null) { if (fields != null) {
@ -232,27 +226,27 @@ public class MapperQueryParser extends QueryParser {
if (quoted) { if (quoted) {
setAnalyzer(quoteAnalyzer); setAnalyzer(quoteAnalyzer);
if (quoteFieldSuffix != null) { if (quoteFieldSuffix != null) {
currentFieldType = parseContext.fieldMapper(field + quoteFieldSuffix); currentFieldType = context.fieldMapper(field + quoteFieldSuffix);
} }
} }
if (currentFieldType == null) { if (currentFieldType == null) {
currentFieldType = parseContext.fieldMapper(field); currentFieldType = context.fieldMapper(field);
} }
if (currentFieldType != null) { if (currentFieldType != null) {
if (quoted) { if (quoted) {
if (!forcedQuoteAnalyzer) { if (!forcedQuoteAnalyzer) {
setAnalyzer(parseContext.getSearchQuoteAnalyzer(currentFieldType)); setAnalyzer(context.getSearchQuoteAnalyzer(currentFieldType));
} }
} else { } else {
if (!forcedAnalyzer) { if (!forcedAnalyzer) {
setAnalyzer(parseContext.getSearchAnalyzer(currentFieldType)); setAnalyzer(context.getSearchAnalyzer(currentFieldType));
} }
} }
if (currentFieldType != null) { if (currentFieldType != null) {
Query query = null; Query query = null;
if (currentFieldType.useTermQueryWithQueryString()) { if (currentFieldType.useTermQueryWithQueryString()) {
try { try {
query = currentFieldType.termQuery(queryText, parseContext); query = currentFieldType.termQuery(queryText, context);
} catch (RuntimeException e) { } catch (RuntimeException e) {
if (settings.lenient()) { if (settings.lenient()) {
return null; return null;
@ -363,7 +357,7 @@ public class MapperQueryParser extends QueryParser {
} }
private Query getRangeQuerySingle(String field, String part1, String part2, boolean startInclusive, boolean endInclusive) { private Query getRangeQuerySingle(String field, String part1, String part2, boolean startInclusive, boolean endInclusive) {
currentFieldType = parseContext.fieldMapper(field); currentFieldType = context.fieldMapper(field);
if (currentFieldType != null) { if (currentFieldType != null) {
if (lowercaseExpandedTerms && !currentFieldType.isNumeric()) { if (lowercaseExpandedTerms && !currentFieldType.isNumeric()) {
part1 = part1 == null ? null : part1.toLowerCase(locale); part1 = part1 == null ? null : part1.toLowerCase(locale);
@ -428,7 +422,7 @@ public class MapperQueryParser extends QueryParser {
} }
private Query getFuzzyQuerySingle(String field, String termStr, String minSimilarity) throws ParseException { private Query getFuzzyQuerySingle(String field, String termStr, String minSimilarity) throws ParseException {
currentFieldType = parseContext.fieldMapper(field); currentFieldType = context.fieldMapper(field);
if (currentFieldType != null) { if (currentFieldType != null) {
try { try {
return currentFieldType.fuzzyQuery(termStr, Fuzziness.build(minSimilarity), fuzzyPrefixLength, settings.fuzzyMaxExpansions(), FuzzyQuery.defaultTranspositions); return currentFieldType.fuzzyQuery(termStr, Fuzziness.build(minSimilarity), fuzzyPrefixLength, settings.fuzzyMaxExpansions(), FuzzyQuery.defaultTranspositions);
@ -498,14 +492,14 @@ public class MapperQueryParser extends QueryParser {
currentFieldType = null; currentFieldType = null;
Analyzer oldAnalyzer = getAnalyzer(); Analyzer oldAnalyzer = getAnalyzer();
try { try {
currentFieldType = parseContext.fieldMapper(field); currentFieldType = context.fieldMapper(field);
if (currentFieldType != null) { if (currentFieldType != null) {
if (!forcedAnalyzer) { if (!forcedAnalyzer) {
setAnalyzer(parseContext.getSearchAnalyzer(currentFieldType)); setAnalyzer(context.getSearchAnalyzer(currentFieldType));
} }
Query query = null; Query query = null;
if (currentFieldType.useTermQueryWithQueryString()) { if (currentFieldType.useTermQueryWithQueryString()) {
query = currentFieldType.prefixQuery(termStr, multiTermRewriteMethod, parseContext); query = currentFieldType.prefixQuery(termStr, multiTermRewriteMethod, context);
} }
if (query == null) { if (query == null) {
query = getPossiblyAnalyzedPrefixQuery(currentFieldType.names().indexName(), termStr); query = getPossiblyAnalyzedPrefixQuery(currentFieldType.names().indexName(), termStr);
@ -590,7 +584,7 @@ public class MapperQueryParser extends QueryParser {
return newMatchAllDocsQuery(); return newMatchAllDocsQuery();
} }
// effectively, we check if a field exists or not // effectively, we check if a field exists or not
return fieldQueryExtensions.get(ExistsFieldQueryExtension.NAME).query(parseContext, actualField); return fieldQueryExtensions.get(ExistsFieldQueryExtension.NAME).query(context, actualField);
} }
} }
if (lowercaseExpandedTerms) { if (lowercaseExpandedTerms) {
@ -639,10 +633,10 @@ public class MapperQueryParser extends QueryParser {
currentFieldType = null; currentFieldType = null;
Analyzer oldAnalyzer = getAnalyzer(); Analyzer oldAnalyzer = getAnalyzer();
try { try {
currentFieldType = parseContext.fieldMapper(field); currentFieldType = context.fieldMapper(field);
if (currentFieldType != null) { if (currentFieldType != null) {
if (!forcedAnalyzer) { if (!forcedAnalyzer) {
setAnalyzer(parseContext.getSearchAnalyzer(currentFieldType)); setAnalyzer(context.getSearchAnalyzer(currentFieldType));
} }
indexedNameField = currentFieldType.names().indexName(); indexedNameField = currentFieldType.names().indexName();
return getPossiblyAnalyzedWildcardQuery(indexedNameField, termStr); return getPossiblyAnalyzedWildcardQuery(indexedNameField, termStr);
@ -780,14 +774,14 @@ public class MapperQueryParser extends QueryParser {
currentFieldType = null; currentFieldType = null;
Analyzer oldAnalyzer = getAnalyzer(); Analyzer oldAnalyzer = getAnalyzer();
try { try {
currentFieldType = parseContext.fieldMapper(field); currentFieldType = context.fieldMapper(field);
if (currentFieldType != null) { if (currentFieldType != null) {
if (!forcedAnalyzer) { if (!forcedAnalyzer) {
setAnalyzer(parseContext.getSearchAnalyzer(currentFieldType)); setAnalyzer(context.getSearchAnalyzer(currentFieldType));
} }
Query query = null; Query query = null;
if (currentFieldType.useTermQueryWithQueryString()) { if (currentFieldType.useTermQueryWithQueryString()) {
query = currentFieldType.regexpQuery(termStr, RegExp.ALL, maxDeterminizedStates, multiTermRewriteMethod, parseContext); query = currentFieldType.regexpQuery(termStr, RegExp.ALL, maxDeterminizedStates, multiTermRewriteMethod, context);
} }
if (query == null) { if (query == null) {
query = super.getRegexpQuery(field, termStr); query = super.getRegexpQuery(field, termStr);
@ -835,7 +829,7 @@ public class MapperQueryParser extends QueryParser {
private Collection<String> extractMultiFields(String field) { private Collection<String> extractMultiFields(String field) {
Collection<String> fields = null; Collection<String> fields = null;
if (field != null) { if (field != null) {
fields = parseContext.simpleMatchToIndexNames(field); fields = context.simpleMatchToIndexNames(field);
} else { } else {
fields = settings.fields(); fields = settings.fields();
} }

View File

@ -22,8 +22,7 @@ package org.apache.lucene.queryparser.classic;
import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.Query; import org.apache.lucene.search.Query;
import org.elasticsearch.index.query.MissingQueryBuilder; import org.elasticsearch.index.query.MissingQueryBuilder;
import org.elasticsearch.index.query.MissingQueryParser; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryParseContext;
/** /**
* *
@ -33,8 +32,8 @@ public class MissingFieldQueryExtension implements FieldQueryExtension {
public static final String NAME = "_missing_"; public static final String NAME = "_missing_";
@Override @Override
public Query query(QueryParseContext parseContext, String queryText) { public Query query(QueryShardContext context, String queryText) {
Query query = MissingQueryBuilder.newFilter(parseContext, queryText, MissingQueryBuilder.DEFAULT_EXISTENCE_VALUE, MissingQueryBuilder.DEFAULT_NULL_VALUE); Query query = MissingQueryBuilder.newFilter(context, queryText, MissingQueryBuilder.DEFAULT_EXISTENCE_VALUE, MissingQueryBuilder.DEFAULT_NULL_VALUE);
if (query != null) { if (query != null) {
return new ConstantScoreQuery(query); return new ConstantScoreQuery(query);
} }

View File

@ -572,6 +572,7 @@ public class ElasticsearchException extends RuntimeException implements ToXConte
org.elasticsearch.index.engine.RecoveryEngineException.class, org.elasticsearch.index.engine.RecoveryEngineException.class,
org.elasticsearch.common.blobstore.BlobStoreException.class, org.elasticsearch.common.blobstore.BlobStoreException.class,
org.elasticsearch.index.snapshots.IndexShardRestoreException.class, org.elasticsearch.index.snapshots.IndexShardRestoreException.class,
org.elasticsearch.index.query.QueryShardException.class,
org.elasticsearch.index.query.QueryParsingException.class, org.elasticsearch.index.query.QueryParsingException.class,
org.elasticsearch.action.support.replication.TransportReplicationAction.RetryOnPrimaryException.class, org.elasticsearch.action.support.replication.TransportReplicationAction.RetryOnPrimaryException.class,
org.elasticsearch.index.engine.DeleteByQueryFailedEngineException.class, org.elasticsearch.index.engine.DeleteByQueryFailedEngineException.class,

View File

@ -42,6 +42,7 @@ import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.index.IndexService; import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.query.IndexQueryParserService; import org.elasticsearch.index.query.IndexQueryParserService;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.IndicesService;
@ -189,8 +190,8 @@ public class TransportValidateQueryAction extends TransportBroadcastAction<Valid
} }
if (request.rewrite()) { if (request.rewrite()) {
explanation = getRewrittenQuery(searcher.searcher(), searchContext.query()); explanation = getRewrittenQuery(searcher.searcher(), searchContext.query());
} }
} catch (QueryParsingException e) { } catch (QueryShardException|QueryParsingException e) {
valid = false; valid = false;
error = e.getDetailedMessage(); error = e.getDetailedMessage();
} catch (AssertionError|IOException e) { } catch (AssertionError|IOException e) {

View File

@ -41,7 +41,7 @@ import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.util.BigArrays; import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.index.IndexService; import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.script.ScriptService; import org.elasticsearch.script.ScriptService;
@ -166,10 +166,10 @@ public class TransportExistsAction extends TransportBroadcastAction<ExistsReques
BytesReference source = request.querySource(); BytesReference source = request.querySource();
if (source != null && source.length() > 0) { if (source != null && source.length() > 0) {
try { try {
QueryParseContext.setTypes(request.types()); QueryShardContext.setTypes(request.types());
context.parsedQuery(indexService.queryParserService().parseQuery(source)); context.parsedQuery(indexService.queryParserService().parseQuery(source));
} finally { } finally {
QueryParseContext.removeTypes(); QueryShardContext.removeTypes();
} }
} }
context.preProcess(); context.preProcess();

View File

@ -28,7 +28,7 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.Index; import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.IndexQueryParserService; import org.elasticsearch.index.query.IndexQueryParserService;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.indices.InvalidAliasNameException; import org.elasticsearch.indices.InvalidAliasNameException;
import java.io.IOException; import java.io.IOException;
@ -142,10 +142,10 @@ public class AliasValidator extends AbstractComponent {
} }
private void validateAliasFilter(XContentParser parser, IndexQueryParserService indexQueryParserService) throws IOException { private void validateAliasFilter(XContentParser parser, IndexQueryParserService indexQueryParserService) throws IOException {
QueryParseContext context = indexQueryParserService.getParseContext(); QueryShardContext context = indexQueryParserService.getShardContext();
try { try {
context.reset(parser); context.reset(parser);
context.parseInnerFilter(); context.parseContext().parseInnerFilter();
} finally { } finally {
context.reset(null); context.reset(null);
parser.close(); parser.close();

View File

@ -33,7 +33,7 @@ import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.analysis.NamedAnalyzer;
import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.similarity.SimilarityProvider; import org.elasticsearch.index.similarity.SimilarityProvider;
import java.io.IOException; import java.io.IOException;
@ -425,7 +425,7 @@ public abstract class MappedFieldType extends FieldType {
} }
/** /**
* Should the field query {@link #termQuery(Object, org.elasticsearch.index.query.QueryParseContext)} be used when detecting this * Should the field query {@link #termQuery(Object, org.elasticsearch.index.query.QueryShardContext)} be used when detecting this
* field in query string. * field in query string.
*/ */
public boolean useTermQueryWithQueryString() { public boolean useTermQueryWithQueryString() {
@ -437,11 +437,11 @@ public abstract class MappedFieldType extends FieldType {
return new Term(names().indexName(), indexedValueForSearch(value)); return new Term(names().indexName(), indexedValueForSearch(value));
} }
public Query termQuery(Object value, @Nullable QueryParseContext context) { public Query termQuery(Object value, @Nullable QueryShardContext context) {
return new TermQuery(createTerm(value)); return new TermQuery(createTerm(value));
} }
public Query termsQuery(List values, @Nullable QueryParseContext context) { public Query termsQuery(List values, @Nullable QueryShardContext context) {
BytesRef[] bytesRefs = new BytesRef[values.size()]; BytesRef[] bytesRefs = new BytesRef[values.size()];
for (int i = 0; i < bytesRefs.length; i++) { for (int i = 0; i < bytesRefs.length; i++) {
bytesRefs[i] = indexedValueForSearch(values.get(i)); bytesRefs[i] = indexedValueForSearch(values.get(i));
@ -460,7 +460,7 @@ public abstract class MappedFieldType extends FieldType {
return new FuzzyQuery(createTerm(value), fuzziness.asDistance(BytesRefs.toString(value)), prefixLength, maxExpansions, transpositions); return new FuzzyQuery(createTerm(value), fuzziness.asDistance(BytesRefs.toString(value)), prefixLength, maxExpansions, transpositions);
} }
public Query prefixQuery(String value, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) { public Query prefixQuery(String value, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryShardContext context) {
PrefixQuery query = new PrefixQuery(createTerm(value)); PrefixQuery query = new PrefixQuery(createTerm(value));
if (method != null) { if (method != null) {
query.setRewriteMethod(method); query.setRewriteMethod(method);
@ -468,7 +468,7 @@ public abstract class MappedFieldType extends FieldType {
return query; return query;
} }
public Query regexpQuery(String value, int flags, int maxDeterminizedStates, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) { public Query regexpQuery(String value, int flags, int maxDeterminizedStates, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryShardContext context) {
RegexpQuery query = new RegexpQuery(createTerm(value), flags, maxDeterminizedStates); RegexpQuery query = new RegexpQuery(createTerm(value), flags, maxDeterminizedStates);
if (method != null) { if (method != null) {
query.setRewriteMethod(method); query.setRewriteMethod(method);

View File

@ -40,7 +40,7 @@ import org.elasticsearch.index.mapper.MergeMappingException;
import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeResult;
import org.elasticsearch.index.mapper.MetadataFieldMapper; import org.elasticsearch.index.mapper.MetadataFieldMapper;
import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.similarity.SimilarityLookupService; import org.elasticsearch.index.similarity.SimilarityLookupService;
import java.io.IOException; import java.io.IOException;
@ -186,7 +186,7 @@ public class AllFieldMapper extends MetadataFieldMapper {
} }
@Override @Override
public Query termQuery(Object value, QueryParseContext context) { public Query termQuery(Object value, QueryShardContext context) {
return queryStringTermQuery(createTerm(value)); return queryStringTermQuery(createTerm(value));
} }
} }

View File

@ -49,7 +49,7 @@ import org.elasticsearch.index.mapper.MergeResult;
import org.elasticsearch.index.mapper.MetadataFieldMapper; import org.elasticsearch.index.mapper.MetadataFieldMapper;
import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.Collection;
@ -167,7 +167,7 @@ public class IdFieldMapper extends MetadataFieldMapper {
} }
@Override @Override
public Query termQuery(Object value, @Nullable QueryParseContext context) { public Query termQuery(Object value, @Nullable QueryShardContext context) {
if (indexOptions() != IndexOptions.NONE || context == null) { if (indexOptions() != IndexOptions.NONE || context == null) {
return super.termQuery(value, context); return super.termQuery(value, context);
} }
@ -176,7 +176,7 @@ public class IdFieldMapper extends MetadataFieldMapper {
} }
@Override @Override
public Query termsQuery(List values, @Nullable QueryParseContext context) { public Query termsQuery(List values, @Nullable QueryShardContext context) {
if (indexOptions() != IndexOptions.NONE || context == null) { if (indexOptions() != IndexOptions.NONE || context == null) {
return super.termsQuery(values, context); return super.termsQuery(values, context);
} }
@ -184,7 +184,7 @@ public class IdFieldMapper extends MetadataFieldMapper {
} }
@Override @Override
public Query prefixQuery(String value, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) { public Query prefixQuery(String value, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryShardContext context) {
if (indexOptions() != IndexOptions.NONE || context == null) { if (indexOptions() != IndexOptions.NONE || context == null) {
return super.prefixQuery(value, method, context); return super.prefixQuery(value, method, context);
} }
@ -201,7 +201,7 @@ public class IdFieldMapper extends MetadataFieldMapper {
} }
@Override @Override
public Query regexpQuery(String value, int flags, int maxDeterminizedStates, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) { public Query regexpQuery(String value, int flags, int maxDeterminizedStates, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryShardContext context) {
if (indexOptions() != IndexOptions.NONE || context == null) { if (indexOptions() != IndexOptions.NONE || context == null) {
return super.regexpQuery(value, flags, maxDeterminizedStates, method, context); return super.regexpQuery(value, flags, maxDeterminizedStates, method, context);
} }

View File

@ -38,7 +38,7 @@ import org.elasticsearch.index.mapper.MergeMappingException;
import org.elasticsearch.index.mapper.MergeResult; import org.elasticsearch.index.mapper.MergeResult;
import org.elasticsearch.index.mapper.MetadataFieldMapper; import org.elasticsearch.index.mapper.MetadataFieldMapper;
import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator; import java.util.Iterator;
@ -157,7 +157,7 @@ public class IndexFieldMapper extends MetadataFieldMapper {
* indices * indices
*/ */
@Override @Override
public Query termQuery(Object value, @Nullable QueryParseContext context) { public Query termQuery(Object value, @Nullable QueryShardContext context) {
if (context == null) { if (context == null) {
return super.termQuery(value, context); return super.termQuery(value, context);
} }
@ -171,7 +171,7 @@ public class IndexFieldMapper extends MetadataFieldMapper {
@Override @Override
public Query termsQuery(List values, QueryParseContext context) { public Query termsQuery(List values, QueryShardContext context) {
if (context == null) { if (context == null) {
return super.termsQuery(values, context); return super.termsQuery(values, context);
} }

View File

@ -43,7 +43,7 @@ import org.elasticsearch.index.mapper.MergeResult;
import org.elasticsearch.index.mapper.MetadataFieldMapper; import org.elasticsearch.index.mapper.MetadataFieldMapper;
import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@ -189,12 +189,12 @@ public class ParentFieldMapper extends MetadataFieldMapper {
} }
@Override @Override
public Query termQuery(Object value, @Nullable QueryParseContext context) { public Query termQuery(Object value, @Nullable QueryShardContext context) {
return termsQuery(Collections.singletonList(value), context); return termsQuery(Collections.singletonList(value), context);
} }
@Override @Override
public Query termsQuery(List values, @Nullable QueryParseContext context) { public Query termsQuery(List values, @Nullable QueryShardContext context) {
if (context == null) { if (context == null) {
return super.termsQuery(values, context); return super.termsQuery(values, context);
} }

View File

@ -43,7 +43,7 @@ import org.elasticsearch.index.mapper.MergeResult;
import org.elasticsearch.index.mapper.MetadataFieldMapper; import org.elasticsearch.index.mapper.MetadataFieldMapper;
import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
@ -137,7 +137,7 @@ public class TypeFieldMapper extends MetadataFieldMapper {
} }
@Override @Override
public Query termQuery(Object value, @Nullable QueryParseContext context) { public Query termQuery(Object value, @Nullable QueryShardContext context) {
if (indexOptions() == IndexOptions.NONE) { if (indexOptions() == IndexOptions.NONE) {
return new ConstantScoreQuery(new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.typePrefixAsBytes(BytesRefs.toBytesRef(value))))); return new ConstantScoreQuery(new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.typePrefixAsBytes(BytesRefs.toBytesRef(value)))));
} }

View File

@ -41,7 +41,7 @@ import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.internal.TypeFieldMapper; import org.elasticsearch.index.mapper.internal.TypeFieldMapper;
import org.elasticsearch.index.percolator.stats.ShardPercolateService; import org.elasticsearch.index.percolator.stats.ShardPercolateService;
import org.elasticsearch.index.query.IndexQueryParserService; import org.elasticsearch.index.query.IndexQueryParserService;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.index.settings.IndexSettings; import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.index.shard.AbstractIndexShardComponent; import org.elasticsearch.index.shard.AbstractIndexShardComponent;
@ -184,12 +184,13 @@ public class PercolatorQueriesRegistry extends AbstractIndexShardComponent imple
} }
} }
//norelease this method parses from xcontent to lucene query, need to re-investigate how to split context here
private Query parseQuery(String type, XContentParser parser) { private Query parseQuery(String type, XContentParser parser) {
String[] previousTypes = null; String[] previousTypes = null;
if (type != null) { if (type != null) {
QueryParseContext.setTypesWithPrevious(new String[]{type}); QueryShardContext.setTypesWithPrevious(new String[]{type});
} }
QueryParseContext context = queryParserService.getParseContext(); QueryShardContext context = queryParserService.getShardContext();
try { try {
context.reset(parser); context.reset(parser);
// This means that fields in the query need to exist in the mapping prior to registering this query // This means that fields in the query need to exist in the mapping prior to registering this query
@ -208,10 +209,10 @@ public class PercolatorQueriesRegistry extends AbstractIndexShardComponent imple
context.setMapUnmappedFieldAsString(mapUnmappedFieldsAsString ? true : false); context.setMapUnmappedFieldAsString(mapUnmappedFieldsAsString ? true : false);
return queryParserService.parseInnerQuery(context); return queryParserService.parseInnerQuery(context);
} catch (IOException e) { } catch (IOException e) {
throw new QueryParsingException(context, "Failed to parse", e); throw new QueryParsingException(context.parseContext(), "Failed to parse", e);
} finally { } finally {
if (type != null) { if (type != null) {
QueryParseContext.setTypes(previousTypes); QueryShardContext.setTypes(previousTypes);
} }
context.reset(null); context.reset(null);
} }

View File

@ -68,20 +68,20 @@ public abstract class AbstractQueryBuilder<QB extends AbstractQueryBuilder> exte
} }
@Override @Override
public final Query toQuery(QueryParseContext parseContext) throws IOException { public final Query toQuery(QueryShardContext context) throws IOException {
Query query = doToQuery(parseContext); Query query = doToQuery(context);
if (query != null) { if (query != null) {
query.setBoost(boost); query.setBoost(boost);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
} }
return query; return query;
} }
//norelease to be made abstract once all query builders override doToQuery providing their own specific implementation. //norelease to be made abstract once all query builders override doToQuery providing their own specific implementation.
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
return parseContext.indexQueryParserService().queryParser(getName()).parse(parseContext); return context.indexQueryParserService().queryParser(getName()).parse(context);
} }
@Override @Override
@ -219,17 +219,17 @@ public abstract class AbstractQueryBuilder<QB extends AbstractQueryBuilder> exte
/** /**
* Helper method to convert collection of {@link QueryBuilder} instances to lucene * Helper method to convert collection of {@link QueryBuilder} instances to lucene
* {@link Query} instances. {@link QueryBuilder} that return <tt>null</tt> calling * {@link Query} instances. {@link QueryBuilder} that return <tt>null</tt> calling
* their {@link QueryBuilder#toQuery(QueryParseContext)} method are not added to the * their {@link QueryBuilder#toQuery(QueryShardContext)} method are not added to the
* resulting collection. * resulting collection.
* *
* @throws IOException * @throws IOException
* @throws QueryParsingException * @throws QueryShardException
*/ */
protected static Collection<Query> toQueries(Collection<QueryBuilder> queryBuilders, QueryParseContext parseContext) throws QueryParsingException, protected static Collection<Query> toQueries(Collection<QueryBuilder> queryBuilders, QueryShardContext context) throws QueryShardException,
IOException { IOException {
List<Query> queries = new ArrayList<>(queryBuilders.size()); List<Query> queries = new ArrayList<>(queryBuilders.size());
for (QueryBuilder queryBuilder : queryBuilders) { for (QueryBuilder queryBuilder : queryBuilders) {
Query query = queryBuilder.toQuery(parseContext); Query query = queryBuilder.toQuery(context);
if (query != null) { if (query != null) {
queries.add(query); queries.add(query);
} }

View File

@ -84,7 +84,7 @@ public class AndQueryBuilder extends AbstractQueryBuilder<AndQueryBuilder> {
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
if (filters.isEmpty()) { if (filters.isEmpty()) {
// no filters provided, this should be ignored upstream // no filters provided, this should be ignored upstream
return null; return null;
@ -92,7 +92,7 @@ public class AndQueryBuilder extends AbstractQueryBuilder<AndQueryBuilder> {
BooleanQuery query = new BooleanQuery(); BooleanQuery query = new BooleanQuery();
for (QueryBuilder f : filters) { for (QueryBuilder f : filters) {
Query innerQuery = f.toQuery(parseContext); Query innerQuery = f.toQuery(context);
// ignore queries that are null // ignore queries that are null
if (innerQuery != null) { if (innerQuery != null) {
query.add(innerQuery, Occur.MUST); query.add(innerQuery, Occur.MUST);

View File

@ -26,14 +26,14 @@ import java.io.IOException;
/** /**
* Class used during the query parsers refactoring. Will be removed once we can parse search requests on the coordinating node. * Class used during the query parsers refactoring. Will be removed once we can parse search requests on the coordinating node.
* All query parsers that have a refactored "fromXContent" method can be changed to extend this instead of {@link BaseQueryParserTemp}. * All query parsers that have a refactored "fromXContent" method can be changed to extend this instead of {@link BaseQueryParserTemp}.
* Keeps old {@link QueryParser#parse(QueryParseContext)} method as a stub delegating to * Keeps old {@link QueryParser#parse(QueryShardContext)} method as a stub delegating to
* {@link QueryParser#fromXContent(QueryParseContext)} and {@link QueryBuilder#toQuery(QueryParseContext)}} * {@link QueryParser#fromXContent(QueryShardContext)} and {@link QueryBuilder#toQuery(QueryShardContext)}}
*/ */
//norelease needs to be removed once we parse search requests on the coordinating node, as the parse method is not needed anymore at that point. //norelease needs to be removed once we parse search requests on the coordinating node, as the parse method is not needed anymore at that point.
public abstract class BaseQueryParser implements QueryParser { public abstract class BaseQueryParser implements QueryParser {
@Override @Override
public final Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public final Query parse(QueryShardContext context) throws IOException, QueryParsingException {
return fromXContent(parseContext).toQuery(parseContext); return fromXContent(context.parseContext()).toQuery(context);
} }
} }

View File

@ -33,7 +33,7 @@ public abstract class BaseQueryParserTemp implements QueryParser {
@Override @Override
public QueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, QueryParsingException { public QueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, QueryParsingException {
Query query = parse(parseContext); Query query = parse(parseContext.shardContext());
return new QueryWrappingQueryBuilder(query); return new QueryWrappingQueryBuilder(query);
} }
} }

View File

@ -254,12 +254,12 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
BooleanQuery booleanQuery = new BooleanQuery(disableCoord); BooleanQuery booleanQuery = new BooleanQuery(disableCoord);
addBooleanClauses(parseContext, booleanQuery, mustClauses, BooleanClause.Occur.MUST); addBooleanClauses(context, booleanQuery, mustClauses, BooleanClause.Occur.MUST);
addBooleanClauses(parseContext, booleanQuery, mustNotClauses, BooleanClause.Occur.MUST_NOT); addBooleanClauses(context, booleanQuery, mustNotClauses, BooleanClause.Occur.MUST_NOT);
addBooleanClauses(parseContext, booleanQuery, shouldClauses, BooleanClause.Occur.SHOULD); addBooleanClauses(context, booleanQuery, shouldClauses, BooleanClause.Occur.SHOULD);
addBooleanClauses(parseContext, booleanQuery, filterClauses, BooleanClause.Occur.FILTER); addBooleanClauses(context, booleanQuery, filterClauses, BooleanClause.Occur.FILTER);
if (booleanQuery.clauses().isEmpty()) { if (booleanQuery.clauses().isEmpty()) {
return new MatchAllDocsQuery(); return new MatchAllDocsQuery();
@ -279,9 +279,9 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
return validationException; return validationException;
} }
private static void addBooleanClauses(QueryParseContext parseContext, BooleanQuery booleanQuery, List<QueryBuilder> clauses, Occur occurs) throws IOException { private static void addBooleanClauses(QueryShardContext context, BooleanQuery booleanQuery, List<QueryBuilder> clauses, Occur occurs) throws IOException {
for (QueryBuilder query : clauses) { for (QueryBuilder query : clauses) {
Query luceneQuery = query.toQuery(parseContext); Query luceneQuery = query.toQuery(context);
if (luceneQuery != null) { if (luceneQuery != null) {
booleanQuery.add(new BooleanClause(luceneQuery, occurs)); booleanQuery.add(new BooleanClause(luceneQuery, occurs));
} }

View File

@ -129,9 +129,9 @@ public class BoostingQueryBuilder extends AbstractQueryBuilder<BoostingQueryBuil
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query positive = positiveQuery.toQuery(parseContext); Query positive = positiveQuery.toQuery(context);
Query negative = negativeQuery.toQuery(parseContext); Query negative = negativeQuery.toQuery(context);
// make upstream queries ignore this query by returning `null` // make upstream queries ignore this query by returning `null`
// if either inner query builder returns null // if either inner query builder returns null
if (positive == null || negative == null) { if (positive == null || negative == null) {

View File

@ -42,7 +42,7 @@ import java.util.Objects;
* CommonTermsQuery query is a query that executes high-frequency terms in a * CommonTermsQuery query is a query that executes high-frequency terms in a
* optional sub-query to prevent slow queries due to "common" terms like * optional sub-query to prevent slow queries due to "common" terms like
* stopwords. This query basically builds 2 queries off the * stopwords. This query basically builds 2 queries off the
* {@link org.apache.lucene.queries.CommonTermsQuery#add(Term) added} terms * {@link org.apache.lucene.queries.CommonTermsQuery#add(Term) added} terms
* where low-frequency terms are added to a required boolean clause * where low-frequency terms are added to a required boolean clause
* and high-frequency terms are added to an optional boolean clause. The * and high-frequency terms are added to an optional boolean clause. The
* optional clause is only executed if the required "low-frequency' clause * optional clause is only executed if the required "low-frequency' clause
@ -154,7 +154,7 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
this.cutoffFrequency = cutoffFrequency; this.cutoffFrequency = cutoffFrequency;
return this; return this;
} }
public float cutoffFrequency() { public float cutoffFrequency() {
return this.cutoffFrequency; return this.cutoffFrequency;
} }
@ -180,7 +180,7 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
this.lowFreqMinimumShouldMatch = lowFreqMinimumShouldMatch; this.lowFreqMinimumShouldMatch = lowFreqMinimumShouldMatch;
return this; return this;
} }
public String lowFreqMinimumShouldMatch() { public String lowFreqMinimumShouldMatch() {
return this.lowFreqMinimumShouldMatch; return this.lowFreqMinimumShouldMatch;
} }
@ -228,9 +228,9 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
String field; String field;
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType != null) { if (fieldType != null) {
field = fieldType.names().indexName(); field = fieldType.names().indexName();
} else { } else {
@ -240,25 +240,25 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
Analyzer analyzerObj; Analyzer analyzerObj;
if (analyzer == null) { if (analyzer == null) {
if (fieldType != null) { if (fieldType != null) {
analyzerObj = parseContext.getSearchAnalyzer(fieldType); analyzerObj = context.getSearchAnalyzer(fieldType);
} else { } else {
analyzerObj = parseContext.mapperService().searchAnalyzer(); analyzerObj = context.mapperService().searchAnalyzer();
} }
} else { } else {
analyzerObj = parseContext.mapperService().analysisService().analyzer(analyzer); analyzerObj = context.mapperService().analysisService().analyzer(analyzer);
if (analyzerObj == null) { if (analyzerObj == null) {
throw new IllegalArgumentException("no analyzer found for [" + analyzer + "]"); throw new QueryShardException(context, "[common] analyzer [" + analyzer + "] not found");
} }
} }
Occur highFreqOccur = highFreqOperator.toBooleanClauseOccur(); Occur highFreqOccur = highFreqOperator.toBooleanClauseOccur();
Occur lowFreqOccur = lowFreqOperator.toBooleanClauseOccur(); Occur lowFreqOccur = lowFreqOperator.toBooleanClauseOccur();
ExtendedCommonTermsQuery commonsQuery = new ExtendedCommonTermsQuery(highFreqOccur, lowFreqOccur, cutoffFrequency, disableCoord, fieldType); ExtendedCommonTermsQuery commonsQuery = new ExtendedCommonTermsQuery(highFreqOccur, lowFreqOccur, cutoffFrequency, disableCoord, fieldType);
return parseQueryString(commonsQuery, text, field, analyzerObj, lowFreqMinimumShouldMatch, highFreqMinimumShouldMatch); return parseQueryString(commonsQuery, text, field, analyzerObj, lowFreqMinimumShouldMatch, highFreqMinimumShouldMatch);
} }
static Query parseQueryString(ExtendedCommonTermsQuery query, Object queryString, String field, Analyzer analyzer, static Query parseQueryString(ExtendedCommonTermsQuery query, Object queryString, String field, Analyzer analyzer,
String lowFreqMinimumShouldMatch, String highFreqMinimumShouldMatch) throws IOException { String lowFreqMinimumShouldMatch, String highFreqMinimumShouldMatch) throws IOException {
// Logic similar to QueryParser#getFieldQuery // Logic similar to QueryParser#getFieldQuery
int count = 0; int count = 0;

View File

@ -87,9 +87,6 @@ public class CommonTermsQueryParser extends BaseQueryParser {
text = parser.objectText(); text = parser.objectText();
} else if ("analyzer".equals(currentFieldName)) { } else if ("analyzer".equals(currentFieldName)) {
analyzer = parser.text(); analyzer = parser.text();
if (parseContext.analysisService().analyzer(analyzer) == null) {
throw new QueryParsingException(parseContext, "[common] analyzer [" + parser.text() + "] not found");
}
} else if ("disable_coord".equals(currentFieldName) || "disableCoord".equals(currentFieldName)) { } else if ("disable_coord".equals(currentFieldName) || "disableCoord".equals(currentFieldName)) {
disableCoord = parser.booleanValue(); disableCoord = parser.booleanValue();
} else if ("boost".equals(currentFieldName)) { } else if ("boost".equals(currentFieldName)) {

View File

@ -67,13 +67,13 @@ public class ConstantScoreQueryBuilder extends AbstractQueryBuilder<ConstantScor
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query innerFilter = filterBuilder.toQuery(parseContext); Query innerFilter = filterBuilder.toQuery(context);
if (innerFilter == null ) { if (innerFilter == null ) {
// return null so that parent queries (e.g. bool) also ignore this // return null so that parent queries (e.g. bool) also ignore this
return null; return null;
} }
return new ConstantScoreQuery(filterBuilder.toQuery(parseContext)); return new ConstantScoreQuery(filterBuilder.toQuery(context));
} }
@Override @Override

View File

@ -96,9 +96,9 @@ public class DisMaxQueryBuilder extends AbstractQueryBuilder<DisMaxQueryBuilder>
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
// return null if there are no queries at all // return null if there are no queries at all
Collection<Query> luceneQueries = toQueries(queries, parseContext); Collection<Query> luceneQueries = toQueries(queries, context);
if (luceneQueries.isEmpty()) { if (luceneQueries.isEmpty()) {
return null; return null;
} }

View File

@ -62,7 +62,7 @@ public class EmptyQueryBuilder extends ToXContentToBytes implements QueryBuilder
} }
@Override @Override
public Query toQuery(QueryParseContext parseContext) throws IOException { public Query toQuery(QueryShardContext context) throws IOException {
// empty // empty
return null; return null;
} }

View File

@ -63,8 +63,8 @@ public class ExistsQueryBuilder extends AbstractQueryBuilder<ExistsQueryBuilder>
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
return newFilter(parseContext, name); return newFilter(context, name);
} }
@Override @Override
@ -73,20 +73,20 @@ public class ExistsQueryBuilder extends AbstractQueryBuilder<ExistsQueryBuilder>
return null; return null;
} }
public static Query newFilter(QueryParseContext parseContext, String fieldPattern) { public static Query newFilter(QueryShardContext context, String fieldPattern) {
final FieldNamesFieldMapper.FieldNamesFieldType fieldNamesFieldType = (FieldNamesFieldMapper.FieldNamesFieldType)parseContext.mapperService().fullName(FieldNamesFieldMapper.NAME); final FieldNamesFieldMapper.FieldNamesFieldType fieldNamesFieldType = (FieldNamesFieldMapper.FieldNamesFieldType)context.mapperService().fullName(FieldNamesFieldMapper.NAME);
if (fieldNamesFieldType == null) { if (fieldNamesFieldType == null) {
// can only happen when no types exist, so no docs exist either // can only happen when no types exist, so no docs exist either
return Queries.newMatchNoDocsQuery(); return Queries.newMatchNoDocsQuery();
} }
ObjectMapper objectMapper = parseContext.getObjectMapper(fieldPattern); ObjectMapper objectMapper = context.getObjectMapper(fieldPattern);
if (objectMapper != null) { if (objectMapper != null) {
// automatic make the object mapper pattern // automatic make the object mapper pattern
fieldPattern = fieldPattern + ".*"; fieldPattern = fieldPattern + ".*";
} }
Collection<String> fields = parseContext.simpleMatchToIndexNames(fieldPattern); Collection<String> fields = context.simpleMatchToIndexNames(fieldPattern);
if (fields.isEmpty()) { if (fields.isEmpty()) {
// no fields exists, so we should not match anything // no fields exists, so we should not match anything
return Queries.newMatchNoDocsQuery(); return Queries.newMatchNoDocsQuery();
@ -94,7 +94,7 @@ public class ExistsQueryBuilder extends AbstractQueryBuilder<ExistsQueryBuilder>
BooleanQuery boolFilter = new BooleanQuery(); BooleanQuery boolFilter = new BooleanQuery();
for (String field : fields) { for (String field : fields) {
MappedFieldType fieldType = parseContext.fieldMapper(field); MappedFieldType fieldType = context.fieldMapper(field);
Query filter = null; Query filter = null;
if (fieldNamesFieldType.isEnabled()) { if (fieldNamesFieldType.isEnabled()) {
final String f; final String f;
@ -103,7 +103,7 @@ public class ExistsQueryBuilder extends AbstractQueryBuilder<ExistsQueryBuilder>
} else { } else {
f = field; f = field;
} }
filter = fieldNamesFieldType.termQuery(f, parseContext); filter = fieldNamesFieldType.termQuery(f, context);
} }
// if _field_names are not indexed, we need to go the slow way // if _field_names are not indexed, we need to go the slow way
if (filter == null && fieldType != null) { if (filter == null && fieldType != null) {

View File

@ -69,9 +69,9 @@ public class FQueryFilterBuilder extends AbstractQueryBuilder<FQueryFilterBuilde
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
// inner query builder can potentially be `null`, in that case we ignore it // inner query builder can potentially be `null`, in that case we ignore it
Query innerQuery = this.queryBuilder.toQuery(parseContext); Query innerQuery = this.queryBuilder.toQuery(context);
if (innerQuery == null) { if (innerQuery == null) {
return null; return null;
} }

View File

@ -76,13 +76,13 @@ public class FieldMaskingSpanQueryBuilder extends AbstractQueryBuilder<FieldMask
} }
@Override @Override
protected SpanQuery doToQuery(QueryParseContext parseContext) throws IOException { protected SpanQuery doToQuery(QueryShardContext context) throws IOException {
String fieldInQuery = fieldName; String fieldInQuery = fieldName;
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType != null) { if (fieldType != null) {
fieldInQuery = fieldType.names().indexName(); fieldInQuery = fieldType.names().indexName();
} }
Query innerQuery = queryBuilder.toQuery(parseContext); Query innerQuery = queryBuilder.toQuery(context);
assert innerQuery instanceof SpanQuery; assert innerQuery instanceof SpanQuery;
return new FieldMaskingSpanQuery((SpanQuery)innerQuery, fieldInQuery); return new FieldMaskingSpanQuery((SpanQuery)innerQuery, fieldInQuery);
} }

View File

@ -95,9 +95,9 @@ public class FilteredQueryBuilder extends AbstractQueryBuilder<FilteredQueryBuil
} }
@Override @Override
public Query doToQuery(QueryParseContext parseContext) throws QueryParsingException, IOException { public Query doToQuery(QueryShardContext context) throws QueryShardException, IOException {
Query query = queryBuilder.toQuery(parseContext); Query query = queryBuilder.toQuery(context);
Query filter = filterBuilder.toQuery(parseContext); Query filter = filterBuilder.toQuery(context);
if (query == null) { if (query == null) {
// Most likely this query was generated from the JSON query DSL - it parsed to an EmptyQueryBuilder so we ignore // Most likely this query was generated from the JSON query DSL - it parsed to an EmptyQueryBuilder so we ignore

View File

@ -52,7 +52,8 @@ public class FuzzyQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken(); XContentParser.Token token = parser.nextToken();
@ -112,9 +113,9 @@ public class FuzzyQueryParser extends BaseQueryParserTemp {
if (value == null) { if (value == null) {
throw new QueryParsingException(parseContext, "No value specified for fuzzy query"); throw new QueryParsingException(parseContext, "No value specified for fuzzy query");
} }
Query query = null; Query query = null;
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType != null) { if (fieldType != null) {
query = fieldType.fuzzyQuery(value, fuzziness, prefixLength, maxExpansions, transpositions); query = fieldType.fuzzyQuery(value, fuzziness, prefixLength, maxExpansions, transpositions);
} }
@ -128,7 +129,7 @@ public class FuzzyQueryParser extends BaseQueryParserTemp {
query.setBoost(boost); query.setBoost(boost);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
return query; return query;
} }

View File

@ -67,7 +67,8 @@ public class GeoBoundingBoxQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -164,7 +165,7 @@ public class GeoBoundingBoxQueryParser extends BaseQueryParserTemp {
} }
} }
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType == null) { if (fieldType == null) {
throw new QueryParsingException(parseContext, "failed to parse [{}] query. could not find [{}] field [{}]", NAME, GeoPointFieldMapper.CONTENT_TYPE, fieldName); throw new QueryParsingException(parseContext, "failed to parse [{}] query. could not find [{}] field [{}]", NAME, GeoPointFieldMapper.CONTENT_TYPE, fieldName);
} }
@ -177,7 +178,7 @@ public class GeoBoundingBoxQueryParser extends BaseQueryParserTemp {
if ("indexed".equals(type)) { if ("indexed".equals(type)) {
filter = IndexedGeoBoundingBoxQuery.create(topLeft, bottomRight, geoFieldType); filter = IndexedGeoBoundingBoxQuery.create(topLeft, bottomRight, geoFieldType);
} else if ("memory".equals(type)) { } else if ("memory".equals(type)) {
IndexGeoPointFieldData indexFieldData = parseContext.getForField(fieldType); IndexGeoPointFieldData indexFieldData = context.getForField(fieldType);
filter = new InMemoryGeoBoundingBoxQuery(topLeft, bottomRight, indexFieldData); filter = new InMemoryGeoBoundingBoxQuery(topLeft, bottomRight, indexFieldData);
} else { } else {
throw new QueryParsingException(parseContext, "failed to parse [{}] query. geo bounding box type [{}] is not supported. either [indexed] or [memory] are allowed", NAME, type); throw new QueryParsingException(parseContext, "failed to parse [{}] query. geo bounding box type [{}] is not supported. either [indexed] or [memory] are allowed", NAME, type);
@ -186,7 +187,7 @@ public class GeoBoundingBoxQueryParser extends BaseQueryParserTemp {
filter.setBoost(boost); filter.setBoost(boost);
} }
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, filter); context.addNamedQuery(queryName, filter);
} }
return filter; return filter;
} }

View File

@ -54,7 +54,8 @@ public class GeoDistanceQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
XContentParser.Token token; XContentParser.Token token;
@ -148,7 +149,7 @@ public class GeoDistanceQueryParser extends BaseQueryParserTemp {
GeoUtils.normalizePoint(point, normalizeLat, normalizeLon); GeoUtils.normalizePoint(point, normalizeLat, normalizeLon);
} }
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType == null) { if (fieldType == null) {
throw new QueryParsingException(parseContext, "failed to find geo_point field [" + fieldName + "]"); throw new QueryParsingException(parseContext, "failed to find geo_point field [" + fieldName + "]");
} }
@ -158,10 +159,10 @@ public class GeoDistanceQueryParser extends BaseQueryParserTemp {
GeoPointFieldMapper.GeoPointFieldType geoFieldType = ((GeoPointFieldMapper.GeoPointFieldType) fieldType); GeoPointFieldMapper.GeoPointFieldType geoFieldType = ((GeoPointFieldMapper.GeoPointFieldType) fieldType);
IndexGeoPointFieldData indexFieldData = parseContext.getForField(fieldType); IndexGeoPointFieldData indexFieldData = context.getForField(fieldType);
Query query = new GeoDistanceRangeQuery(point, null, distance, true, false, geoDistance, geoFieldType, indexFieldData, optimizeBbox); Query query = new GeoDistanceRangeQuery(point, null, distance, true, false, geoDistance, geoFieldType, indexFieldData, optimizeBbox);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
query.setBoost(boost); query.setBoost(boost);
return query; return query;

View File

@ -54,7 +54,8 @@ public class GeoDistanceRangeQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
XContentParser.Token token; XContentParser.Token token;
@ -188,7 +189,7 @@ public class GeoDistanceRangeQueryParser extends BaseQueryParserTemp {
GeoUtils.normalizePoint(point, normalizeLat, normalizeLon); GeoUtils.normalizePoint(point, normalizeLat, normalizeLon);
} }
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType == null) { if (fieldType == null) {
throw new QueryParsingException(parseContext, "failed to find geo_point field [" + fieldName + "]"); throw new QueryParsingException(parseContext, "failed to find geo_point field [" + fieldName + "]");
} }
@ -197,10 +198,10 @@ public class GeoDistanceRangeQueryParser extends BaseQueryParserTemp {
} }
GeoPointFieldMapper.GeoPointFieldType geoFieldType = ((GeoPointFieldMapper.GeoPointFieldType) fieldType); GeoPointFieldMapper.GeoPointFieldType geoFieldType = ((GeoPointFieldMapper.GeoPointFieldType) fieldType);
IndexGeoPointFieldData indexFieldData = parseContext.getForField(fieldType); IndexGeoPointFieldData indexFieldData = context.getForField(fieldType);
Query query = new GeoDistanceRangeQuery(point, from, to, includeLower, includeUpper, geoDistance, geoFieldType, indexFieldData, optimizeBbox); Query query = new GeoDistanceRangeQuery(point, from, to, includeLower, includeUpper, geoDistance, geoFieldType, indexFieldData, optimizeBbox);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
query.setBoost(boost); query.setBoost(boost);
return query; return query;

View File

@ -60,7 +60,8 @@ public class GeoPolygonQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -140,7 +141,7 @@ public class GeoPolygonQueryParser extends BaseQueryParserTemp {
} }
} }
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType == null) { if (fieldType == null) {
throw new QueryParsingException(parseContext, "failed to find geo_point field [" + fieldName + "]"); throw new QueryParsingException(parseContext, "failed to find geo_point field [" + fieldName + "]");
} }
@ -148,10 +149,10 @@ public class GeoPolygonQueryParser extends BaseQueryParserTemp {
throw new QueryParsingException(parseContext, "field [" + fieldName + "] is not a geo_point field"); throw new QueryParsingException(parseContext, "field [" + fieldName + "] is not a geo_point field");
} }
IndexGeoPointFieldData indexFieldData = parseContext.getForField(fieldType); IndexGeoPointFieldData indexFieldData = context.getForField(fieldType);
Query query = new GeoPolygonQuery(indexFieldData, shell.toArray(new GeoPoint[shell.size()])); Query query = new GeoPolygonQuery(indexFieldData, shell.toArray(new GeoPoint[shell.size()]));
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
query.setBoost(boost); query.setBoost(boost);
return query; return query;

View File

@ -53,7 +53,8 @@ public class GeoShapeQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -136,7 +137,7 @@ public class GeoShapeQueryParser extends BaseQueryParserTemp {
throw new QueryParsingException(parseContext, "No Shape Relation defined"); throw new QueryParsingException(parseContext, "No Shape Relation defined");
} }
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType == null) { if (fieldType == null) {
throw new QueryParsingException(parseContext, "Failed to find geo_shape field [" + fieldName + "]"); throw new QueryParsingException(parseContext, "Failed to find geo_shape field [" + fieldName + "]");
} }
@ -157,7 +158,7 @@ public class GeoShapeQueryParser extends BaseQueryParserTemp {
// this strategy doesn't support disjoint anymore: but it did before, including creating lucene fieldcache (!) // this strategy doesn't support disjoint anymore: but it did before, including creating lucene fieldcache (!)
// in this case, execute disjoint as exists && !intersects // in this case, execute disjoint as exists && !intersects
BooleanQuery bool = new BooleanQuery(); BooleanQuery bool = new BooleanQuery();
Query exists = ExistsQueryBuilder.newFilter(parseContext, fieldName); Query exists = ExistsQueryBuilder.newFilter(context, fieldName);
Filter intersects = strategy.makeFilter(getArgs(shape, ShapeRelation.INTERSECTS)); Filter intersects = strategy.makeFilter(getArgs(shape, ShapeRelation.INTERSECTS));
bool.add(exists, BooleanClause.Occur.MUST); bool.add(exists, BooleanClause.Occur.MUST);
bool.add(intersects, BooleanClause.Occur.MUST_NOT); bool.add(intersects, BooleanClause.Occur.MUST_NOT);
@ -167,7 +168,7 @@ public class GeoShapeQueryParser extends BaseQueryParserTemp {
} }
query.setBoost(boost); query.setBoost(boost);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
return query; return query;
} }

View File

@ -69,7 +69,7 @@ public class GeohashCellQuery {
* @param geohashes optional array of additional geohashes * @param geohashes optional array of additional geohashes
* @return a new GeoBoundinboxfilter * @return a new GeoBoundinboxfilter
*/ */
public static Query create(QueryParseContext context, GeoPointFieldMapper.GeoPointFieldType fieldType, String geohash, @Nullable List<CharSequence> geohashes) { public static Query create(QueryShardContext context, GeoPointFieldMapper.GeoPointFieldType fieldType, String geohash, @Nullable List<CharSequence> geohashes) {
MappedFieldType geoHashMapper = fieldType.geohashFieldType(); MappedFieldType geoHashMapper = fieldType.geohashFieldType();
if (geoHashMapper == null) { if (geoHashMapper == null) {
throw new IllegalArgumentException("geohash filter needs geohash_prefix to be enabled"); throw new IllegalArgumentException("geohash filter needs geohash_prefix to be enabled");
@ -186,7 +186,8 @@ public class GeohashCellQuery {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -248,7 +249,7 @@ public class GeohashCellQuery {
throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing geohash value", NAME); throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing geohash value", NAME);
} }
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType == null) { if (fieldType == null) {
throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing [{}] field [{}]", NAME, GeoPointFieldMapper.CONTENT_TYPE, fieldName); throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing [{}] field [{}]", NAME, GeoPointFieldMapper.CONTENT_TYPE, fieldName);
} }
@ -269,12 +270,12 @@ public class GeohashCellQuery {
Query filter; Query filter;
if (neighbors) { if (neighbors) {
filter = create(parseContext, geoFieldType, geohash, GeoHashUtils.addNeighbors(geohash, new ArrayList<CharSequence>(8))); filter = create(context, geoFieldType, geohash, GeoHashUtils.addNeighbors(geohash, new ArrayList<CharSequence>(8)));
} else { } else {
filter = create(parseContext, geoFieldType, geohash, null); filter = create(context, geoFieldType, geohash, null);
} }
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, filter); context.addNamedQuery(queryName, filter);
} }
if (filter != null) { if (filter != null) {
filter.setBoost(boost); filter.setBoost(boost);

View File

@ -22,9 +22,6 @@ package org.elasticsearch.index.query;
import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiDocValues; import org.apache.lucene.index.MultiDocValues;
import org.apache.lucene.search.*; import org.apache.lucene.search.*;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryWrapperFilter;
import org.apache.lucene.search.join.BitDocIdSetFilter; import org.apache.lucene.search.join.BitDocIdSetFilter;
import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParseField;
import org.apache.lucene.search.join.JoinUtil; import org.apache.lucene.search.join.JoinUtil;
@ -70,7 +67,8 @@ public class HasChildQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
boolean queryFound = false; boolean queryFound = false;
@ -140,7 +138,7 @@ public class HasChildQueryParser extends BaseQueryParserTemp {
} }
innerQuery.setBoost(boost); innerQuery.setBoost(boost);
DocumentMapper childDocMapper = parseContext.mapperService().documentMapper(childType); DocumentMapper childDocMapper = context.mapperService().documentMapper(childType);
if (childDocMapper == null) { if (childDocMapper == null) {
throw new QueryParsingException(parseContext, "[has_child] No mapping for for type [" + childType + "]"); throw new QueryParsingException(parseContext, "[has_child] No mapping for for type [" + childType + "]");
} }
@ -150,14 +148,14 @@ public class HasChildQueryParser extends BaseQueryParserTemp {
} }
if (innerHits != null) { if (innerHits != null) {
ParsedQuery parsedQuery = new ParsedQuery(innerQuery, parseContext.copyNamedQueries()); ParsedQuery parsedQuery = new ParsedQuery(innerQuery, context.copyNamedQueries());
InnerHitsContext.ParentChildInnerHits parentChildInnerHits = new InnerHitsContext.ParentChildInnerHits(innerHits.v2(), parsedQuery, null, parseContext.mapperService(), childDocMapper); InnerHitsContext.ParentChildInnerHits parentChildInnerHits = new InnerHitsContext.ParentChildInnerHits(innerHits.v2(), parsedQuery, null, context.mapperService(), childDocMapper);
String name = innerHits.v1() != null ? innerHits.v1() : childType; String name = innerHits.v1() != null ? innerHits.v1() : childType;
parseContext.addInnerHits(name, parentChildInnerHits); context.addInnerHits(name, parentChildInnerHits);
} }
String parentType = parentFieldMapper.type(); String parentType = parentFieldMapper.type();
DocumentMapper parentDocMapper = parseContext.mapperService().documentMapper(parentType); DocumentMapper parentDocMapper = context.mapperService().documentMapper(parentType);
if (parentDocMapper == null) { if (parentDocMapper == null) {
throw new QueryParsingException(parseContext, "[has_child] Type [" + childType + "] points to a non existent parent type [" throw new QueryParsingException(parseContext, "[has_child] Type [" + childType + "] points to a non existent parent type ["
+ parentType + "]"); + parentType + "]");
@ -169,15 +167,15 @@ public class HasChildQueryParser extends BaseQueryParserTemp {
BitDocIdSetFilter nonNestedDocsFilter = null; BitDocIdSetFilter nonNestedDocsFilter = null;
if (parentDocMapper.hasNestedObjects()) { if (parentDocMapper.hasNestedObjects()) {
nonNestedDocsFilter = parseContext.bitsetFilter(Queries.newNonNestedFilter()); nonNestedDocsFilter = context.bitsetFilter(Queries.newNonNestedFilter());
} }
// wrap the query with type query // wrap the query with type query
innerQuery = Queries.filtered(innerQuery, childDocMapper.typeFilter()); innerQuery = Queries.filtered(innerQuery, childDocMapper.typeFilter());
final Query query; final Query query;
final ParentChildIndexFieldData parentChildIndexFieldData = parseContext.getForField(parentFieldMapper.fieldType()); final ParentChildIndexFieldData parentChildIndexFieldData = context.getForField(parentFieldMapper.fieldType());
if (parseContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) { if (context.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) {
query = joinUtilHelper(parentType, parentChildIndexFieldData, parentDocMapper.typeFilter(), scoreType, innerQuery, minChildren, maxChildren); query = joinUtilHelper(parentType, parentChildIndexFieldData, parentDocMapper.typeFilter(), scoreType, innerQuery, minChildren, maxChildren);
} else { } else {
// TODO: use the query API // TODO: use the query API
@ -191,7 +189,7 @@ public class HasChildQueryParser extends BaseQueryParserTemp {
} }
} }
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
query.setBoost(boost); query.setBoost(boost);
return query; return query;
@ -288,7 +286,7 @@ public class HasChildQueryParser extends BaseQueryParserTemp {
return "LateParsingQuery {parentType=" + parentType + "}"; return "LateParsingQuery {parentType=" + parentType + "}";
} }
} }
@Override @Override
public HasChildQueryBuilder getBuilderPrototype() { public HasChildQueryBuilder getBuilderPrototype() {
return HasChildQueryBuilder.PROTOTYPE; return HasChildQueryBuilder.PROTOTYPE;

View File

@ -64,7 +64,8 @@ public class HasParentQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
boolean queryFound = false; boolean queryFound = false;
@ -133,40 +134,40 @@ public class HasParentQueryParser extends BaseQueryParserTemp {
} }
innerQuery.setBoost(boost); innerQuery.setBoost(boost);
Query query = createParentQuery(innerQuery, parentType, score, parseContext, innerHits); Query query = createParentQuery(innerQuery, parentType, score, context, innerHits);
if (query == null) { if (query == null) {
return null; return null;
} }
query.setBoost(boost); query.setBoost(boost);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
return query; return query;
} }
static Query createParentQuery(Query innerQuery, String parentType, boolean score, QueryParseContext parseContext, Tuple<String, SubSearchContext> innerHits) throws IOException { static Query createParentQuery(Query innerQuery, String parentType, boolean score, QueryShardContext context, Tuple<String, SubSearchContext> innerHits) throws IOException {
DocumentMapper parentDocMapper = parseContext.mapperService().documentMapper(parentType); DocumentMapper parentDocMapper = context.mapperService().documentMapper(parentType);
if (parentDocMapper == null) { if (parentDocMapper == null) {
throw new QueryParsingException(parseContext, "[has_parent] query configured 'parent_type' [" + parentType throw new QueryParsingException(context.parseContext(), "[has_parent] query configured 'parent_type' [" + parentType
+ "] is not a valid type"); + "] is not a valid type");
} }
if (innerHits != null) { if (innerHits != null) {
ParsedQuery parsedQuery = new ParsedQuery(innerQuery, parseContext.copyNamedQueries()); ParsedQuery parsedQuery = new ParsedQuery(innerQuery, context.copyNamedQueries());
InnerHitsContext.ParentChildInnerHits parentChildInnerHits = new InnerHitsContext.ParentChildInnerHits(innerHits.v2(), parsedQuery, null, parseContext.mapperService(), parentDocMapper); InnerHitsContext.ParentChildInnerHits parentChildInnerHits = new InnerHitsContext.ParentChildInnerHits(innerHits.v2(), parsedQuery, null, context.mapperService(), parentDocMapper);
String name = innerHits.v1() != null ? innerHits.v1() : parentType; String name = innerHits.v1() != null ? innerHits.v1() : parentType;
parseContext.addInnerHits(name, parentChildInnerHits); context.addInnerHits(name, parentChildInnerHits);
} }
Set<String> parentTypes = new HashSet<>(5); Set<String> parentTypes = new HashSet<>(5);
parentTypes.add(parentDocMapper.type()); parentTypes.add(parentDocMapper.type());
ParentChildIndexFieldData parentChildIndexFieldData = null; ParentChildIndexFieldData parentChildIndexFieldData = null;
for (DocumentMapper documentMapper : parseContext.mapperService().docMappers(false)) { for (DocumentMapper documentMapper : context.mapperService().docMappers(false)) {
ParentFieldMapper parentFieldMapper = documentMapper.parentFieldMapper(); ParentFieldMapper parentFieldMapper = documentMapper.parentFieldMapper();
if (parentFieldMapper.active()) { if (parentFieldMapper.active()) {
DocumentMapper parentTypeDocumentMapper = parseContext.mapperService().documentMapper(parentFieldMapper.type()); DocumentMapper parentTypeDocumentMapper = context.mapperService().documentMapper(parentFieldMapper.type());
parentChildIndexFieldData = parseContext.getForField(parentFieldMapper.fieldType()); parentChildIndexFieldData = context.getForField(parentFieldMapper.fieldType());
if (parentTypeDocumentMapper == null) { if (parentTypeDocumentMapper == null) {
// Only add this, if this parentFieldMapper (also a parent) isn't a child of another parent. // Only add this, if this parentFieldMapper (also a parent) isn't a child of another parent.
parentTypes.add(parentFieldMapper.type()); parentTypes.add(parentFieldMapper.type());
@ -174,19 +175,19 @@ public class HasParentQueryParser extends BaseQueryParserTemp {
} }
} }
if (parentChildIndexFieldData == null) { if (parentChildIndexFieldData == null) {
throw new QueryParsingException(parseContext, "[has_parent] no _parent field configured"); throw new QueryParsingException(context.parseContext(), "[has_parent] no _parent field configured");
} }
Query parentFilter = null; Query parentFilter = null;
if (parentTypes.size() == 1) { if (parentTypes.size() == 1) {
DocumentMapper documentMapper = parseContext.mapperService().documentMapper(parentTypes.iterator().next()); DocumentMapper documentMapper = context.mapperService().documentMapper(parentTypes.iterator().next());
if (documentMapper != null) { if (documentMapper != null) {
parentFilter = documentMapper.typeFilter(); parentFilter = documentMapper.typeFilter();
} }
} else { } else {
BooleanQuery parentsFilter = new BooleanQuery(); BooleanQuery parentsFilter = new BooleanQuery();
for (String parentTypeStr : parentTypes) { for (String parentTypeStr : parentTypes) {
DocumentMapper documentMapper = parseContext.mapperService().documentMapper(parentTypeStr); DocumentMapper documentMapper = context.mapperService().documentMapper(parentTypeStr);
if (documentMapper != null) { if (documentMapper != null) {
parentsFilter.add(documentMapper.typeFilter(), BooleanClause.Occur.SHOULD); parentsFilter.add(documentMapper.typeFilter(), BooleanClause.Occur.SHOULD);
} }
@ -201,7 +202,7 @@ public class HasParentQueryParser extends BaseQueryParserTemp {
// wrap the query with type query // wrap the query with type query
innerQuery = Queries.filtered(innerQuery, parentDocMapper.typeFilter()); innerQuery = Queries.filtered(innerQuery, parentDocMapper.typeFilter());
Filter childrenFilter = new QueryWrapperFilter(Queries.not(parentFilter)); Filter childrenFilter = new QueryWrapperFilter(Queries.not(parentFilter));
if (parseContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) { if (context.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) {
ScoreType scoreMode = score ? ScoreType.MAX : ScoreType.NONE; ScoreType scoreMode = score ? ScoreType.MAX : ScoreType.NONE;
return joinUtilHelper(parentType, parentChildIndexFieldData, childrenFilter, scoreMode, innerQuery, 0, Integer.MAX_VALUE); return joinUtilHelper(parentType, parentChildIndexFieldData, childrenFilter, scoreMode, innerQuery, 0, Integer.MAX_VALUE);
} else { } else {

View File

@ -124,16 +124,16 @@ public class IdsQueryBuilder extends AbstractQueryBuilder<IdsQueryBuilder> {
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query query; Query query;
if (this.ids.isEmpty()) { if (this.ids.isEmpty()) {
query = Queries.newMatchNoDocsQuery(); query = Queries.newMatchNoDocsQuery();
} else { } else {
Collection<String> typesForQuery; Collection<String> typesForQuery;
if (types == null || types.length == 0) { if (types == null || types.length == 0) {
typesForQuery = parseContext.queryTypes(); typesForQuery = context.queryTypes();
} else if (types.length == 1 && MetaData.ALL.equals(types[0])) { } else if (types.length == 1 && MetaData.ALL.equals(types[0])) {
typesForQuery = parseContext.mapperService().types(); typesForQuery = context.mapperService().types();
} else { } else {
typesForQuery = Sets.newHashSet(types); typesForQuery = Sets.newHashSet(types);
} }

View File

@ -53,10 +53,10 @@ public class IndexQueryParserService extends AbstractIndexComponent {
public static final String PARSE_STRICT = "index.query.parse.strict"; public static final String PARSE_STRICT = "index.query.parse.strict";
public static final String ALLOW_UNMAPPED = "index.query.parse.allow_unmapped_fields"; public static final String ALLOW_UNMAPPED = "index.query.parse.allow_unmapped_fields";
private CloseableThreadLocal<QueryParseContext> cache = new CloseableThreadLocal<QueryParseContext>() { private CloseableThreadLocal<QueryShardContext> cache = new CloseableThreadLocal<QueryShardContext>() {
@Override @Override
protected QueryParseContext initialValue() { protected QueryShardContext initialValue() {
return new QueryParseContext(index, IndexQueryParserService.this); return new QueryShardContext(index, IndexQueryParserService.this);
} }
}; };
@ -120,16 +120,20 @@ public class IndexQueryParserService extends AbstractIndexComponent {
return indicesQueriesRegistry.queryParsers().get(name); return indicesQueriesRegistry.queryParsers().get(name);
} }
public IndicesQueriesRegistry indicesQueriesRegistry() {
return indicesQueriesRegistry;
}
public ParsedQuery parse(QueryBuilder queryBuilder) { public ParsedQuery parse(QueryBuilder queryBuilder) {
XContentParser parser = null; XContentParser parser = null;
try { try {
BytesReference bytes = queryBuilder.buildAsBytes(); BytesReference bytes = queryBuilder.buildAsBytes();
parser = XContentFactory.xContent(bytes).createParser(bytes); parser = XContentFactory.xContent(bytes).createParser(bytes);
return parse(cache.get(), parser); return parse(cache.get(), parser);
} catch (QueryParsingException e) { } catch (QueryShardException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new QueryParsingException(getParseContext(), "Failed to parse", e); throw new QueryParsingException(getShardContext().parseContext(), "Failed to parse", e);
} finally { } finally {
if (parser != null) { if (parser != null) {
parser.close(); parser.close();
@ -146,10 +150,10 @@ public class IndexQueryParserService extends AbstractIndexComponent {
try { try {
parser = XContentFactory.xContent(source, offset, length).createParser(source, offset, length); parser = XContentFactory.xContent(source, offset, length).createParser(source, offset, length);
return parse(cache.get(), parser); return parse(cache.get(), parser);
} catch (QueryParsingException e) { } catch (QueryShardException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new QueryParsingException(getParseContext(), "Failed to parse", e); throw new QueryParsingException(getShardContext().parseContext(), "Failed to parse", e);
} finally { } finally {
if (parser != null) { if (parser != null) {
parser.close(); parser.close();
@ -161,7 +165,8 @@ public class IndexQueryParserService extends AbstractIndexComponent {
return parse(cache.get(), source); return parse(cache.get(), source);
} }
public ParsedQuery parse(QueryParseContext context, BytesReference source) { //norelease
public ParsedQuery parse(QueryShardContext context, BytesReference source) {
XContentParser parser = null; XContentParser parser = null;
try { try {
parser = XContentFactory.xContent(source).createParser(source); parser = XContentFactory.xContent(source).createParser(source);
@ -169,7 +174,7 @@ public class IndexQueryParserService extends AbstractIndexComponent {
} catch (QueryParsingException e) { } catch (QueryParsingException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new QueryParsingException(context, "Failed to parse", e); throw new QueryParsingException(context.parseContext(), "Failed to parse", e);
} finally { } finally {
if (parser != null) { if (parser != null) {
parser.close(); parser.close();
@ -177,15 +182,15 @@ public class IndexQueryParserService extends AbstractIndexComponent {
} }
} }
public ParsedQuery parse(String source) throws QueryParsingException { public ParsedQuery parse(String source) throws QueryParsingException, QueryShardException {
XContentParser parser = null; XContentParser parser = null;
try { try {
parser = XContentFactory.xContent(source).createParser(source); parser = XContentFactory.xContent(source).createParser(source);
return innerParse(cache.get(), parser); return innerParse(cache.get(), parser);
} catch (QueryParsingException e) { } catch (QueryShardException|QueryParsingException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
throw new QueryParsingException(getParseContext(), "Failed to parse [" + source + "]", e); throw new QueryParsingException(getShardContext().parseContext(), "Failed to parse [" + source + "]", e);
} finally { } finally {
if (parser != null) { if (parser != null) {
parser.close(); parser.close();
@ -197,11 +202,12 @@ public class IndexQueryParserService extends AbstractIndexComponent {
return parse(cache.get(), parser); return parse(cache.get(), parser);
} }
public ParsedQuery parse(QueryParseContext context, XContentParser parser) { //norelease
public ParsedQuery parse(QueryShardContext context, XContentParser parser) {
try { try {
return innerParse(context, parser); return innerParse(context, parser);
} catch (IOException e) { } catch (IOException e) {
throw new QueryParsingException(context, "Failed to parse", e); throw new QueryParsingException(context.parseContext(), "Failed to parse", e);
} }
} }
@ -209,11 +215,12 @@ public class IndexQueryParserService extends AbstractIndexComponent {
* Parses an inner filter, returning null if the filter should be ignored. * Parses an inner filter, returning null if the filter should be ignored.
*/ */
@Nullable @Nullable
//norelease
public ParsedQuery parseInnerFilter(XContentParser parser) throws IOException { public ParsedQuery parseInnerFilter(XContentParser parser) throws IOException {
QueryParseContext context = cache.get(); QueryShardContext context = cache.get();
context.reset(parser); context.reset(parser);
try { try {
Query filter = context.parseInnerFilter(); Query filter = context.parseContext().parseInnerFilter();
if (filter == null) { if (filter == null) {
return null; return null;
} }
@ -224,27 +231,23 @@ public class IndexQueryParserService extends AbstractIndexComponent {
} }
@Nullable @Nullable
public Query parseInnerQuery(XContentParser parser) throws IOException { public QueryBuilder parseInnerQueryBuilder(QueryParseContext parseContext) throws IOException {
QueryParseContext context = cache.get(); parseContext.parseFieldMatcher(parseFieldMatcher);
context.reset(parser); QueryBuilder query = parseContext.parseInnerQueryBuilder();
try { return query;
return context.parseInnerQuery();
} finally {
context.reset(null);
}
} }
@Nullable @Nullable
public Query parseInnerQuery(QueryParseContext parseContext) throws IOException { //norelease
parseContext.parseFieldMatcher(parseFieldMatcher); public Query parseInnerQuery(QueryShardContext context) throws IOException {
Query query = parseContext.parseInnerQuery(); Query query = context.parseContext().parseInnerQueryBuilder().toQuery(context);
if (query == null) { if (query == null) {
query = Queries.newMatchNoDocsQuery(); query = Queries.newMatchNoDocsQuery();
} }
return query; return query;
} }
public QueryParseContext getParseContext() { public QueryShardContext getShardContext() {
return cache.get(); return cache.get();
} }
@ -276,36 +279,41 @@ public class IndexQueryParserService extends AbstractIndexComponent {
XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource); XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource);
parsedQuery = parse(qSourceParser); parsedQuery = parse(qSourceParser);
} else { } else {
throw new QueryParsingException(getParseContext(), "request does not support [" + fieldName + "]"); throw new QueryParsingException(getShardContext().parseContext(), "request does not support [" + fieldName + "]");
} }
} }
} }
if (parsedQuery != null) { if (parsedQuery != null) {
return parsedQuery; return parsedQuery;
} }
} catch (QueryParsingException e) { } catch (QueryShardException e) {
throw e; throw e;
} catch (Throwable e) { } catch (Throwable e) {
throw new QueryParsingException(getParseContext(), "Failed to parse", e); throw new QueryParsingException(getShardContext().parseContext(), "Failed to parse", e);
} }
throw new QueryParsingException(getParseContext(), "Required query is missing"); throw new QueryParsingException(getShardContext().parseContext(), "Required query is missing");
} }
private ParsedQuery innerParse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException { //norelease
parseContext.reset(parser); private ParsedQuery innerParse(QueryShardContext context, XContentParser parser) throws IOException, QueryShardException {
context.reset(parser);
try { try {
parseContext.parseFieldMatcher(parseFieldMatcher); context.parseFieldMatcher(parseFieldMatcher);
Query query = parseContext.parseInnerQuery(); return innerParse(context, context.parseContext().parseInnerQueryBuilder());
if (query == null) {
query = Queries.newMatchNoDocsQuery();
}
return new ParsedQuery(query, parseContext.copyNamedQueries());
} finally { } finally {
parseContext.reset(null); context.reset(null);
} }
} }
private static ParsedQuery innerParse(QueryShardContext context, QueryBuilder queryBuilder) throws IOException, QueryShardException {
Query query = queryBuilder.toQuery(context);
if (query == null) {
query = Queries.newMatchNoDocsQuery();
}
return new ParsedQuery(query, context.copyNamedQueries());
}
public ParseFieldMatcher parseFieldMatcher() { public ParseFieldMatcher parseFieldMatcher() {
return parseFieldMatcher; return parseFieldMatcher;
} }

View File

@ -58,7 +58,8 @@ public class IndicesQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
Query noMatchQuery = null; Query noMatchQuery = null;
@ -149,7 +150,7 @@ public class IndicesQueryParser extends BaseQueryParserTemp {
} }
} }
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, chosenQuery); context.addNamedQuery(queryName, chosenQuery);
} }
chosenQuery.setBoost(boost); chosenQuery.setBoost(boost);
return chosenQuery; return chosenQuery;

View File

@ -55,7 +55,7 @@ public class LimitQueryBuilder extends AbstractQueryBuilder<LimitQueryBuilder> {
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
// this filter is deprecated and parses to a filter that matches everything // this filter is deprecated and parses to a filter that matches everything
return Queries.newMatchAllQuery(); return Queries.newMatchAllQuery();
} }

View File

@ -44,7 +44,7 @@ public class MatchAllQueryBuilder extends AbstractQueryBuilder<MatchAllQueryBuil
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
return Queries.newMatchAllQuery(); return Queries.newMatchAllQuery();
} }

View File

@ -48,7 +48,8 @@ public class MatchQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
MatchQuery.Type type = MatchQuery.Type.BOOLEAN; MatchQuery.Type type = MatchQuery.Type.BOOLEAN;
@ -68,7 +69,7 @@ public class MatchQueryParser extends BaseQueryParserTemp {
Object value = null; Object value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
MatchQuery matchQuery = new MatchQuery(parseContext); MatchQuery matchQuery = new MatchQuery(context);
String minimumShouldMatch = null; String minimumShouldMatch = null;
String queryName = null; String queryName = null;
@ -94,7 +95,7 @@ public class MatchQueryParser extends BaseQueryParserTemp {
} }
} else if ("analyzer".equals(currentFieldName)) { } else if ("analyzer".equals(currentFieldName)) {
String analyzer = parser.text(); String analyzer = parser.text();
if (parseContext.analysisService().analyzer(analyzer) == null) { if (context.analysisService().analyzer(analyzer) == null) {
throw new QueryParsingException(parseContext, "[match] analyzer [" + parser.text() + "] not found"); throw new QueryParsingException(parseContext, "[match] analyzer [" + parser.text() + "] not found");
} }
matchQuery.setAnalyzer(analyzer); matchQuery.setAnalyzer(analyzer);
@ -163,7 +164,7 @@ public class MatchQueryParser extends BaseQueryParserTemp {
} }
query.setBoost(boost); query.setBoost(boost);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
return query; return query;
} }

View File

@ -110,28 +110,28 @@ public class MissingQueryBuilder extends AbstractQueryBuilder<MissingQueryBuilde
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
return newFilter(parseContext, fieldPattern, existence, nullValue); return newFilter(context, fieldPattern, existence, nullValue);
} }
public static Query newFilter(QueryParseContext parseContext, String fieldPattern, boolean existence, boolean nullValue) { public static Query newFilter(QueryShardContext context, String fieldPattern, boolean existence, boolean nullValue) {
if (!existence && !nullValue) { if (!existence && !nullValue) {
throw new QueryParsingException(parseContext, "missing must have either existence, or null_value, or both set to true"); throw new QueryShardException(context, "missing must have either existence, or null_value, or both set to true");
} }
final FieldNamesFieldMapper.FieldNamesFieldType fieldNamesFieldType = (FieldNamesFieldMapper.FieldNamesFieldType) parseContext.mapperService().fullName(FieldNamesFieldMapper.NAME); final FieldNamesFieldMapper.FieldNamesFieldType fieldNamesFieldType = (FieldNamesFieldMapper.FieldNamesFieldType) context.mapperService().fullName(FieldNamesFieldMapper.NAME);
if (fieldNamesFieldType == null) { if (fieldNamesFieldType == null) {
// can only happen when no types exist, so no docs exist either // can only happen when no types exist, so no docs exist either
return Queries.newMatchNoDocsQuery(); return Queries.newMatchNoDocsQuery();
} }
ObjectMapper objectMapper = parseContext.getObjectMapper(fieldPattern); ObjectMapper objectMapper = context.getObjectMapper(fieldPattern);
if (objectMapper != null) { if (objectMapper != null) {
// automatic make the object mapper pattern // automatic make the object mapper pattern
fieldPattern = fieldPattern + ".*"; fieldPattern = fieldPattern + ".*";
} }
Collection<String> fields = parseContext.simpleMatchToIndexNames(fieldPattern); Collection<String> fields = context.simpleMatchToIndexNames(fieldPattern);
if (fields.isEmpty()) { if (fields.isEmpty()) {
if (existence) { if (existence) {
// if we ask for existence of fields, and we found none, then we should match on all // if we ask for existence of fields, and we found none, then we should match on all
@ -146,7 +146,7 @@ public class MissingQueryBuilder extends AbstractQueryBuilder<MissingQueryBuilde
if (existence) { if (existence) {
BooleanQuery boolFilter = new BooleanQuery(); BooleanQuery boolFilter = new BooleanQuery();
for (String field : fields) { for (String field : fields) {
MappedFieldType fieldType = parseContext.fieldMapper(field); MappedFieldType fieldType = context.fieldMapper(field);
Query filter = null; Query filter = null;
if (fieldNamesFieldType.isEnabled()) { if (fieldNamesFieldType.isEnabled()) {
final String f; final String f;
@ -155,7 +155,7 @@ public class MissingQueryBuilder extends AbstractQueryBuilder<MissingQueryBuilde
} else { } else {
f = field; f = field;
} }
filter = fieldNamesFieldType.termQuery(f, parseContext); filter = fieldNamesFieldType.termQuery(f, context);
} }
// if _field_names are not indexed, we need to go the slow way // if _field_names are not indexed, we need to go the slow way
if (filter == null && fieldType != null) { if (filter == null && fieldType != null) {
@ -173,7 +173,7 @@ public class MissingQueryBuilder extends AbstractQueryBuilder<MissingQueryBuilde
if (nullValue) { if (nullValue) {
for (String field : fields) { for (String field : fields) {
MappedFieldType fieldType = parseContext.fieldMapper(field); MappedFieldType fieldType = context.fieldMapper(field);
if (fieldType != null) { if (fieldType != null) {
nullFilter = fieldType.nullValueQuery(); nullFilter = fieldType.nullValueQuery();
} }

View File

@ -21,6 +21,7 @@ package org.elasticsearch.index.query;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queries.TermsQuery; import org.apache.lucene.queries.TermsQuery;
import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanClause;
@ -91,11 +92,12 @@ public class MoreLikeThisQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
MoreLikeThisQuery mltQuery = new MoreLikeThisQuery(); MoreLikeThisQuery mltQuery = new MoreLikeThisQuery();
mltQuery.setSimilarity(parseContext.searchSimilarity()); mltQuery.setSimilarity(context.searchSimilarity());
Analyzer analyzer = null; Analyzer analyzer = null;
List<String> moreLikeFields = null; List<String> moreLikeFields = null;
boolean failOnUnsupportedField = true; boolean failOnUnsupportedField = true;
@ -142,7 +144,7 @@ public class MoreLikeThisQueryParser extends BaseQueryParserTemp {
} else if (parseContext.parseFieldMatcher().match(currentFieldName, Fields.MINIMUM_SHOULD_MATCH)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, Fields.MINIMUM_SHOULD_MATCH)) {
mltQuery.setMinimumShouldMatch(parser.text()); mltQuery.setMinimumShouldMatch(parser.text());
} else if ("analyzer".equals(currentFieldName)) { } else if ("analyzer".equals(currentFieldName)) {
analyzer = parseContext.analysisService().analyzer(parser.text()); analyzer = context.analysisService().analyzer(parser.text());
} else if ("boost".equals(currentFieldName)) { } else if ("boost".equals(currentFieldName)) {
mltQuery.setBoost(parser.floatValue()); mltQuery.setBoost(parser.floatValue());
} else if (parseContext.parseFieldMatcher().match(currentFieldName, Fields.FAIL_ON_UNSUPPORTED_FIELD)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, Fields.FAIL_ON_UNSUPPORTED_FIELD)) {
@ -165,7 +167,7 @@ public class MoreLikeThisQueryParser extends BaseQueryParserTemp {
moreLikeFields = Lists.newLinkedList(); moreLikeFields = Lists.newLinkedList();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
String field = parser.text(); String field = parser.text();
MappedFieldType fieldType = parseContext.fieldMapper(field); MappedFieldType fieldType = context.fieldMapper(field);
moreLikeFields.add(fieldType == null ? field : fieldType.names().indexName()); moreLikeFields.add(fieldType == null ? field : fieldType.names().indexName());
} }
} else if (parseContext.parseFieldMatcher().match(currentFieldName, Fields.DOCUMENT_IDS)) { } else if (parseContext.parseFieldMatcher().match(currentFieldName, Fields.DOCUMENT_IDS)) {
@ -214,14 +216,14 @@ public class MoreLikeThisQueryParser extends BaseQueryParserTemp {
// set analyzer // set analyzer
if (analyzer == null) { if (analyzer == null) {
analyzer = parseContext.mapperService().searchAnalyzer(); analyzer = context.mapperService().searchAnalyzer();
} }
mltQuery.setAnalyzer(analyzer); mltQuery.setAnalyzer(analyzer);
// set like text fields // set like text fields
boolean useDefaultField = (moreLikeFields == null); boolean useDefaultField = (moreLikeFields == null);
if (useDefaultField) { if (useDefaultField) {
moreLikeFields = Lists.newArrayList(parseContext.defaultField()); moreLikeFields = Lists.newArrayList(context.defaultField());
} }
// possibly remove unsupported fields // possibly remove unsupported fields
removeUnsupportedFields(moreLikeFields, analyzer, failOnUnsupportedField); removeUnsupportedFields(moreLikeFields, analyzer, failOnUnsupportedField);
@ -232,7 +234,7 @@ public class MoreLikeThisQueryParser extends BaseQueryParserTemp {
// support for named query // support for named query
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, mltQuery); context.addNamedQuery(queryName, mltQuery);
} }
// handle like texts // handle like texts
@ -256,12 +258,12 @@ public class MoreLikeThisQueryParser extends BaseQueryParserTemp {
item.index(parseContext.index().name()); item.index(parseContext.index().name());
} }
if (item.type() == null) { if (item.type() == null) {
if (parseContext.queryTypes().size() > 1) { if (context.queryTypes().size() > 1) {
throw new QueryParsingException(parseContext, throw new QueryParsingException(parseContext,
"ambiguous type for item with id: " + item.id() "ambiguous type for item with id: " + item.id()
+ " and index: " + item.index()); + " and index: " + item.index());
} else { } else {
item.type(parseContext.queryTypes().iterator().next()); item.type(context.queryTypes().iterator().next());
} }
} }
// default fields if not present but don't override for artificial docs // default fields if not present but don't override for artificial docs

View File

@ -50,14 +50,15 @@ public class MultiMatchQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
Object value = null; Object value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
Float tieBreaker = null; Float tieBreaker = null;
MultiMatchQueryBuilder.Type type = null; MultiMatchQueryBuilder.Type type = null;
MultiMatchQuery multiMatchQuery = new MultiMatchQuery(parseContext); MultiMatchQuery multiMatchQuery = new MultiMatchQuery(context);
String minimumShouldMatch = null; String minimumShouldMatch = null;
Map<String, Float> fieldNameWithBoosts = Maps.newHashMap(); Map<String, Float> fieldNameWithBoosts = Maps.newHashMap();
String queryName = null; String queryName = null;
@ -70,10 +71,10 @@ public class MultiMatchQueryParser extends BaseQueryParserTemp {
} else if ("fields".equals(currentFieldName)) { } else if ("fields".equals(currentFieldName)) {
if (token == XContentParser.Token.START_ARRAY) { if (token == XContentParser.Token.START_ARRAY) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
extractFieldAndBoost(parseContext, parser, fieldNameWithBoosts); extractFieldAndBoost(context, parser, fieldNameWithBoosts);
} }
} else if (token.isValue()) { } else if (token.isValue()) {
extractFieldAndBoost(parseContext, parser, fieldNameWithBoosts); extractFieldAndBoost(context, parser, fieldNameWithBoosts);
} else { } else {
throw new QueryParsingException(parseContext, "[" + MultiMatchQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]"); throw new QueryParsingException(parseContext, "[" + MultiMatchQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");
} }
@ -84,7 +85,7 @@ public class MultiMatchQueryParser extends BaseQueryParserTemp {
type = MultiMatchQueryBuilder.Type.parse(parser.text(), parseContext.parseFieldMatcher()); type = MultiMatchQueryBuilder.Type.parse(parser.text(), parseContext.parseFieldMatcher());
} else if ("analyzer".equals(currentFieldName)) { } else if ("analyzer".equals(currentFieldName)) {
String analyzer = parser.text(); String analyzer = parser.text();
if (parseContext.analysisService().analyzer(analyzer) == null) { if (context.analysisService().analyzer(analyzer) == null) {
throw new QueryParsingException(parseContext, "[" + MultiMatchQueryBuilder.NAME + "] analyzer [" + parser.text() + "] not found"); throw new QueryParsingException(parseContext, "[" + MultiMatchQueryBuilder.NAME + "] analyzer [" + parser.text() + "] not found");
} }
multiMatchQuery.setAnalyzer(analyzer); multiMatchQuery.setAnalyzer(analyzer);
@ -156,12 +157,12 @@ public class MultiMatchQueryParser extends BaseQueryParserTemp {
query.setBoost(boost); query.setBoost(boost);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
return query; return query;
} }
private void extractFieldAndBoost(QueryParseContext parseContext, XContentParser parser, Map<String, Float> fieldNameWithBoosts) throws IOException { private void extractFieldAndBoost(QueryShardContext context, XContentParser parser, Map<String, Float> fieldNameWithBoosts) throws IOException {
String fField = null; String fField = null;
Float fBoost = null; Float fBoost = null;
char[] fieldText = parser.textCharacters(); char[] fieldText = parser.textCharacters();
@ -179,7 +180,7 @@ public class MultiMatchQueryParser extends BaseQueryParserTemp {
} }
if (Regex.isSimpleMatchPattern(fField)) { if (Regex.isSimpleMatchPattern(fField)) {
for (String field : parseContext.mapperService().simpleMatchToIndexNames(fField)) { for (String field : context.mapperService().simpleMatchToIndexNames(fField)) {
fieldNameWithBoosts.put(field, fBoost); fieldNameWithBoosts.put(field, fBoost);
} }
} else { } else {

View File

@ -54,9 +54,10 @@ public class NestedQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
final ToBlockJoinQueryBuilder builder = new ToBlockJoinQueryBuilder(parseContext); final ToBlockJoinQueryBuilder builder = new ToBlockJoinQueryBuilder(context);
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
ScoreMode scoreMode = ScoreMode.Avg; ScoreMode scoreMode = ScoreMode.Avg;
@ -110,7 +111,7 @@ public class NestedQueryParser extends BaseQueryParserTemp {
if (joinQuery != null) { if (joinQuery != null) {
joinQuery.setBoost(boost); joinQuery.setBoost(boost);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, joinQuery); context.addNamedQuery(queryName, joinQuery);
} }
} }
return joinQuery; return joinQuery;
@ -121,8 +122,8 @@ public class NestedQueryParser extends BaseQueryParserTemp {
private ScoreMode scoreMode; private ScoreMode scoreMode;
private Tuple<String, SubSearchContext> innerHits; private Tuple<String, SubSearchContext> innerHits;
public ToBlockJoinQueryBuilder(QueryParseContext parseContext) throws IOException { public ToBlockJoinQueryBuilder(QueryShardContext context) throws IOException {
super(parseContext); super(context);
} }
public void setScoreMode(ScoreMode scoreMode) { public void setScoreMode(ScoreMode scoreMode) {
@ -146,14 +147,14 @@ public class NestedQueryParser extends BaseQueryParserTemp {
innerQuery = null; innerQuery = null;
} }
} else { } else {
throw new QueryParsingException(parseContext, "[nested] requires either 'query' or 'filter' field"); throw new QueryShardException(shardContext, "[nested] requires either 'query' or 'filter' field");
} }
if (innerHits != null) { if (innerHits != null) {
ParsedQuery parsedQuery = new ParsedQuery(innerQuery, parseContext.copyNamedQueries()); ParsedQuery parsedQuery = new ParsedQuery(innerQuery, shardContext.copyNamedQueries());
InnerHitsContext.NestedInnerHits nestedInnerHits = new InnerHitsContext.NestedInnerHits(innerHits.v2(), parsedQuery, null, getParentObjectMapper(), nestedObjectMapper); InnerHitsContext.NestedInnerHits nestedInnerHits = new InnerHitsContext.NestedInnerHits(innerHits.v2(), parsedQuery, null, getParentObjectMapper(), nestedObjectMapper);
String name = innerHits.v1() != null ? innerHits.v1() : path; String name = innerHits.v1() != null ? innerHits.v1() : path;
parseContext.addInnerHits(name, nestedInnerHits); shardContext.addInnerHits(name, nestedInnerHits);
} }
if (innerQuery != null) { if (innerQuery != null) {

View File

@ -60,8 +60,8 @@ public class NotQueryBuilder extends AbstractQueryBuilder<NotQueryBuilder> {
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query luceneQuery = filter.toQuery(parseContext); Query luceneQuery = filter.toQuery(context);
if (luceneQuery == null) { if (luceneQuery == null) {
return null; return null;
} }

View File

@ -81,7 +81,7 @@ public class OrQueryBuilder extends AbstractQueryBuilder<OrQueryBuilder> {
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
if (filters.isEmpty()) { if (filters.isEmpty()) {
// no filters provided, this should be ignored upstream // no filters provided, this should be ignored upstream
return null; return null;
@ -89,7 +89,7 @@ public class OrQueryBuilder extends AbstractQueryBuilder<OrQueryBuilder> {
BooleanQuery query = new BooleanQuery(); BooleanQuery query = new BooleanQuery();
for (QueryBuilder f : filters) { for (QueryBuilder f : filters) {
Query innerQuery = f.toQuery(parseContext); Query innerQuery = f.toQuery(context);
// ignore queries that are null // ignore queries that are null
if (innerQuery != null) { if (innerQuery != null) {
query.add(innerQuery, Occur.SHOULD); query.add(innerQuery, Occur.SHOULD);

View File

@ -42,9 +42,9 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
public static final String NAME = "prefix"; public static final String NAME = "prefix";
private final String fieldName; private final String fieldName;
private final String value; private final String value;
private String rewrite; private String rewrite;
static final PrefixQueryBuilder PROTOTYPE = new PrefixQueryBuilder(null, null); static final PrefixQueryBuilder PROTOTYPE = new PrefixQueryBuilder(null, null);
@ -59,7 +59,7 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
this.fieldName = fieldName; this.fieldName = fieldName;
this.value = value; this.value = value;
} }
public String fieldName() { public String fieldName() {
return this.fieldName; return this.fieldName;
} }
@ -96,13 +96,13 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
MultiTermQuery.RewriteMethod method = QueryParsers.parseRewriteMethod(parseContext.parseFieldMatcher(), rewrite, null); MultiTermQuery.RewriteMethod method = QueryParsers.parseRewriteMethod(context.parseFieldMatcher(), rewrite, null);
Query query = null; Query query = null;
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType != null) { if (fieldType != null) {
query = fieldType.prefixQuery(value, method, parseContext); query = fieldType.prefixQuery(value, method, context);
} }
if (query == null) { if (query == null) {
PrefixQuery prefixQuery = new PrefixQuery(new Term(fieldName, BytesRefs.toBytesRef(value))); PrefixQuery prefixQuery = new PrefixQuery(new Term(fieldName, BytesRefs.toBytesRef(value)));
@ -111,7 +111,7 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
} }
query = prefixQuery; query = prefixQuery;
} }
return query; return query;
} }
@ -148,7 +148,7 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
@Override @Override
protected boolean doEquals(PrefixQueryBuilder other) { protected boolean doEquals(PrefixQueryBuilder other) {
return Objects.equals(fieldName, other.fieldName) && return Objects.equals(fieldName, other.fieldName) &&
Objects.equals(value, other.value) && Objects.equals(value, other.value) &&
Objects.equals(rewrite, other.rewrite); Objects.equals(rewrite, other.rewrite);
} }

View File

@ -42,12 +42,12 @@ public interface QueryBuilder<QB extends QueryBuilder> extends NamedWriteable<QB
* Returns <tt>null</tt> if this query should be ignored in the context of * Returns <tt>null</tt> if this query should be ignored in the context of
* parent queries. * parent queries.
* *
* @param parseContext additional information needed to construct the queries * @param context additional information needed to construct the queries
* @return the {@link Query} or <tt>null</tt> if this query should be ignored upstream * @return the {@link Query} or <tt>null</tt> if this query should be ignored upstream
* @throws QueryParsingException * @throws QueryShardException
* @throws IOException * @throws IOException
*/ */
Query toQuery(QueryParseContext parseContext) throws IOException; Query toQuery(QueryShardContext context) throws IOException;
/** /**
* Returns a {@link org.elasticsearch.common.bytes.BytesReference} * Returns a {@link org.elasticsearch.common.bytes.BytesReference}

View File

@ -65,9 +65,9 @@ public class QueryFilterBuilder extends AbstractQueryBuilder<QueryFilterBuilder>
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
// inner query builder can potentially be `null`, in that case we ignore it // inner query builder can potentially be `null`, in that case we ignore it
Query innerQuery = this.queryBuilder.toQuery(parseContext); Query innerQuery = this.queryBuilder.toQuery(context);
if (innerQuery == null) { if (innerQuery == null) {
return null; return null;
} }

View File

@ -19,201 +19,111 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.MapperQueryParser;
import org.apache.lucene.queryparser.classic.QueryParserSettings;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.Query; import org.apache.lucene.search.Query;
import org.apache.lucene.search.join.BitDocIdSetFilter;
import org.apache.lucene.search.similarities.Similarity;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Nullable; import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseField; import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.Index; import org.elasticsearch.index.Index;
import org.elasticsearch.index.analysis.AnalysisService; import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.mapper.*;
import org.elasticsearch.index.mapper.core.StringFieldMapper;
import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.query.support.NestedScope;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.fetch.innerhits.InnerHitsContext;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.lookup.SearchLookup;
import java.io.IOException; import java.io.IOException;
import java.util.*;
public class QueryParseContext { public class QueryParseContext {
private static final ParseField CACHE = new ParseField("_cache").withAllDeprecated("Elasticsearch makes its own caching decisions"); private static final ParseField CACHE = new ParseField("_cache").withAllDeprecated("Elasticsearch makes its own caching decisions");
private static final ParseField CACHE_KEY = new ParseField("_cache_key").withAllDeprecated("Filters are always used as cache keys"); private static final ParseField CACHE_KEY = new ParseField("_cache_key").withAllDeprecated("Filters are always used as cache keys");
private static ThreadLocal<String[]> typesContext = new ThreadLocal<>();
public static void setTypes(String[] types) {
typesContext.set(types);
}
public static String[] getTypes() {
return typesContext.get();
}
public static String[] setTypesWithPrevious(String[] types) {
String[] old = typesContext.get();
setTypes(types);
return old;
}
public static void removeTypes() {
typesContext.remove();
}
private final Index index;
private final Version indexVersionCreated;
private final IndexQueryParserService indexQueryParser;
private final Map<String, Query> namedQueries = Maps.newHashMap();
private final MapperQueryParser queryParser = new MapperQueryParser(this);
private XContentParser parser; private XContentParser parser;
private final Index index;
//norelease this flag is also used in the QueryShardContext, we need to make sure we set it there correctly in doToQuery()
private boolean isFilter;
private ParseFieldMatcher parseFieldMatcher; private ParseFieldMatcher parseFieldMatcher;
private boolean allowUnmappedFields; //norelease this can eventually be deleted when context() method goes away
private final QueryShardContext shardContext;
private IndicesQueriesRegistry indicesQueriesRegistry;
private boolean mapUnmappedFieldAsString; public QueryParseContext(Index index, IndicesQueriesRegistry registry) {
private NestedScope nestedScope;
private boolean isFilter;
public QueryParseContext(Index index, IndexQueryParserService indexQueryParser) {
this.index = index; this.index = index;
this.indexVersionCreated = Version.indexCreated(indexQueryParser.indexSettings()); this.indicesQueriesRegistry = registry;
this.indexQueryParser = indexQueryParser; this.shardContext = null;
}
QueryParseContext(QueryShardContext context) {
this.shardContext = context;
this.index = context.index();
this.indicesQueriesRegistry = context.indexQueryParserService().indicesQueriesRegistry();
}
public void reset(XContentParser jp) {
this.parseFieldMatcher = ParseFieldMatcher.EMPTY;
this.parser = jp;
}
//norelease this is still used in BaseQueryParserTemp and FunctionScoreQueryParse, remove if not needed there anymore
@Deprecated
public QueryShardContext shardContext() {
return this.shardContext;
}
public XContentParser parser() {
return this.parser;
} }
public void parseFieldMatcher(ParseFieldMatcher parseFieldMatcher) { public void parseFieldMatcher(ParseFieldMatcher parseFieldMatcher) {
this.parseFieldMatcher = parseFieldMatcher; this.parseFieldMatcher = parseFieldMatcher;
} }
public ParseFieldMatcher parseFieldMatcher() { public boolean isDeprecatedSetting(String setting) {
return parseFieldMatcher; return parseFieldMatcher.match(setting, CACHE) || parseFieldMatcher.match(setting, CACHE_KEY);
}
public void reset(XContentParser jp) {
allowUnmappedFields = indexQueryParser.defaultAllowUnmappedFields();
this.parseFieldMatcher = ParseFieldMatcher.EMPTY;
this.lookup = null;
this.parser = jp;
this.namedQueries.clear();
this.nestedScope = new NestedScope();
this.isFilter = false;
} }
public Index index() { public Index index() {
return this.index; return this.index;
} }
public void parser(XContentParser parser) { /**
this.parser = parser; * @deprecated replaced by calls to parseInnerFilterToQueryBuilder(String queryName) for the resulting queries
} */
public XContentParser parser() {
return parser;
}
public IndexQueryParserService indexQueryParserService() {
return indexQueryParser;
}
public AnalysisService analysisService() {
return indexQueryParser.analysisService;
}
public ScriptService scriptService() {
return indexQueryParser.scriptService;
}
public MapperService mapperService() {
return indexQueryParser.mapperService;
}
@Nullable @Nullable
public SimilarityService similarityService() { @Deprecated
return indexQueryParser.similarityService; //norelease should be possible to remove after refactoring all queries
} public Query parseInnerFilter(String queryName) throws IOException, QueryShardException {
assert this.shardContext != null;
public Similarity searchSimilarity() { QueryBuilder builder = parseInnerFilterToQueryBuilder(queryName);
return indexQueryParser.similarityService != null ? indexQueryParser.similarityService.similarity() : null; return (builder != null) ? builder.toQuery(this.shardContext) : null;
}
public String defaultField() {
return indexQueryParser.defaultField();
}
public boolean queryStringLenient() {
return indexQueryParser.queryStringLenient();
}
public MapperQueryParser queryParser(QueryParserSettings settings) {
queryParser.reset(settings);
return queryParser;
}
public BitDocIdSetFilter bitsetFilter(Filter filter) {
return indexQueryParser.bitsetFilterCache.getBitDocIdSetFilter(filter);
}
public <IFD extends IndexFieldData<?>> IFD getForField(MappedFieldType mapper) {
return indexQueryParser.fieldDataService.getForField(mapper);
}
public void addNamedQuery(String name, Query query) {
namedQueries.put(name, query);
}
public ImmutableMap<String, Query> copyNamedQueries() {
return ImmutableMap.copyOf(namedQueries);
}
public void combineNamedQueries(QueryParseContext context) {
namedQueries.putAll(context.namedQueries);
} }
/** /**
* Return whether we are currently parsing a filter or a query. * @deprecated replaced by calls to parseInnerFilterToQueryBuilder() for the resulting queries
*/ */
public boolean isFilter() { @Nullable
return isFilter; @Deprecated
//norelease should be possible to remove after refactoring all queries
public Query parseInnerFilter() throws QueryShardException, IOException {
assert this.shardContext != null;
QueryBuilder builder = parseInnerFilterToQueryBuilder();
Query result = null;
if (builder != null) {
result = builder.toQuery(this.shardContext);
}
return result;
} }
public void addInnerHits(String name, InnerHitsContext.BaseInnerHits context) { /**
SearchContext sc = SearchContext.current(); * @deprecated replaced by calls to parseInnerQueryBuilder() for the resulting queries
if (sc == null) { */
throw new QueryParsingException(this, "inner_hits unsupported"); @Nullable
@Deprecated
//norelease should be possible to remove after refactoring all queries
public Query parseInnerQuery() throws IOException, QueryShardException {
QueryBuilder builder = parseInnerQueryBuilder();
Query result = null;
if (builder != null) {
result = builder.toQuery(this.shardContext);
} }
return result;
InnerHitsContext innerHitsContext;
if (sc.innerHits() == null) {
innerHitsContext = new InnerHitsContext(new HashMap<String, InnerHitsContext.BaseInnerHits>());
sc.innerHits(innerHitsContext);
} else {
innerHitsContext = sc.innerHits();
}
innerHitsContext.addInnerHitDefinition(name, context);
} }
/** /**
@ -244,7 +154,7 @@ public class QueryParseContext {
throw new QueryParsingException(this, "[_na] query malformed, no field after start_object"); throw new QueryParsingException(this, "[_na] query malformed, no field after start_object");
} }
QueryParser queryParser = indexQueryParser.queryParser(queryName); QueryParser queryParser = queryParser(queryName);
if (queryParser == null) { if (queryParser == null) {
throw new QueryParsingException(this, "No query registered for [" + queryName + "]"); throw new QueryParsingException(this, "No query registered for [" + queryName + "]");
} }
@ -257,40 +167,12 @@ public class QueryParseContext {
} }
/** /**
* @deprecated replaced by calls to parseInnerQueryBuilder() for the resulting queries * @return a new QueryBuilder based on the current state of the parser, but does so that the inner query
*/ * is parsed to a filter
@Nullable
@Deprecated
public Query parseInnerQuery() throws IOException, QueryParsingException {
QueryBuilder builder = parseInnerQueryBuilder();
Query result = null;
if (builder != null) {
result = builder.toQuery(this);
}
return result;
}
/**
* @deprecated replaced by calls to parseInnerFilterToQueryBuilder() for the resulting queries
*/
@Nullable
@Deprecated
public Query parseInnerFilter() throws QueryParsingException, IOException {
QueryBuilder builder = parseInnerFilterToQueryBuilder();
Query result = null;
if (builder != null) {
result = builder.toQuery(this);
}
return result;
}
/**
* @return
* @throws QueryParsingException
* @throws IOException * @throws IOException
*/ */
@Nullable @Nullable
public QueryBuilder parseInnerFilterToQueryBuilder() throws QueryParsingException, IOException { public QueryBuilder parseInnerFilterToQueryBuilder() throws IOException {
final boolean originalIsFilter = isFilter; final boolean originalIsFilter = isFilter;
try { try {
isFilter = true; isFilter = true;
@ -300,11 +182,11 @@ public class QueryParseContext {
} }
} }
public QueryBuilder parseInnerFilterToQueryBuilder(String queryName) throws IOException, QueryParsingException { QueryBuilder parseInnerFilterToQueryBuilder(String queryName) throws IOException, QueryParsingException {
final boolean originalIsFilter = isFilter; final boolean originalIsFilter = isFilter;
try { try {
isFilter = true; isFilter = true;
QueryParser queryParser = indexQueryParser.queryParser(queryName); QueryParser queryParser = queryParser(queryName);
if (queryParser == null) { if (queryParser == null) {
throw new QueryParsingException(this, "No query registered for [" + queryName + "]"); throw new QueryParsingException(this, "No query registered for [" + queryName + "]");
} }
@ -314,123 +196,19 @@ public class QueryParseContext {
} }
} }
/** public boolean isFilter() {
* @deprecated replaced by calls to parseInnerFilterToQueryBuilder(String queryName) for the resulting queries return this.isFilter;
*/
@Nullable
@Deprecated
public Query parseInnerFilter(String queryName) throws IOException, QueryParsingException {
QueryBuilder builder = parseInnerFilterToQueryBuilder(queryName);
return (builder != null) ? builder.toQuery(this) : null;
} }
public Collection<String> simpleMatchToIndexNames(String pattern) { public ParseFieldMatcher parseFieldMatcher() {
return indexQueryParser.mapperService.simpleMatchToIndexNames(pattern, getTypes()); return parseFieldMatcher;
} }
public MappedFieldType fieldMapper(String name) { public void parser(XContentParser innerParser) {
return failIfFieldMappingNotFound(name, indexQueryParser.mapperService.smartNameFieldType(name, getTypes())); this.parser = innerParser;
} }
public ObjectMapper getObjectMapper(String name) { QueryParser queryParser(String name) {
return indexQueryParser.mapperService.getObjectMapper(name, getTypes()); return indicesQueriesRegistry.queryParsers().get(name);
} }
/** Gets the search analyzer for the given field, or the default if there is none present for the field
* TODO: remove this by moving defaults into mappers themselves
*/
public Analyzer getSearchAnalyzer(MappedFieldType fieldType) {
if (fieldType.searchAnalyzer() != null) {
return fieldType.searchAnalyzer();
}
return mapperService().searchAnalyzer();
}
/** Gets the search quote nalyzer for the given field, or the default if there is none present for the field
* TODO: remove this by moving defaults into mappers themselves
*/
public Analyzer getSearchQuoteAnalyzer(MappedFieldType fieldType) {
if (fieldType.searchQuoteAnalyzer() != null) {
return fieldType.searchQuoteAnalyzer();
}
return mapperService().searchQuoteAnalyzer();
}
public void setAllowUnmappedFields(boolean allowUnmappedFields) {
this.allowUnmappedFields = allowUnmappedFields;
}
public void setMapUnmappedFieldAsString(boolean mapUnmappedFieldAsString) {
this.mapUnmappedFieldAsString = mapUnmappedFieldAsString;
}
private MappedFieldType failIfFieldMappingNotFound(String name, MappedFieldType fieldMapping) {
if (allowUnmappedFields) {
return fieldMapping;
} else if (mapUnmappedFieldAsString){
StringFieldMapper.Builder builder = MapperBuilders.stringField(name);
// it would be better to pass the real index settings, but they are not easily accessible from here...
Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, indexQueryParser.getIndexCreatedVersion()).build();
return builder.build(new Mapper.BuilderContext(settings, new ContentPath(1))).fieldType();
} else {
Version indexCreatedVersion = indexQueryParser.getIndexCreatedVersion();
if (fieldMapping == null && indexCreatedVersion.onOrAfter(Version.V_1_4_0_Beta1)) {
throw new QueryParsingException(this, "Strict field resolution and no field mapping can be found for the field with name ["
+ name + "]");
} else {
return fieldMapping;
}
}
}
/**
* Returns the narrowed down explicit types, or, if not set, all types.
*/
public Collection<String> queryTypes() {
String[] types = getTypes();
if (types == null || types.length == 0) {
return mapperService().types();
}
if (types.length == 1 && types[0].equals("_all")) {
return mapperService().types();
}
return Arrays.asList(types);
}
private SearchLookup lookup = null;
public SearchLookup lookup() {
SearchContext current = SearchContext.current();
if (current != null) {
return current.lookup();
}
if (lookup == null) {
lookup = new SearchLookup(mapperService(), indexQueryParser.fieldDataService, null);
}
return lookup;
}
public long nowInMillis() {
SearchContext current = SearchContext.current();
if (current != null) {
return current.nowInMillis();
}
return System.currentTimeMillis();
}
public NestedScope nestedScope() {
return nestedScope;
}
/**
* Return whether the setting is deprecated.
*/
public boolean isDeprecatedSetting(String setting) {
return parseFieldMatcher.match(setting, CACHE) || parseFieldMatcher.match(setting, CACHE_KEY);
}
public Version indexVersionCreated() {
return indexVersionCreated;
}
} }

View File

@ -44,10 +44,10 @@ public interface QueryParser {
*/ */
//norelease can be removed in favour of fromXContent once search requests can be parsed on the coordinating node //norelease can be removed in favour of fromXContent once search requests can be parsed on the coordinating node
@Nullable @Nullable
Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException; Query parse(QueryShardContext context) throws IOException, QueryParsingException;
/** /**
* Creates a new {@link QueryBuilder} from the query held by the {@link QueryParseContext} * Creates a new {@link QueryBuilder} from the query held by the {@link QueryShardContext}
* in {@link org.elasticsearch.common.xcontent.XContent} format * in {@link org.elasticsearch.common.xcontent.XContent} format
* *
* @param parseContext * @param parseContext

View File

@ -31,7 +31,8 @@ import org.elasticsearch.rest.RestStatus;
import java.io.IOException; import java.io.IOException;
/** /**
* * Exception that can be used when parsing queries with a given {@link QueryParseContext}.
* Can contain information about location of the error.
*/ */
public class QueryParsingException extends ElasticsearchException { public class QueryParsingException extends ElasticsearchException {
@ -71,9 +72,15 @@ public class QueryParsingException extends ElasticsearchException {
this.columnNumber = col; this.columnNumber = col;
} }
public QueryParsingException(StreamInput in) throws IOException{
super(in);
lineNumber = in.readInt();
columnNumber = in.readInt();
}
/** /**
* Line number of the location of the error * Line number of the location of the error
* *
* @return the line number or -1 if unknown * @return the line number or -1 if unknown
*/ */
public int getLineNumber() { public int getLineNumber() {
@ -82,7 +89,7 @@ public class QueryParsingException extends ElasticsearchException {
/** /**
* Column number of the location of the error * Column number of the location of the error
* *
* @return the column number or -1 if unknown * @return the column number or -1 if unknown
*/ */
public int getColumnNumber() { public int getColumnNumber() {
@ -109,11 +116,4 @@ public class QueryParsingException extends ElasticsearchException {
out.writeInt(lineNumber); out.writeInt(lineNumber);
out.writeInt(columnNumber); out.writeInt(columnNumber);
} }
public QueryParsingException(StreamInput in) throws IOException{
super(in);
lineNumber = in.readInt();
columnNumber = in.readInt();
}
} }

View File

@ -0,0 +1,327 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.query;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryparser.classic.MapperQueryParser;
import org.apache.lucene.queryparser.classic.QueryParserSettings;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.join.BitDocIdSetFilter;
import org.apache.lucene.search.similarities.Similarity;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.mapper.ContentPath;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.MapperBuilders;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.core.StringFieldMapper;
import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.query.support.NestedScope;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.fetch.innerhits.InnerHitsContext;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.lookup.SearchLookup;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* Context object used to create lucene queries on the shard level.
*/
public class QueryShardContext {
private static ThreadLocal<String[]> typesContext = new ThreadLocal<>();
public static void setTypes(String[] types) {
typesContext.set(types);
}
public static String[] getTypes() {
return typesContext.get();
}
public static String[] setTypesWithPrevious(String[] types) {
String[] old = typesContext.get();
setTypes(types);
return old;
}
public static void removeTypes() {
typesContext.remove();
}
private final Index index;
private final Version indexVersionCreated;
private final IndexQueryParserService indexQueryParser;
private final Map<String, Query> namedQueries = Maps.newHashMap();
private final MapperQueryParser queryParser = new MapperQueryParser(this);
private ParseFieldMatcher parseFieldMatcher;
private boolean allowUnmappedFields;
private boolean mapUnmappedFieldAsString;
private NestedScope nestedScope;
//norelease this should be possible to remove once query context are completely separated
private QueryParseContext parseContext;
private boolean isFilter;
public QueryShardContext(Index index, IndexQueryParserService indexQueryParser) {
this.index = index;
this.indexVersionCreated = Version.indexCreated(indexQueryParser.indexSettings());
this.indexQueryParser = indexQueryParser;
this.parseContext = new QueryParseContext(this);
}
public void parseFieldMatcher(ParseFieldMatcher parseFieldMatcher) {
this.parseFieldMatcher = parseFieldMatcher;
}
public ParseFieldMatcher parseFieldMatcher() {
return parseFieldMatcher;
}
private void reset() {
allowUnmappedFields = indexQueryParser.defaultAllowUnmappedFields();
this.parseFieldMatcher = ParseFieldMatcher.EMPTY;
this.lookup = null;
this.namedQueries.clear();
this.nestedScope = new NestedScope();
}
//norelease remove parser argument once query contexts are separated
public void reset(XContentParser jp) {
this.reset();
this.parseContext.reset(jp);
}
public Index index() {
return this.index;
}
public IndexQueryParserService indexQueryParserService() {
return indexQueryParser;
}
public AnalysisService analysisService() {
return indexQueryParser.analysisService;
}
public ScriptService scriptService() {
return indexQueryParser.scriptService;
}
public MapperService mapperService() {
return indexQueryParser.mapperService;
}
@Nullable
public SimilarityService similarityService() {
return indexQueryParser.similarityService;
}
public Similarity searchSimilarity() {
return indexQueryParser.similarityService != null ? indexQueryParser.similarityService.similarity() : null;
}
public String defaultField() {
return indexQueryParser.defaultField();
}
public boolean queryStringLenient() {
return indexQueryParser.queryStringLenient();
}
public MapperQueryParser queryParser(QueryParserSettings settings) {
queryParser.reset(settings);
return queryParser;
}
public BitDocIdSetFilter bitsetFilter(Filter filter) {
return indexQueryParser.bitsetFilterCache.getBitDocIdSetFilter(filter);
}
public <IFD extends IndexFieldData<?>> IFD getForField(MappedFieldType mapper) {
return indexQueryParser.fieldDataService.getForField(mapper);
}
public void addNamedQuery(String name, Query query) {
namedQueries.put(name, query);
}
public ImmutableMap<String, Query> copyNamedQueries() {
return ImmutableMap.copyOf(namedQueries);
}
public void combineNamedQueries(QueryShardContext context) {
namedQueries.putAll(context.namedQueries);
}
/**
* Return whether we are currently parsing a filter or a query.
*/
public boolean isFilter() {
return isFilter;
}
public void addInnerHits(String name, InnerHitsContext.BaseInnerHits context) {
SearchContext sc = SearchContext.current();
if (sc == null) {
throw new QueryShardException(this, "inner_hits unsupported");
}
InnerHitsContext innerHitsContext;
if (sc.innerHits() == null) {
innerHitsContext = new InnerHitsContext(new HashMap<String, InnerHitsContext.BaseInnerHits>());
sc.innerHits(innerHitsContext);
} else {
innerHitsContext = sc.innerHits();
}
innerHitsContext.addInnerHitDefinition(name, context);
}
public Collection<String> simpleMatchToIndexNames(String pattern) {
return indexQueryParser.mapperService.simpleMatchToIndexNames(pattern, getTypes());
}
public MappedFieldType fieldMapper(String name) {
return failIfFieldMappingNotFound(name, indexQueryParser.mapperService.smartNameFieldType(name, getTypes()));
}
public ObjectMapper getObjectMapper(String name) {
return indexQueryParser.mapperService.getObjectMapper(name, getTypes());
}
/** Gets the search analyzer for the given field, or the default if there is none present for the field
* TODO: remove this by moving defaults into mappers themselves
*/
public Analyzer getSearchAnalyzer(MappedFieldType fieldType) {
if (fieldType.searchAnalyzer() != null) {
return fieldType.searchAnalyzer();
}
return mapperService().searchAnalyzer();
}
/** Gets the search quote nalyzer for the given field, or the default if there is none present for the field
* TODO: remove this by moving defaults into mappers themselves
*/
public Analyzer getSearchQuoteAnalyzer(MappedFieldType fieldType) {
if (fieldType.searchQuoteAnalyzer() != null) {
return fieldType.searchQuoteAnalyzer();
}
return mapperService().searchQuoteAnalyzer();
}
public void setAllowUnmappedFields(boolean allowUnmappedFields) {
this.allowUnmappedFields = allowUnmappedFields;
}
public void setMapUnmappedFieldAsString(boolean mapUnmappedFieldAsString) {
this.mapUnmappedFieldAsString = mapUnmappedFieldAsString;
}
private MappedFieldType failIfFieldMappingNotFound(String name, MappedFieldType fieldMapping) {
if (allowUnmappedFields) {
return fieldMapping;
} else if (mapUnmappedFieldAsString){
StringFieldMapper.Builder builder = MapperBuilders.stringField(name);
// it would be better to pass the real index settings, but they are not easily accessible from here...
Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, indexQueryParser.getIndexCreatedVersion()).build();
return builder.build(new Mapper.BuilderContext(settings, new ContentPath(1))).fieldType();
} else {
Version indexCreatedVersion = indexQueryParser.getIndexCreatedVersion();
if (fieldMapping == null && indexCreatedVersion.onOrAfter(Version.V_1_4_0_Beta1)) {
throw new QueryShardException(this, "Strict field resolution and no field mapping can be found for the field with name ["
+ name + "]");
} else {
return fieldMapping;
}
}
}
/**
* Returns the narrowed down explicit types, or, if not set, all types.
*/
public Collection<String> queryTypes() {
String[] types = getTypes();
if (types == null || types.length == 0) {
return mapperService().types();
}
if (types.length == 1 && types[0].equals("_all")) {
return mapperService().types();
}
return Arrays.asList(types);
}
private SearchLookup lookup = null;
public SearchLookup lookup() {
SearchContext current = SearchContext.current();
if (current != null) {
return current.lookup();
}
if (lookup == null) {
lookup = new SearchLookup(mapperService(), indexQueryParser.fieldDataService, null);
}
return lookup;
}
public long nowInMillis() {
SearchContext current = SearchContext.current();
if (current != null) {
return current.nowInMillis();
}
return System.currentTimeMillis();
}
public NestedScope nestedScope() {
return nestedScope;
}
public Version indexVersionCreated() {
return indexVersionCreated;
}
public QueryParseContext parseContext() {
return this.parseContext;
}
}

View File

@ -0,0 +1,72 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.index.query;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.Index;
import org.elasticsearch.rest.RestStatus;
import java.io.IOException;
/**
* Exception that is thrown when creating lucene queries on the shard
*/
public class QueryShardException extends ElasticsearchException {
public QueryShardException(QueryShardContext context, String msg, Object... args) {
this(context, msg, null, args);
}
public QueryShardException(QueryShardContext context, String msg, Throwable cause, Object... args) {
super(msg, cause, args);
setIndex(context.index());
}
/**
* This constructor is provided for use in unit tests where a
* {@link QueryShardContext} may not be available
*/
public QueryShardException(Index index, int line, int col, String msg, Throwable cause) {
super(msg, cause);
setIndex(index);
}
public QueryShardException(StreamInput in) throws IOException{
super(in);
}
@Override
public RestStatus status() {
return RestStatus.BAD_REQUEST;
}
@Override
protected void innerToXContent(XContentBuilder builder, Params params) throws IOException {
super.innerToXContent(builder, params);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
}
}

View File

@ -66,13 +66,14 @@ public class QueryStringQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String queryName = null; String queryName = null;
QueryParserSettings qpSettings = new QueryParserSettings(); QueryParserSettings qpSettings = new QueryParserSettings();
qpSettings.defaultField(parseContext.defaultField()); qpSettings.defaultField(context.defaultField());
qpSettings.lenient(parseContext.queryStringLenient()); qpSettings.lenient(context.queryStringLenient());
qpSettings.analyzeWildcard(defaultAnalyzeWildcard); qpSettings.analyzeWildcard(defaultAnalyzeWildcard);
qpSettings.allowLeadingWildcard(defaultAllowLeadingWildcard); qpSettings.allowLeadingWildcard(defaultAllowLeadingWildcard);
qpSettings.locale(Locale.ROOT); qpSettings.locale(Locale.ROOT);
@ -105,7 +106,7 @@ public class QueryStringQueryParser extends BaseQueryParserTemp {
} }
if (Regex.isSimpleMatchPattern(fField)) { if (Regex.isSimpleMatchPattern(fField)) {
for (String field : parseContext.mapperService().simpleMatchToIndexNames(fField)) { for (String field : context.mapperService().simpleMatchToIndexNames(fField)) {
qpSettings.fields().add(field); qpSettings.fields().add(field);
if (fBoost != -1) { if (fBoost != -1) {
if (qpSettings.boosts() == null) { if (qpSettings.boosts() == null) {
@ -143,13 +144,13 @@ public class QueryStringQueryParser extends BaseQueryParserTemp {
throw new QueryParsingException(parseContext, "Query default operator [" + op + "] is not allowed"); throw new QueryParsingException(parseContext, "Query default operator [" + op + "] is not allowed");
} }
} else if ("analyzer".equals(currentFieldName)) { } else if ("analyzer".equals(currentFieldName)) {
NamedAnalyzer analyzer = parseContext.analysisService().analyzer(parser.text()); NamedAnalyzer analyzer = context.analysisService().analyzer(parser.text());
if (analyzer == null) { if (analyzer == null) {
throw new QueryParsingException(parseContext, "[query_string] analyzer [" + parser.text() + "] not found"); throw new QueryParsingException(parseContext, "[query_string] analyzer [" + parser.text() + "] not found");
} }
qpSettings.forcedAnalyzer(analyzer); qpSettings.forcedAnalyzer(analyzer);
} else if ("quote_analyzer".equals(currentFieldName) || "quoteAnalyzer".equals(currentFieldName)) { } else if ("quote_analyzer".equals(currentFieldName) || "quoteAnalyzer".equals(currentFieldName)) {
NamedAnalyzer analyzer = parseContext.analysisService().analyzer(parser.text()); NamedAnalyzer analyzer = context.analysisService().analyzer(parser.text());
if (analyzer == null) { if (analyzer == null) {
throw new QueryParsingException(parseContext, "[query_string] quote_analyzer [" + parser.text() throw new QueryParsingException(parseContext, "[query_string] quote_analyzer [" + parser.text()
+ "] not found"); + "] not found");
@ -214,16 +215,16 @@ public class QueryStringQueryParser extends BaseQueryParserTemp {
if (qpSettings.queryString() == null) { if (qpSettings.queryString() == null) {
throw new QueryParsingException(parseContext, "query_string must be provided with a [query]"); throw new QueryParsingException(parseContext, "query_string must be provided with a [query]");
} }
qpSettings.defaultAnalyzer(parseContext.mapperService().searchAnalyzer()); qpSettings.defaultAnalyzer(context.mapperService().searchAnalyzer());
qpSettings.defaultQuoteAnalyzer(parseContext.mapperService().searchQuoteAnalyzer()); qpSettings.defaultQuoteAnalyzer(context.mapperService().searchQuoteAnalyzer());
if (qpSettings.escape()) { if (qpSettings.escape()) {
qpSettings.queryString(org.apache.lucene.queryparser.classic.QueryParser.escape(qpSettings.queryString())); qpSettings.queryString(org.apache.lucene.queryparser.classic.QueryParser.escape(qpSettings.queryString()));
} }
qpSettings.queryTypes(parseContext.queryTypes()); qpSettings.queryTypes(context.queryTypes());
MapperQueryParser queryParser = parseContext.queryParser(qpSettings); MapperQueryParser queryParser = context.queryParser(qpSettings);
try { try {
Query query = queryParser.parse(qpSettings.queryString()); Query query = queryParser.parse(qpSettings.queryString());
@ -238,7 +239,7 @@ public class QueryStringQueryParser extends BaseQueryParserTemp {
Queries.applyMinimumShouldMatch((BooleanQuery) query, qpSettings.minimumShouldMatch()); Queries.applyMinimumShouldMatch((BooleanQuery) query, qpSettings.minimumShouldMatch());
} }
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
return query; return query;
} catch (org.apache.lucene.queryparser.classic.ParseException e) { } catch (org.apache.lucene.queryparser.classic.ParseException e) {

View File

@ -25,7 +25,7 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException; import java.io.IOException;
/** /**
* QueryBuilder implementation that holds a lucene query, which can be returned by {@link QueryBuilder#toQuery(QueryParseContext)}. * QueryBuilder implementation that holds a lucene query, which can be returned by {@link QueryBuilder#toQuery(QueryShardContext)}.
* Doesn't support conversion to {@link org.elasticsearch.common.xcontent.XContent} via {@link #doXContent(XContentBuilder, Params)}. * Doesn't support conversion to {@link org.elasticsearch.common.xcontent.XContent} via {@link #doXContent(XContentBuilder, Params)}.
*/ */
//norelease to be removed once all queries support separate fromXContent and toQuery methods. Make AbstractQueryBuilder#toQuery final as well then. //norelease to be removed once all queries support separate fromXContent and toQuery methods. Make AbstractQueryBuilder#toQuery final as well then.
@ -47,7 +47,7 @@ public class QueryWrappingQueryBuilder extends AbstractQueryBuilder<QueryWrappin
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
return query; return query;
} }

View File

@ -243,9 +243,9 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query query = null; Query query = null;
MappedFieldType mapper = parseContext.fieldMapper(this.fieldName); MappedFieldType mapper = context.fieldMapper(this.fieldName);
if (mapper != null) { if (mapper != null) {
if (mapper instanceof DateFieldMapper.DateFieldType) { if (mapper instanceof DateFieldMapper.DateFieldType) {
DateMathParser forcedDateParser = null; DateMathParser forcedDateParser = null;
@ -259,7 +259,7 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
query = ((DateFieldMapper.DateFieldType) mapper).rangeQuery(from, to, includeLower, includeUpper, dateTimeZone, forcedDateParser); query = ((DateFieldMapper.DateFieldType) mapper).rangeQuery(from, to, includeLower, includeUpper, dateTimeZone, forcedDateParser);
} else { } else {
if (timeZone != null) { if (timeZone != null) {
throw new QueryParsingException(parseContext, "[range] time_zone can not be applied to non date field [" throw new QueryShardException(context, "[range] time_zone can not be applied to non date field ["
+ fieldName + "]"); + fieldName + "]");
} }
//LUCENE 4 UPGRADE Mapper#rangeQuery should use bytesref as well? //LUCENE 4 UPGRADE Mapper#rangeQuery should use bytesref as well?
@ -267,7 +267,7 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
} }
} else { } else {
if (timeZone != null) { if (timeZone != null) {
throw new QueryParsingException(parseContext, "[range] time_zone can not be applied to non unmapped field [" throw new QueryShardException(context, "[range] time_zone can not be applied to non unmapped field ["
+ fieldName + "]"); + fieldName + "]");
} }
} }

View File

@ -149,13 +149,13 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
} }
@Override @Override
public Query doToQuery(QueryParseContext parseContext) throws QueryParsingException, IOException { public Query doToQuery(QueryShardContext context) throws QueryShardException, IOException {
MultiTermQuery.RewriteMethod method = QueryParsers.parseRewriteMethod(parseContext.parseFieldMatcher(), rewrite, null); MultiTermQuery.RewriteMethod method = QueryParsers.parseRewriteMethod(context.parseFieldMatcher(), rewrite, null);
Query query = null; Query query = null;
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType != null) { if (fieldType != null) {
query = fieldType.regexpQuery(value, flagsValue, maxDeterminizedStates, method, parseContext); query = fieldType.regexpQuery(value, flagsValue, maxDeterminizedStates, method, context);
} }
if (query == null) { if (query == null) {
RegexpQuery regexpQuery = new RegexpQuery(new Term(fieldName, BytesRefs.toBytesRef(value)), flagsValue, maxDeterminizedStates); RegexpQuery regexpQuery = new RegexpQuery(new Term(fieldName, BytesRefs.toBytesRef(value)), flagsValue, maxDeterminizedStates);

View File

@ -25,7 +25,6 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.search.RandomAccessWeight; import org.apache.lucene.search.RandomAccessWeight;
import org.apache.lucene.search.Weight; import org.apache.lucene.search.Weight;
import org.apache.lucene.util.Bits; import org.apache.lucene.util.Bits;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
@ -43,7 +42,7 @@ public class ScriptQueryBuilder extends AbstractQueryBuilder<ScriptQueryBuilder>
static final ScriptQueryBuilder PROTOTYPE = new ScriptQueryBuilder(null); static final ScriptQueryBuilder PROTOTYPE = new ScriptQueryBuilder(null);
private final Script script; private final Script script;
public ScriptQueryBuilder(Script script) { public ScriptQueryBuilder(Script script) {
this.script = script; this.script = script;
} }
@ -66,8 +65,8 @@ public class ScriptQueryBuilder extends AbstractQueryBuilder<ScriptQueryBuilder>
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
return new ScriptQuery(script, parseContext.scriptService(), parseContext.lookup()); return new ScriptQuery(script, context.scriptService(), context.lookup());
} }
@Override @Override
@ -151,7 +150,7 @@ public class ScriptQueryBuilder extends AbstractQueryBuilder<ScriptQueryBuilder>
}; };
} }
} }
@Override @Override
protected ScriptQueryBuilder doReadFrom(StreamInput in) throws IOException { protected ScriptQueryBuilder doReadFrom(StreamInput in) throws IOException {
return new ScriptQueryBuilder(Script.readScript(in)); return new ScriptQueryBuilder(Script.readScript(in));

View File

@ -26,7 +26,9 @@ import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.query.SimpleQueryParser.Settings; import org.elasticsearch.index.query.SimpleQueryParser.Settings;
import java.io.IOException; import java.io.IOException;
@ -260,26 +262,44 @@ public class SimpleQueryStringBuilder extends AbstractQueryBuilder<SimpleQuerySt
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
// Use the default field (_all) if no fields specified // Use the default field (_all) if no fields specified
if (fieldsAndWeights.isEmpty()) { if (fieldsAndWeights.isEmpty()) {
String field = parseContext.defaultField(); String field = context.defaultField();
fieldsAndWeights.put(field, 1.0F); fieldsAndWeights.put(field, 1.0F);
} }
// field names in builder can have wildcards etc, need to resolve them here
Map<String, Float> resolvedFieldsAndWeights = new TreeMap<>();
for (String fField : fieldsAndWeights.keySet()) {
if (Regex.isSimpleMatchPattern(fField)) {
for (String fieldName : context.mapperService().simpleMatchToIndexNames(fField)) {
resolvedFieldsAndWeights.put(fieldName, fieldsAndWeights.get(fField));
}
} else {
MappedFieldType fieldType = context.fieldMapper(fField);
if (fieldType != null) {
resolvedFieldsAndWeights.put(fieldType.names().indexName(), fieldsAndWeights.get(fField));
} else {
resolvedFieldsAndWeights.put(fField, fieldsAndWeights.get(fField));
}
}
}
// Use standard analyzer by default if none specified // Use standard analyzer by default if none specified
Analyzer luceneAnalyzer; Analyzer luceneAnalyzer;
if (analyzer == null) { if (analyzer == null) {
luceneAnalyzer = parseContext.mapperService().searchAnalyzer(); luceneAnalyzer = context.mapperService().searchAnalyzer();
} else { } else {
luceneAnalyzer = parseContext.analysisService().analyzer(analyzer); luceneAnalyzer = context.analysisService().analyzer(analyzer);
if (luceneAnalyzer == null) { if (luceneAnalyzer == null) {
throw new QueryParsingException(parseContext, "[" + SimpleQueryStringBuilder.NAME + "] analyzer [" + analyzer throw new QueryShardException(context, "[" + SimpleQueryStringBuilder.NAME + "] analyzer [" + analyzer
+ "] not found"); + "] not found");
} }
} }
SimpleQueryParser sqp = new SimpleQueryParser(luceneAnalyzer, fieldsAndWeights, flags, settings);
SimpleQueryParser sqp = new SimpleQueryParser(luceneAnalyzer, resolvedFieldsAndWeights, flags, settings);
sqp.setDefaultOperator(defaultOperator.toBooleanClauseOccur()); sqp.setDefaultOperator(defaultOperator.toBooleanClauseOccur());
Query query = sqp.parse(queryText); Query query = sqp.parse(queryText);

View File

@ -20,10 +20,7 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import org.elasticsearch.common.Strings; import org.elasticsearch.common.Strings;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MappedFieldType;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
@ -108,19 +105,7 @@ public class SimpleQueryStringParser extends BaseQueryParser {
if (fField == null) { if (fField == null) {
fField = parser.text(); fField = parser.text();
} }
fieldsAndWeights.put(fField, fBoost);
if (Regex.isSimpleMatchPattern(fField)) {
for (String fieldName : parseContext.mapperService().simpleMatchToIndexNames(fField)) {
fieldsAndWeights.put(fieldName, fBoost);
}
} else {
MappedFieldType fieldType = parseContext.fieldMapper(fField);
if (fieldType != null) {
fieldsAndWeights.put(fieldType.names().indexName(), fBoost);
} else {
fieldsAndWeights.put(fField, fBoost);
}
}
} }
} else { } else {
throw new QueryParsingException(parseContext, throw new QueryParsingException(parseContext,

View File

@ -74,10 +74,10 @@ public class SpanContainingQueryBuilder extends AbstractQueryBuilder<SpanContain
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query innerBig = big.toQuery(parseContext); Query innerBig = big.toQuery(context);
assert innerBig instanceof SpanQuery; assert innerBig instanceof SpanQuery;
Query innerLittle = little.toQuery(parseContext); Query innerLittle = little.toQuery(context);
assert innerLittle instanceof SpanQuery; assert innerLittle instanceof SpanQuery;
return new SpanContainingQuery((SpanQuery) innerBig, (SpanQuery) innerLittle); return new SpanContainingQuery((SpanQuery) innerBig, (SpanQuery) innerLittle);
} }

View File

@ -76,8 +76,8 @@ public class SpanFirstQueryBuilder extends AbstractQueryBuilder<SpanFirstQueryBu
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query innerSpanQuery = matchBuilder.toQuery(parseContext); Query innerSpanQuery = matchBuilder.toQuery(context);
assert innerSpanQuery instanceof SpanQuery; assert innerSpanQuery instanceof SpanQuery;
return new SpanFirstQuery((SpanQuery) innerSpanQuery, end); return new SpanFirstQuery((SpanQuery) innerSpanQuery, end);
} }

View File

@ -57,8 +57,8 @@ public class SpanMultiTermQueryBuilder extends AbstractQueryBuilder<SpanMultiTer
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query subQuery = multiTermQueryBuilder.toQuery(parseContext); Query subQuery = multiTermQueryBuilder.toQuery(context);
if (subQuery instanceof MultiTermQuery == false) { if (subQuery instanceof MultiTermQuery == false) {
throw new UnsupportedOperationException("unsupported inner query, should be " + MultiTermQuery.class.getName() +" but was " throw new UnsupportedOperationException("unsupported inner query, should be " + MultiTermQuery.class.getName() +" but was "
+ subQuery.getClass().getName()); + subQuery.getClass().getName());

View File

@ -130,10 +130,10 @@ public class SpanNearQueryBuilder extends AbstractQueryBuilder<SpanNearQueryBuil
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
SpanQuery[] spanQueries = new SpanQuery[clauses.size()]; SpanQuery[] spanQueries = new SpanQuery[clauses.size()];
for (int i = 0; i < clauses.size(); i++) { for (int i = 0; i < clauses.size(); i++) {
Query query = clauses.get(i).toQuery(parseContext); Query query = clauses.get(i).toQuery(context);
assert query instanceof SpanQuery; assert query instanceof SpanQuery;
spanQueries[i] = (SpanQuery) query; spanQueries[i] = (SpanQuery) query;
} }

View File

@ -130,11 +130,11 @@ public class SpanNotQueryBuilder extends AbstractQueryBuilder<SpanNotQueryBuilde
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query includeQuery = this.include.toQuery(parseContext); Query includeQuery = this.include.toQuery(context);
assert includeQuery instanceof SpanQuery; assert includeQuery instanceof SpanQuery;
Query excludeQuery = this.exclude.toQuery(parseContext); Query excludeQuery = this.exclude.toQuery(context);
assert excludeQuery instanceof SpanQuery; assert excludeQuery instanceof SpanQuery;
SpanNotQuery query = new SpanNotQuery((SpanQuery) includeQuery, (SpanQuery) excludeQuery, pre, post); SpanNotQuery query = new SpanNotQuery((SpanQuery) includeQuery, (SpanQuery) excludeQuery, pre, post);

View File

@ -67,10 +67,10 @@ public class SpanOrQueryBuilder extends AbstractQueryBuilder<SpanOrQueryBuilder>
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
SpanQuery[] spanQueries = new SpanQuery[clauses.size()]; SpanQuery[] spanQueries = new SpanQuery[clauses.size()];
for (int i = 0; i < clauses.size(); i++) { for (int i = 0; i < clauses.size(); i++) {
Query query = clauses.get(i).toQuery(parseContext); Query query = clauses.get(i).toQuery(context);
assert query instanceof SpanQuery; assert query instanceof SpanQuery;
spanQueries[i] = (SpanQuery) query; spanQueries[i] = (SpanQuery) query;
} }

View File

@ -68,7 +68,7 @@ public class SpanTermQueryBuilder extends BaseTermQueryBuilder<SpanTermQueryBuil
} }
@Override @Override
public SpanQuery doToQuery(QueryParseContext context) throws IOException { public SpanQuery doToQuery(QueryShardContext context) throws IOException {
BytesRef valueBytes = null; BytesRef valueBytes = null;
String fieldName = this.fieldName; String fieldName = this.fieldName;
MappedFieldType mapper = context.fieldMapper(fieldName); MappedFieldType mapper = context.fieldMapper(fieldName);

View File

@ -79,10 +79,10 @@ public class SpanWithinQueryBuilder extends AbstractQueryBuilder<SpanWithinQuery
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query innerBig = big.toQuery(parseContext); Query innerBig = big.toQuery(context);
assert innerBig instanceof SpanQuery; assert innerBig instanceof SpanQuery;
Query innerLittle = little.toQuery(parseContext); Query innerLittle = little.toQuery(context);
assert innerLittle instanceof SpanQuery; assert innerLittle instanceof SpanQuery;
return new SpanWithinQuery((SpanQuery) innerBig, (SpanQuery) innerLittle); return new SpanWithinQuery((SpanQuery) innerBig, (SpanQuery) innerLittle);
} }

View File

@ -66,13 +66,14 @@ public class TemplateQueryParser extends BaseQueryParserTemp {
* Parses the template query replacing template parameters with provided * Parses the template query replacing template parameters with provided
* values. Handles both submitting the template as part of the request as * values. Handles both submitting the template as part of the request as
* well as referencing only the template name. * well as referencing only the template name.
* *
* @param parseContext * @param context
* parse context containing the templated query. * parse context containing the templated query.
*/ */
@Override @Override
@Nullable @Nullable
public Query parse(QueryParseContext parseContext) throws IOException { public Query parse(QueryShardContext context) throws IOException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
Template template = parse(parser, parseContext.parseFieldMatcher()); Template template = parse(parser, parseContext.parseFieldMatcher());
ExecutableScript executable = this.scriptService.executable(template, ScriptContext.Standard.SEARCH); ExecutableScript executable = this.scriptService.executable(template, ScriptContext.Standard.SEARCH);
@ -80,9 +81,9 @@ public class TemplateQueryParser extends BaseQueryParserTemp {
BytesReference querySource = (BytesReference) executable.run(); BytesReference querySource = (BytesReference) executable.run();
try (XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource)) { try (XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource)) {
final QueryParseContext context = new QueryParseContext(parseContext.index(), parseContext.indexQueryParserService()); final QueryShardContext contextCopy = new QueryShardContext(context.index(), context.indexQueryParserService());
context.reset(qSourceParser); contextCopy.reset(qSourceParser);
return context.parseInnerQuery(); return contextCopy.parseContext().parseInnerQuery();
} }
} }

View File

@ -71,11 +71,11 @@ public class TermQueryBuilder extends BaseTermQueryBuilder<TermQueryBuilder> {
} }
@Override @Override
public Query doToQuery(QueryParseContext parseContext) throws IOException { public Query doToQuery(QueryShardContext context) throws IOException {
Query query = null; Query query = null;
MappedFieldType mapper = parseContext.fieldMapper(this.fieldName); MappedFieldType mapper = context.fieldMapper(this.fieldName);
if (mapper != null) { if (mapper != null) {
query = mapper.termQuery(this.value, parseContext); query = mapper.termQuery(this.value, context);
} }
if (query == null) { if (query == null) {
query = new TermQuery(new Term(this.fieldName, BytesRefs.toBytesRef(this.value))); query = new TermQuery(new Term(this.fieldName, BytesRefs.toBytesRef(this.value)));

View File

@ -70,7 +70,8 @@ public class TermsQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String queryName = null; String queryName = null;
@ -158,7 +159,7 @@ public class TermsQueryParser extends BaseQueryParserTemp {
throw new QueryParsingException(parseContext, "terms query requires a field name, followed by array of terms"); throw new QueryParsingException(parseContext, "terms query requires a field name, followed by array of terms");
} }
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType != null) { if (fieldType != null) {
fieldName = fieldType.names().indexName(); fieldName = fieldType.names().indexName();
} }
@ -181,7 +182,7 @@ public class TermsQueryParser extends BaseQueryParserTemp {
Query query; Query query;
if (parseContext.isFilter()) { if (parseContext.isFilter()) {
if (fieldType != null) { if (fieldType != null) {
query = fieldType.termsQuery(terms, parseContext); query = fieldType.termsQuery(terms, context);
} else { } else {
BytesRef[] filterValues = new BytesRef[terms.size()]; BytesRef[] filterValues = new BytesRef[terms.size()];
for (int i = 0; i < filterValues.length; i++) { for (int i = 0; i < filterValues.length; i++) {
@ -193,7 +194,7 @@ public class TermsQueryParser extends BaseQueryParserTemp {
BooleanQuery bq = new BooleanQuery(); BooleanQuery bq = new BooleanQuery();
for (Object term : terms) { for (Object term : terms) {
if (fieldType != null) { if (fieldType != null) {
bq.add(fieldType.termQuery(term, parseContext), Occur.SHOULD); bq.add(fieldType.termQuery(term, context), Occur.SHOULD);
} else { } else {
bq.add(new TermQuery(new Term(fieldName, BytesRefs.toBytesRef(term))), Occur.SHOULD); bq.add(new TermQuery(new Term(fieldName, BytesRefs.toBytesRef(term))), Occur.SHOULD);
} }
@ -204,7 +205,7 @@ public class TermsQueryParser extends BaseQueryParserTemp {
query.setBoost(boost); query.setBoost(boost);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
return query; return query;
} }

View File

@ -48,10 +48,10 @@ public class TypeQueryBuilder extends AbstractQueryBuilder<TypeQueryBuilder> {
TypeQueryBuilder(BytesRef type) { TypeQueryBuilder(BytesRef type) {
this.type = type; this.type = type;
} }
public BytesRef type() { public BytesRef type() {
return this.type; return this.type;
} }
@Override @Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException { protected void doXContent(XContentBuilder builder, Params params) throws IOException {
@ -67,10 +67,10 @@ public class TypeQueryBuilder extends AbstractQueryBuilder<TypeQueryBuilder> {
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
Query filter; Query filter;
//LUCENE 4 UPGRADE document mapper should use bytesref as well? //LUCENE 4 UPGRADE document mapper should use bytesref as well?
DocumentMapper documentMapper = parseContext.mapperService().documentMapper(type.utf8ToString()); DocumentMapper documentMapper = context.mapperService().documentMapper(type.utf8ToString());
if (documentMapper == null) { if (documentMapper == null) {
filter = new TermQuery(new Term(TypeFieldMapper.NAME, type)); filter = new TermQuery(new Term(TypeFieldMapper.NAME, type));
} else { } else {

View File

@ -106,11 +106,11 @@ public class WildcardQueryBuilder extends AbstractQueryBuilder<WildcardQueryBuil
} }
@Override @Override
protected Query doToQuery(QueryParseContext parseContext) throws IOException { protected Query doToQuery(QueryShardContext context) throws IOException {
String indexFieldName; String indexFieldName;
BytesRef valueBytes; BytesRef valueBytes;
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType != null) { if (fieldType != null) {
indexFieldName = fieldType.names().indexName(); indexFieldName = fieldType.names().indexName();
valueBytes = fieldType.indexedValueForSearch(value); valueBytes = fieldType.indexedValueForSearch(value);
@ -120,7 +120,7 @@ public class WildcardQueryBuilder extends AbstractQueryBuilder<WildcardQueryBuil
} }
WildcardQuery query = new WildcardQuery(new Term(indexFieldName, valueBytes)); WildcardQuery query = new WildcardQuery(new Term(indexFieldName, valueBytes));
MultiTermQuery.RewriteMethod rewriteMethod = QueryParsers.parseRewriteMethod(parseContext.parseFieldMatcher(), rewrite, null); MultiTermQuery.RewriteMethod rewriteMethod = QueryParsers.parseRewriteMethod(context.parseFieldMatcher(), rewrite, null);
QueryParsers.setRewriteMethod(query, rewriteMethod); QueryParsers.setRewriteMethod(query, rewriteMethod);
return query; return query;
} }

View File

@ -41,7 +41,8 @@ public class WrapperQueryParser extends BaseQueryParserTemp {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken(); XContentParser.Token token = parser.nextToken();
@ -56,11 +57,11 @@ public class WrapperQueryParser extends BaseQueryParserTemp {
byte[] querySource = parser.binaryValue(); byte[] querySource = parser.binaryValue();
try (XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource)) { try (XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource)) {
final QueryParseContext context = new QueryParseContext(parseContext.index(), parseContext.indexQueryParserService()); final QueryShardContext contextCopy = new QueryShardContext(context.index(), context.indexQueryParserService());
context.reset(qSourceParser); contextCopy.reset(qSourceParser);
Query result = context.parseInnerQuery(); Query result = contextCopy.parseContext().parseInnerQuery();
parser.nextToken(); parser.nextToken();
parseContext.combineNamedQueries(context); context.combineNamedQueries(contextCopy);
return result; return result;
} }
} }

View File

@ -43,7 +43,7 @@ import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.core.DateFieldMapper; import org.elasticsearch.index.mapper.core.DateFieldMapper;
import org.elasticsearch.index.mapper.core.NumberFieldMapper; import org.elasticsearch.index.mapper.core.NumberFieldMapper;
import org.elasticsearch.index.mapper.geo.GeoPointFieldMapper; import org.elasticsearch.index.mapper.geo.GeoPointFieldMapper;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.index.query.functionscore.gauss.GaussDecayFunctionBuilder; import org.elasticsearch.index.query.functionscore.gauss.GaussDecayFunctionBuilder;
import org.elasticsearch.index.query.functionscore.gauss.GaussDecayFunctionParser; import org.elasticsearch.index.query.functionscore.gauss.GaussDecayFunctionParser;
@ -119,7 +119,7 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
* *
* */ * */
@Override @Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException { public ScoreFunction parse(QueryShardContext context, XContentParser parser) throws IOException, QueryParsingException {
String currentFieldName; String currentFieldName;
XContentParser.Token token; XContentParser.Token token;
AbstractDistanceScoreFunction scoreFunction; AbstractDistanceScoreFunction scoreFunction;
@ -132,7 +132,7 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
if (token == XContentParser.Token.START_OBJECT) { if (token == XContentParser.Token.START_OBJECT) {
variableContent.copyCurrentStructure(parser); variableContent.copyCurrentStructure(parser);
fieldName = currentFieldName; fieldName = currentFieldName;
} else if (parseContext.parseFieldMatcher().match(currentFieldName, MULTI_VALUE_MODE)) { } else if (context.parseFieldMatcher().match(currentFieldName, MULTI_VALUE_MODE)) {
multiValueMode = parser.text(); multiValueMode = parser.text();
} else { } else {
throw new ElasticsearchParseException("malformed score function score parameters."); throw new ElasticsearchParseException("malformed score function score parameters.");
@ -142,34 +142,34 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
throw new ElasticsearchParseException("malformed score function score parameters."); throw new ElasticsearchParseException("malformed score function score parameters.");
} }
XContentParser variableParser = XContentFactory.xContent(variableContent.string()).createParser(variableContent.string()); XContentParser variableParser = XContentFactory.xContent(variableContent.string()).createParser(variableContent.string());
scoreFunction = parseVariable(fieldName, variableParser, parseContext, MultiValueMode.fromString(multiValueMode.toUpperCase(Locale.ROOT))); scoreFunction = parseVariable(fieldName, variableParser, context, MultiValueMode.fromString(multiValueMode.toUpperCase(Locale.ROOT)));
return scoreFunction; return scoreFunction;
} }
// parses origin and scale parameter for field "fieldName" // parses origin and scale parameter for field "fieldName"
private AbstractDistanceScoreFunction parseVariable(String fieldName, XContentParser parser, QueryParseContext parseContext, MultiValueMode mode) throws IOException { private AbstractDistanceScoreFunction parseVariable(String fieldName, XContentParser parser, QueryShardContext context, MultiValueMode mode) throws IOException {
// now, the field must exist, else we cannot read the value for // now, the field must exist, else we cannot read the value for
// the doc later // the doc later
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType == null) { if (fieldType == null) {
throw new QueryParsingException(parseContext, "unknown field [{}]", fieldName); throw new QueryParsingException(context.parseContext(), "unknown field [{}]", fieldName);
} }
// dates and time need special handling // dates and time need special handling
parser.nextToken(); parser.nextToken();
if (fieldType instanceof DateFieldMapper.DateFieldType) { if (fieldType instanceof DateFieldMapper.DateFieldType) {
return parseDateVariable(fieldName, parser, parseContext, (DateFieldMapper.DateFieldType) fieldType, mode); return parseDateVariable(fieldName, parser, context, (DateFieldMapper.DateFieldType) fieldType, mode);
} else if (fieldType instanceof GeoPointFieldMapper.GeoPointFieldType) { } else if (fieldType instanceof GeoPointFieldMapper.GeoPointFieldType) {
return parseGeoVariable(fieldName, parser, parseContext, (GeoPointFieldMapper.GeoPointFieldType) fieldType, mode); return parseGeoVariable(fieldName, parser, context, (GeoPointFieldMapper.GeoPointFieldType) fieldType, mode);
} else if (fieldType instanceof NumberFieldMapper.NumberFieldType) { } else if (fieldType instanceof NumberFieldMapper.NumberFieldType) {
return parseNumberVariable(fieldName, parser, parseContext, (NumberFieldMapper.NumberFieldType) fieldType, mode); return parseNumberVariable(fieldName, parser, context, (NumberFieldMapper.NumberFieldType) fieldType, mode);
} else { } else {
throw new QueryParsingException(parseContext, "field [{}] is of type [{}], but only numeric types are supported.", fieldName, fieldType); throw new QueryParsingException(context.parseContext(), "field [{}] is of type [{}], but only numeric types are supported.", fieldName, fieldType);
} }
} }
private AbstractDistanceScoreFunction parseNumberVariable(String fieldName, XContentParser parser, QueryParseContext parseContext, private AbstractDistanceScoreFunction parseNumberVariable(String fieldName, XContentParser parser, QueryShardContext context,
NumberFieldMapper.NumberFieldType fieldType, MultiValueMode mode) throws IOException { NumberFieldMapper.NumberFieldType fieldType, MultiValueMode mode) throws IOException {
XContentParser.Token token; XContentParser.Token token;
String parameterName = null; String parameterName = null;
@ -199,11 +199,11 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
if (!scaleFound || !refFound) { if (!scaleFound || !refFound) {
throw new ElasticsearchParseException("both [{}] and [{}] must be set for numeric fields.", DecayFunctionBuilder.SCALE, DecayFunctionBuilder.ORIGIN); throw new ElasticsearchParseException("both [{}] and [{}] must be set for numeric fields.", DecayFunctionBuilder.SCALE, DecayFunctionBuilder.ORIGIN);
} }
IndexNumericFieldData numericFieldData = parseContext.getForField(fieldType); IndexNumericFieldData numericFieldData = context.getForField(fieldType);
return new NumericFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), numericFieldData, mode); return new NumericFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), numericFieldData, mode);
} }
private AbstractDistanceScoreFunction parseGeoVariable(String fieldName, XContentParser parser, QueryParseContext parseContext, private AbstractDistanceScoreFunction parseGeoVariable(String fieldName, XContentParser parser, QueryShardContext context,
GeoPointFieldMapper.GeoPointFieldType fieldType, MultiValueMode mode) throws IOException { GeoPointFieldMapper.GeoPointFieldType fieldType, MultiValueMode mode) throws IOException {
XContentParser.Token token; XContentParser.Token token;
String parameterName = null; String parameterName = null;
@ -231,12 +231,12 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
} }
double scale = DistanceUnit.DEFAULT.parse(scaleString, DistanceUnit.DEFAULT); double scale = DistanceUnit.DEFAULT.parse(scaleString, DistanceUnit.DEFAULT);
double offset = DistanceUnit.DEFAULT.parse(offsetString, DistanceUnit.DEFAULT); double offset = DistanceUnit.DEFAULT.parse(offsetString, DistanceUnit.DEFAULT);
IndexGeoPointFieldData indexFieldData = parseContext.getForField(fieldType); IndexGeoPointFieldData indexFieldData = context.getForField(fieldType);
return new GeoFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), indexFieldData, mode); return new GeoFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), indexFieldData, mode);
} }
private AbstractDistanceScoreFunction parseDateVariable(String fieldName, XContentParser parser, QueryParseContext parseContext, private AbstractDistanceScoreFunction parseDateVariable(String fieldName, XContentParser parser, QueryShardContext context,
DateFieldMapper.DateFieldType dateFieldType, MultiValueMode mode) throws IOException { DateFieldMapper.DateFieldType dateFieldType, MultiValueMode mode) throws IOException {
XContentParser.Token token; XContentParser.Token token;
String parameterName = null; String parameterName = null;
@ -271,7 +271,7 @@ public abstract class DecayFunctionParser implements ScoreFunctionParser {
double scale = val.getMillis(); double scale = val.getMillis();
val = TimeValue.parseTimeValue(offsetString, TimeValue.timeValueHours(24), getClass().getSimpleName() + ".offset"); val = TimeValue.parseTimeValue(offsetString, TimeValue.timeValueHours(24), getClass().getSimpleName() + ".offset");
double offset = val.getMillis(); double offset = val.getMillis();
IndexNumericFieldData numericFieldData = parseContext.getForField(dateFieldType); IndexNumericFieldData numericFieldData = context.getForField(dateFieldType);
return new NumericFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), numericFieldData, mode); return new NumericFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), numericFieldData, mode);
} }

View File

@ -82,7 +82,8 @@ public class FunctionScoreQueryParser implements QueryParser {
} }
@Override @Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException { public Query parse(QueryShardContext context) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
Query query = null; Query query = null;
@ -127,7 +128,7 @@ public class FunctionScoreQueryParser implements QueryParser {
String errorString = "already found [" + singleFunctionName + "], now encountering [functions]."; String errorString = "already found [" + singleFunctionName + "], now encountering [functions].";
handleMisplacedFunctionsDeclaration(errorString, singleFunctionName); handleMisplacedFunctionsDeclaration(errorString, singleFunctionName);
} }
currentFieldName = parseFiltersAndFunctions(parseContext, parser, filterFunctions, currentFieldName); currentFieldName = parseFiltersAndFunctions(context, parser, filterFunctions, currentFieldName);
functionArrayFound = true; functionArrayFound = true;
} else { } else {
ScoreFunction scoreFunction; ScoreFunction scoreFunction;
@ -138,7 +139,7 @@ public class FunctionScoreQueryParser implements QueryParser {
// we try to parse a score function. If there is no score // we try to parse a score function. If there is no score
// function for the current field name, // function for the current field name,
// functionParserMapper.get() will throw an Exception. // functionParserMapper.get() will throw an Exception.
scoreFunction = functionParserMapper.get(parseContext, currentFieldName).parse(parseContext, parser); scoreFunction = functionParserMapper.get(parseContext, currentFieldName).parse(context, parser);
} }
if (functionArrayFound) { if (functionArrayFound) {
String errorString = "already found [functions] array, now encountering [" + currentFieldName + "]."; String errorString = "already found [functions] array, now encountering [" + currentFieldName + "].";
@ -191,7 +192,7 @@ public class FunctionScoreQueryParser implements QueryParser {
} }
result.setBoost(boost); result.setBoost(boost);
if (queryName != null) { if (queryName != null) {
parseContext.addNamedQuery(queryName, query); context.addNamedQuery(queryName, query);
} }
return result; return result;
} }
@ -204,8 +205,9 @@ public class FunctionScoreQueryParser implements QueryParser {
throw new ElasticsearchParseException("failed to parse [{}] query. [{}]", NAME, errorString); throw new ElasticsearchParseException("failed to parse [{}] query. [{}]", NAME, errorString);
} }
private String parseFiltersAndFunctions(QueryParseContext parseContext, XContentParser parser, private String parseFiltersAndFunctions(QueryShardContext context, XContentParser parser,
ArrayList<FiltersFunctionScoreQuery.FilterFunction> filterFunctions, String currentFieldName) throws IOException { ArrayList<FiltersFunctionScoreQuery.FilterFunction> filterFunctions, String currentFieldName) throws IOException {
QueryParseContext parseContext = context.parseContext();
XContentParser.Token token; XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
Query filter = null; Query filter = null;
@ -227,7 +229,7 @@ public class FunctionScoreQueryParser implements QueryParser {
// functionParserMapper throws exception if parser // functionParserMapper throws exception if parser
// non-existent // non-existent
ScoreFunctionParser functionParser = functionParserMapper.get(parseContext, currentFieldName); ScoreFunctionParser functionParser = functionParserMapper.get(parseContext, currentFieldName);
scoreFunction = functionParser.parse(parseContext, parser); scoreFunction = functionParser.parse(context, parser);
} }
} }
} }
@ -275,9 +277,10 @@ public class FunctionScoreQueryParser implements QueryParser {
return cf; return cf;
} }
//norelease to be removed once all queries are moved over to extend BaseQueryParser
@Override @Override
public QueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, QueryParsingException { public QueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, QueryParsingException {
Query query = parse(parseContext); Query query = parse(parseContext.shardContext());
return new QueryWrappingQueryBuilder(query); return new QueryWrappingQueryBuilder(query);
} }

View File

@ -21,14 +21,14 @@ package org.elasticsearch.index.query.functionscore;
import org.elasticsearch.common.lucene.search.function.ScoreFunction; import org.elasticsearch.common.lucene.search.function.ScoreFunction;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryParsingException;
import java.io.IOException; import java.io.IOException;
public interface ScoreFunctionParser { public interface ScoreFunctionParser {
ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException; ScoreFunction parse(QueryShardContext context, XContentParser parser) throws IOException, QueryParsingException;
/** /**
* Returns the name of the function, for example "linear", "gauss" etc. This * Returns the name of the function, for example "linear", "gauss" etc. This

View File

@ -19,14 +19,13 @@
package org.elasticsearch.index.query.functionscore.factor; package org.elasticsearch.index.query.functionscore.factor;
import org.elasticsearch.index.query.functionscore.ScoreFunctionParser;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.lucene.search.function.BoostScoreFunction; import org.elasticsearch.common.lucene.search.function.BoostScoreFunction;
import org.elasticsearch.common.lucene.search.function.ScoreFunction; import org.elasticsearch.common.lucene.search.function.ScoreFunction;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.index.query.functionscore.ScoreFunctionParser;
import java.io.IOException; import java.io.IOException;
@ -43,7 +42,7 @@ public class FactorParser implements ScoreFunctionParser {
} }
@Override @Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException { public ScoreFunction parse(QueryShardContext context, XContentParser parser) throws IOException, QueryParsingException {
float boostFactor = parser.floatValue(); float boostFactor = parser.floatValue();
return new BoostScoreFunction(boostFactor); return new BoostScoreFunction(boostFactor);
} }

View File

@ -24,8 +24,8 @@ import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction;
import org.elasticsearch.common.lucene.search.function.ScoreFunction; import org.elasticsearch.common.lucene.search.function.ScoreFunction;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexNumericFieldData; import org.elasticsearch.index.fielddata.IndexNumericFieldData;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.index.query.functionscore.ScoreFunctionParser; import org.elasticsearch.index.query.functionscore.ScoreFunctionParser;
@ -52,7 +52,8 @@ public class FieldValueFactorFunctionParser implements ScoreFunctionParser {
public static String[] NAMES = { "field_value_factor", "fieldValueFactor" }; public static String[] NAMES = { "field_value_factor", "fieldValueFactor" };
@Override @Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException { public ScoreFunction parse(QueryShardContext context, XContentParser parser) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
String currentFieldName = null; String currentFieldName = null;
String field = null; String field = null;

View File

@ -27,8 +27,8 @@ import org.elasticsearch.common.lucene.search.function.RandomScoreFunction;
import org.elasticsearch.common.lucene.search.function.ScoreFunction; import org.elasticsearch.common.lucene.search.function.ScoreFunction;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexFieldData; import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.index.query.functionscore.ScoreFunctionParser; import org.elasticsearch.index.query.functionscore.ScoreFunctionParser;
@ -51,8 +51,8 @@ public class RandomScoreFunctionParser implements ScoreFunctionParser {
} }
@Override @Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException { public ScoreFunction parse(QueryShardContext context, XContentParser parser) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
int seed = -1; int seed = -1;
String currentFieldName = null; String currentFieldName = null;
@ -90,7 +90,7 @@ public class RandomScoreFunctionParser implements ScoreFunctionParser {
} }
if (seed == -1) { if (seed == -1) {
seed = Longs.hashCode(parseContext.nowInMillis()); seed = Longs.hashCode(context.nowInMillis());
} }
final ShardId shardId = SearchContext.current().indexShard().shardId(); final ShardId shardId = SearchContext.current().indexShard().shardId();
final int salt = (shardId.index().name().hashCode() << 10) | shardId.id(); final int salt = (shardId.index().name().hashCode() << 10) | shardId.id();

View File

@ -21,11 +21,11 @@
package org.elasticsearch.index.query.functionscore.script; package org.elasticsearch.index.query.functionscore.script;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.lucene.search.function.ScoreFunction; import org.elasticsearch.common.lucene.search.function.ScoreFunction;
import org.elasticsearch.common.lucene.search.function.ScriptScoreFunction; import org.elasticsearch.common.lucene.search.function.ScriptScoreFunction;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.index.query.functionscore.ScoreFunctionParser; import org.elasticsearch.index.query.functionscore.ScoreFunctionParser;
@ -58,7 +58,8 @@ public class ScriptScoreFunctionParser implements ScoreFunctionParser {
} }
@Override @Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException { public ScoreFunction parse(QueryShardContext context, XContentParser parser) throws IOException, QueryParsingException {
QueryParseContext parseContext = context.parseContext();
ScriptParameterParser scriptParameterParser = new ScriptParameterParser(); ScriptParameterParser scriptParameterParser = new ScriptParameterParser();
Script script = null; Script script = null;
Map<String, Object> vars = null; Map<String, Object> vars = null;
@ -100,7 +101,7 @@ public class ScriptScoreFunctionParser implements ScoreFunctionParser {
SearchScript searchScript; SearchScript searchScript;
try { try {
searchScript = parseContext.scriptService().search(parseContext.lookup(), script, ScriptContext.Standard.SEARCH); searchScript = context.scriptService().search(context.lookup(), script, ScriptContext.Standard.SEARCH);
return new ScriptScoreFunction(script, searchScript); return new ScriptScoreFunction(script, searchScript);
} catch (Exception e) { } catch (Exception e) {
throw new QueryParsingException(parseContext, NAMES[0] + " the script could not be loaded", e); throw new QueryParsingException(parseContext, NAMES[0] + " the script could not be loaded", e);

View File

@ -22,6 +22,7 @@ package org.elasticsearch.index.query.support;
import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.search.fetch.fielddata.FieldDataFieldsParseElement; import org.elasticsearch.search.fetch.fielddata.FieldDataFieldsParseElement;
@ -51,7 +52,7 @@ public class InnerHitsQueryParserHelper {
this.fieldDataFieldsParseElement = fieldDataFieldsParseElement; this.fieldDataFieldsParseElement = fieldDataFieldsParseElement;
} }
public Tuple<String, SubSearchContext> parse(QueryParseContext parserContext) throws IOException, QueryParsingException { public Tuple<String, SubSearchContext> parse(QueryParseContext parserContext) throws IOException, QueryShardException {
String fieldName = null; String fieldName = null;
XContentParser.Token token; XContentParser.Token token;
String innerHitName = null; String innerHitName = null;

View File

@ -26,10 +26,10 @@ import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.object.ObjectMapper; import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryParsingException;
import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException; import java.io.IOException;
@ -41,6 +41,7 @@ import java.io.IOException;
*/ */
public class NestedInnerQueryParseSupport { public class NestedInnerQueryParseSupport {
protected final QueryShardContext shardContext;
protected final QueryParseContext parseContext; protected final QueryParseContext parseContext;
private BytesReference source; private BytesReference source;
@ -60,12 +61,15 @@ public class NestedInnerQueryParseSupport {
private ObjectMapper parentObjectMapper; private ObjectMapper parentObjectMapper;
public NestedInnerQueryParseSupport(XContentParser parser, SearchContext searchContext) { public NestedInnerQueryParseSupport(XContentParser parser, SearchContext searchContext) {
parseContext = searchContext.queryParserService().getParseContext(); parseContext = searchContext.queryParserService().getShardContext().parseContext();
parseContext.reset(parser); shardContext = searchContext.queryParserService().getShardContext();
shardContext.reset(parser);
} }
public NestedInnerQueryParseSupport(QueryParseContext parseContext) { public NestedInnerQueryParseSupport(QueryShardContext context) {
this.parseContext = parseContext; this.parseContext = context.parseContext();
this.shardContext = context;
} }
public void query() throws IOException { public void query() throws IOException {
@ -103,10 +107,10 @@ public class NestedInnerQueryParseSupport {
return innerQuery; return innerQuery;
} else { } else {
if (path == null) { if (path == null) {
throw new QueryParsingException(parseContext, "[nested] requires 'path' field"); throw new QueryShardException(shardContext, "[nested] requires 'path' field");
} }
if (!queryFound) { if (!queryFound) {
throw new QueryParsingException(parseContext, "[nested] requires either 'query' or 'filter' field"); throw new QueryShardException(shardContext, "[nested] requires either 'query' or 'filter' field");
} }
XContentParser old = parseContext.parser(); XContentParser old = parseContext.parser();
@ -132,10 +136,10 @@ public class NestedInnerQueryParseSupport {
return innerFilter; return innerFilter;
} else { } else {
if (path == null) { if (path == null) {
throw new QueryParsingException(parseContext, "[nested] requires 'path' field"); throw new QueryShardException(shardContext, "[nested] requires 'path' field");
} }
if (!filterFound) { if (!filterFound) {
throw new QueryParsingException(parseContext, "[nested] requires either 'query' or 'filter' field"); throw new QueryShardException(shardContext, "[nested] requires either 'query' or 'filter' field");
} }
setPathLevel(); setPathLevel();
@ -155,12 +159,12 @@ public class NestedInnerQueryParseSupport {
public void setPath(String path) { public void setPath(String path) {
this.path = path; this.path = path;
nestedObjectMapper = parseContext.getObjectMapper(path); nestedObjectMapper = shardContext.getObjectMapper(path);
if (nestedObjectMapper == null) { if (nestedObjectMapper == null) {
throw new QueryParsingException(parseContext, "[nested] failed to find nested object under path [" + path + "]"); throw new QueryShardException(shardContext, "[nested] failed to find nested object under path [" + path + "]");
} }
if (!nestedObjectMapper.nested().isNested()) { if (!nestedObjectMapper.nested().isNested()) {
throw new QueryParsingException(parseContext, "[nested] nested object under path [" + path + "] is not of nested type"); throw new QueryShardException(shardContext, "[nested] nested object under path [" + path + "] is not of nested type");
} }
} }
@ -185,18 +189,18 @@ public class NestedInnerQueryParseSupport {
} }
private void setPathLevel() { private void setPathLevel() {
ObjectMapper objectMapper = parseContext.nestedScope().getObjectMapper(); ObjectMapper objectMapper = shardContext.nestedScope().getObjectMapper();
if (objectMapper == null) { if (objectMapper == null) {
parentFilter = parseContext.bitsetFilter(Queries.newNonNestedFilter()); parentFilter = shardContext.bitsetFilter(Queries.newNonNestedFilter());
} else { } else {
parentFilter = parseContext.bitsetFilter(objectMapper.nestedTypeFilter()); parentFilter = shardContext.bitsetFilter(objectMapper.nestedTypeFilter());
} }
childFilter = parseContext.bitsetFilter(nestedObjectMapper.nestedTypeFilter()); childFilter = shardContext.bitsetFilter(nestedObjectMapper.nestedTypeFilter());
parentObjectMapper = parseContext.nestedScope().nextLevel(nestedObjectMapper); parentObjectMapper = shardContext.nestedScope().nextLevel(nestedObjectMapper);
} }
private void resetPathLevel() { private void resetPathLevel() {
parseContext.nestedScope().previousLevel(); shardContext.nestedScope().previousLevel();
} }
} }

View File

@ -25,6 +25,7 @@ import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import java.io.IOException; import java.io.IOException;
@ -84,14 +85,14 @@ public abstract class XContentStructure {
BytesReference br = this.bytes(); BytesReference br = this.bytes();
assert br != null : "innerBytes must be set with .bytes(bytes) or .freeze() before parsing"; assert br != null : "innerBytes must be set with .bytes(bytes) or .freeze() before parsing";
XContentParser innerParser = XContentHelper.createParser(br); XContentParser innerParser = XContentHelper.createParser(br);
String[] origTypes = QueryParseContext.setTypesWithPrevious(types); String[] origTypes = QueryShardContext.setTypesWithPrevious(types);
XContentParser old = parseContext.parser(); XContentParser old = parseContext.parser();
parseContext.parser(innerParser); parseContext.parser(innerParser);
try { try {
return parseContext.parseInnerQuery(); return parseContext.parseInnerQuery();
} finally { } finally {
parseContext.parser(old); parseContext.parser(old);
QueryParseContext.setTypes(origTypes); QueryShardContext.setTypes(origTypes);
} }
} }
@ -106,12 +107,12 @@ public abstract class XContentStructure {
public InnerQuery(QueryParseContext parseContext1, @Nullable String... types) throws IOException { public InnerQuery(QueryParseContext parseContext1, @Nullable String... types) throws IOException {
super(parseContext1); super(parseContext1);
if (types != null) { if (types != null) {
String[] origTypes = QueryParseContext.setTypesWithPrevious(types); String[] origTypes = QueryShardContext.setTypesWithPrevious(types);
try { try {
query = parseContext1.parseInnerQuery(); query = parseContext1.parseInnerQuery();
queryParsed = true; queryParsed = true;
} finally { } finally {
QueryParseContext.setTypes(origTypes); QueryShardContext.setTypes(origTypes);
} }
} else { } else {
BytesReference innerBytes = XContentFactory.smileBuilder().copyCurrentStructure(parseContext1.parser()).bytes(); BytesReference innerBytes = XContentFactory.smileBuilder().copyCurrentStructure(parseContext1.parser()).bytes();

View File

@ -30,7 +30,7 @@ import org.elasticsearch.common.lucene.search.MultiPhrasePrefixQuery;
import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.support.QueryParsers; import org.elasticsearch.index.query.support.QueryParsers;
import java.io.IOException; import java.io.IOException;
@ -49,7 +49,7 @@ public class MatchQuery {
ALL ALL
} }
protected final QueryParseContext parseContext; protected final QueryShardContext context;
protected String analyzer; protected String analyzer;
@ -60,9 +60,9 @@ public class MatchQuery {
protected int phraseSlop = 0; protected int phraseSlop = 0;
protected Fuzziness fuzziness = null; protected Fuzziness fuzziness = null;
protected int fuzzyPrefixLength = FuzzyQuery.defaultPrefixLength; protected int fuzzyPrefixLength = FuzzyQuery.defaultPrefixLength;
protected int maxExpansions = FuzzyQuery.defaultMaxExpansions; protected int maxExpansions = FuzzyQuery.defaultMaxExpansions;
protected boolean transpositions = FuzzyQuery.defaultTranspositions; protected boolean transpositions = FuzzyQuery.defaultTranspositions;
@ -72,11 +72,11 @@ public class MatchQuery {
protected boolean lenient; protected boolean lenient;
protected ZeroTermsQuery zeroTermsQuery = ZeroTermsQuery.NONE; protected ZeroTermsQuery zeroTermsQuery = ZeroTermsQuery.NONE;
protected Float commonTermsCutoff = null; protected Float commonTermsCutoff = null;
public MatchQuery(QueryParseContext parseContext) { public MatchQuery(QueryShardContext context) {
this.parseContext = parseContext; this.context = context;
} }
public void setAnalyzer(String analyzer) { public void setAnalyzer(String analyzer) {
@ -86,7 +86,7 @@ public class MatchQuery {
public void setOccur(BooleanClause.Occur occur) { public void setOccur(BooleanClause.Occur occur) {
this.occur = occur; this.occur = occur;
} }
public void setCommonTermsCutoff(float cutoff) { public void setCommonTermsCutoff(float cutoff) {
this.commonTermsCutoff = Float.valueOf(cutoff); this.commonTermsCutoff = Float.valueOf(cutoff);
} }
@ -134,11 +134,11 @@ public class MatchQuery {
protected Analyzer getAnalyzer(MappedFieldType fieldType) { protected Analyzer getAnalyzer(MappedFieldType fieldType) {
if (this.analyzer == null) { if (this.analyzer == null) {
if (fieldType != null) { if (fieldType != null) {
return parseContext.getSearchAnalyzer(fieldType); return context.getSearchAnalyzer(fieldType);
} }
return parseContext.mapperService().searchAnalyzer(); return context.mapperService().searchAnalyzer();
} else { } else {
Analyzer analyzer = parseContext.mapperService().analysisService().analyzer(this.analyzer); Analyzer analyzer = context.mapperService().analysisService().analyzer(this.analyzer);
if (analyzer == null) { if (analyzer == null) {
throw new IllegalArgumentException("No analyzer found for [" + this.analyzer + "]"); throw new IllegalArgumentException("No analyzer found for [" + this.analyzer + "]");
} }
@ -148,7 +148,7 @@ public class MatchQuery {
public Query parse(Type type, String fieldName, Object value) throws IOException { public Query parse(Type type, String fieldName, Object value) throws IOException {
final String field; final String field;
MappedFieldType fieldType = parseContext.fieldMapper(fieldName); MappedFieldType fieldType = context.fieldMapper(fieldName);
if (fieldType != null) { if (fieldType != null) {
field = fieldType.names().indexName(); field = fieldType.names().indexName();
} else { } else {
@ -157,14 +157,14 @@ public class MatchQuery {
if (fieldType != null && fieldType.useTermQueryWithQueryString() && !forceAnalyzeQueryString()) { if (fieldType != null && fieldType.useTermQueryWithQueryString() && !forceAnalyzeQueryString()) {
try { try {
return fieldType.termQuery(value, parseContext); return fieldType.termQuery(value, context);
} catch (RuntimeException e) { } catch (RuntimeException e) {
if (lenient) { if (lenient) {
return null; return null;
} }
throw e; throw e;
} }
} }
Analyzer analyzer = getAnalyzer(fieldType); Analyzer analyzer = getAnalyzer(fieldType);
assert analyzer != null; assert analyzer != null;

View File

@ -29,10 +29,9 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.query.MultiMatchQueryBuilder; import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@ -48,10 +47,10 @@ public class MultiMatchQuery extends MatchQuery {
this.groupTieBreaker = tieBreaker; this.groupTieBreaker = tieBreaker;
} }
public MultiMatchQuery(QueryParseContext parseContext) { public MultiMatchQuery(QueryShardContext context) {
super(parseContext); super(context);
} }
private Query parseAndApply(Type type, String fieldName, Object value, String minimumShouldMatch, Float boostValue) throws IOException { private Query parseAndApply(Type type, String fieldName, Object value, String minimumShouldMatch, Float boostValue) throws IOException {
Query query = parse(type, fieldName, value); Query query = parse(type, fieldName, value);
if (query instanceof BooleanQuery) { if (query instanceof BooleanQuery) {
@ -163,7 +162,7 @@ public class MultiMatchQuery extends MatchQuery {
List<Tuple<String, Float>> missing = new ArrayList<>(); List<Tuple<String, Float>> missing = new ArrayList<>();
for (Map.Entry<String, Float> entry : fieldNames.entrySet()) { for (Map.Entry<String, Float> entry : fieldNames.entrySet()) {
String name = entry.getKey(); String name = entry.getKey();
MappedFieldType fieldType = parseContext.fieldMapper(name); MappedFieldType fieldType = context.fieldMapper(name);
if (fieldType != null) { if (fieldType != null) {
Analyzer actualAnalyzer = getAnalyzer(fieldType); Analyzer actualAnalyzer = getAnalyzer(fieldType);
name = fieldType.names().indexName(); name = fieldType.names().indexName();

View File

@ -35,7 +35,12 @@ import org.elasticsearch.index.aliases.IndexAliasesService;
import org.elasticsearch.index.cache.IndexCache; import org.elasticsearch.index.cache.IndexCache;
import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.IgnoreOnRecoveryEngineException; import org.elasticsearch.index.engine.IgnoreOnRecoveryEngineException;
import org.elasticsearch.index.mapper.*; import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.MapperException;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.MapperUtils;
import org.elasticsearch.index.mapper.Mapping;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.query.IndexQueryParserService; import org.elasticsearch.index.query.IndexQueryParserService;
import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.query.ParsedQuery;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryParsingException;

View File

@ -28,7 +28,7 @@ import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryShardException;
import java.io.IOException; import java.io.IOException;
@ -115,7 +115,7 @@ public class GND extends NXYSignificanceHeuristic {
} }
@Override @Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException, QueryParsingException { public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException, QueryShardException {
String givenName = parser.currentName(); String givenName = parser.currentName();
boolean backgroundIsSuperset = true; boolean backgroundIsSuperset = true;
XContentParser.Token token = parser.nextToken(); XContentParser.Token token = parser.nextToken();

View File

@ -27,7 +27,7 @@ import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryShardException;
import java.io.IOException; import java.io.IOException;
@ -108,7 +108,7 @@ public class JLHScore extends SignificanceHeuristic {
public static class JLHScoreParser implements SignificanceHeuristicParser { public static class JLHScoreParser implements SignificanceHeuristicParser {
@Override @Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException, QueryParsingException { public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException, QueryShardException {
// move to the closing bracket // move to the closing bracket
if (!parser.nextToken().equals(XContentParser.Token.END_OBJECT)) { if (!parser.nextToken().equals(XContentParser.Token.END_OBJECT)) {
throw new ElasticsearchParseException("failed to parse [jhl] significance heuristic. expected an empty object, but found [{}] instead", parser.currentToken()); throw new ElasticsearchParseException("failed to parse [jhl] significance heuristic. expected an empty object, but found [{}] instead", parser.currentToken());

View File

@ -27,7 +27,7 @@ import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryShardException;
import java.io.IOException; import java.io.IOException;
@ -138,7 +138,7 @@ public abstract class NXYSignificanceHeuristic extends SignificanceHeuristic {
public static abstract class NXYParser implements SignificanceHeuristicParser { public static abstract class NXYParser implements SignificanceHeuristicParser {
@Override @Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException, QueryParsingException { public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException, QueryShardException {
String givenName = parser.currentName(); String givenName = parser.currentName();
boolean includeNegatives = false; boolean includeNegatives = false;
boolean backgroundIsSuperset = true; boolean backgroundIsSuperset = true;

View File

@ -27,7 +27,7 @@ import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryShardException;
import java.io.IOException; import java.io.IOException;
@ -77,7 +77,7 @@ public class PercentageScore extends SignificanceHeuristic {
public static class PercentageScoreParser implements SignificanceHeuristicParser { public static class PercentageScoreParser implements SignificanceHeuristicParser {
@Override @Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException, QueryParsingException { public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException, QueryShardException {
// move to the closing bracket // move to the closing bracket
if (!parser.nextToken().equals(XContentParser.Token.END_OBJECT)) { if (!parser.nextToken().equals(XContentParser.Token.END_OBJECT)) {
throw new ElasticsearchParseException("failed to parse [percentage] significance heuristic. expected an empty object, but got [{}] instead", parser.currentToken()); throw new ElasticsearchParseException("failed to parse [percentage] significance heuristic. expected an empty object, but got [{}] instead", parser.currentToken());

View File

@ -30,7 +30,7 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.logging.ESLoggerFactory; import org.elasticsearch.common.logging.ESLoggerFactory;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParsingException; import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.script.*; import org.elasticsearch.script.*;
import org.elasticsearch.script.Script.ScriptField; import org.elasticsearch.script.Script.ScriptField;
import org.elasticsearch.script.ScriptParameterParser.ScriptParameterValue; import org.elasticsearch.script.ScriptParameterParser.ScriptParameterValue;
@ -130,7 +130,7 @@ public class ScriptHeuristic extends SignificanceHeuristic {
} }
@Override @Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException, QueryParsingException { public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException, QueryShardException {
String heuristicName = parser.currentName(); String heuristicName = parser.currentName();
Script script = null; Script script = null;
XContentParser.Token token; XContentParser.Token token;

View File

@ -24,7 +24,7 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.object.ObjectMapper; import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.query.ParsedQuery;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchParseElement;
import org.elasticsearch.search.fetch.fielddata.FieldDataFieldsParseElement; import org.elasticsearch.search.fetch.fielddata.FieldDataFieldsParseElement;
import org.elasticsearch.search.fetch.script.ScriptFieldsParseElement; import org.elasticsearch.search.fetch.script.ScriptFieldsParseElement;
@ -59,15 +59,15 @@ public class InnerHitsParseElement implements SearchParseElement {
@Override @Override
public void parse(XContentParser parser, SearchContext searchContext) throws Exception { public void parse(XContentParser parser, SearchContext searchContext) throws Exception {
QueryParseContext parseContext = searchContext.queryParserService().getParseContext(); QueryShardContext context = searchContext.queryParserService().getShardContext();
parseContext.reset(parser); context.reset(parser);
Map<String, InnerHitsContext.BaseInnerHits> innerHitsMap = parseInnerHits(parser, parseContext, searchContext); Map<String, InnerHitsContext.BaseInnerHits> innerHitsMap = parseInnerHits(parser, context, searchContext);
if (innerHitsMap != null) { if (innerHitsMap != null) {
searchContext.innerHits(new InnerHitsContext(innerHitsMap)); searchContext.innerHits(new InnerHitsContext(innerHitsMap));
} }
} }
private Map<String, InnerHitsContext.BaseInnerHits> parseInnerHits(XContentParser parser, QueryParseContext parseContext, SearchContext searchContext) throws Exception { private Map<String, InnerHitsContext.BaseInnerHits> parseInnerHits(XContentParser parser, QueryShardContext context, SearchContext searchContext) throws Exception {
XContentParser.Token token; XContentParser.Token token;
Map<String, InnerHitsContext.BaseInnerHits> innerHitsMap = null; Map<String, InnerHitsContext.BaseInnerHits> innerHitsMap = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
@ -79,7 +79,7 @@ public class InnerHitsParseElement implements SearchParseElement {
if (token != XContentParser.Token.START_OBJECT) { if (token != XContentParser.Token.START_OBJECT) {
throw new IllegalArgumentException("Inner hit definition for [" + innerHitName + " starts with a [" + token + "], expected a [" + XContentParser.Token.START_OBJECT + "]."); throw new IllegalArgumentException("Inner hit definition for [" + innerHitName + " starts with a [" + token + "], expected a [" + XContentParser.Token.START_OBJECT + "].");
} }
InnerHitsContext.BaseInnerHits innerHits = parseInnerHit(parser, parseContext, searchContext, innerHitName); InnerHitsContext.BaseInnerHits innerHits = parseInnerHit(parser, context, searchContext, innerHitName);
if (innerHitsMap == null) { if (innerHitsMap == null) {
innerHitsMap = new HashMap<>(); innerHitsMap = new HashMap<>();
} }
@ -88,7 +88,7 @@ public class InnerHitsParseElement implements SearchParseElement {
return innerHitsMap; return innerHitsMap;
} }
private InnerHitsContext.BaseInnerHits parseInnerHit(XContentParser parser, QueryParseContext parseContext, SearchContext searchContext, String innerHitName) throws Exception { private InnerHitsContext.BaseInnerHits parseInnerHit(XContentParser parser, QueryShardContext context, SearchContext searchContext, String innerHitName) throws Exception {
XContentParser.Token token = parser.nextToken(); XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) { if (token != XContentParser.Token.FIELD_NAME) {
throw new IllegalArgumentException("Unexpected token " + token + " inside inner hit definition. Either specify [path] or [type] object"); throw new IllegalArgumentException("Unexpected token " + token + " inside inner hit definition. Either specify [path] or [type] object");
@ -123,9 +123,9 @@ public class InnerHitsParseElement implements SearchParseElement {
final InnerHitsContext.BaseInnerHits innerHits; final InnerHitsContext.BaseInnerHits innerHits;
if (nestedPath != null) { if (nestedPath != null) {
innerHits = parseNested(parser, parseContext, searchContext, fieldName); innerHits = parseNested(parser, context, searchContext, fieldName);
} else if (type != null) { } else if (type != null) {
innerHits = parseParentChild(parser, parseContext, searchContext, fieldName); innerHits = parseParentChild(parser, context, searchContext, fieldName);
} else { } else {
throw new IllegalArgumentException("Either [path] or [type] must be defined"); throw new IllegalArgumentException("Either [path] or [type] must be defined");
} }
@ -143,16 +143,16 @@ public class InnerHitsParseElement implements SearchParseElement {
return innerHits; return innerHits;
} }
private InnerHitsContext.ParentChildInnerHits parseParentChild(XContentParser parser, QueryParseContext parseContext, SearchContext searchContext, String type) throws Exception { private InnerHitsContext.ParentChildInnerHits parseParentChild(XContentParser parser, QueryShardContext context, SearchContext searchContext, String type) throws Exception {
ParseResult parseResult = parseSubSearchContext(searchContext, parseContext, parser); ParseResult parseResult = parseSubSearchContext(searchContext, context, parser);
DocumentMapper documentMapper = searchContext.mapperService().documentMapper(type); DocumentMapper documentMapper = searchContext.mapperService().documentMapper(type);
if (documentMapper == null) { if (documentMapper == null) {
throw new IllegalArgumentException("type [" + type + "] doesn't exist"); throw new IllegalArgumentException("type [" + type + "] doesn't exist");
} }
return new InnerHitsContext.ParentChildInnerHits(parseResult.context(), parseResult.query(), parseResult.childInnerHits(), parseContext.mapperService(), documentMapper); return new InnerHitsContext.ParentChildInnerHits(parseResult.context(), parseResult.query(), parseResult.childInnerHits(), context.mapperService(), documentMapper);
} }
private InnerHitsContext.NestedInnerHits parseNested(XContentParser parser, QueryParseContext parseContext, SearchContext searchContext, String nestedPath) throws Exception { private InnerHitsContext.NestedInnerHits parseNested(XContentParser parser, QueryShardContext context, SearchContext searchContext, String nestedPath) throws Exception {
ObjectMapper objectMapper = searchContext.getObjectMapper(nestedPath); ObjectMapper objectMapper = searchContext.getObjectMapper(nestedPath);
if (objectMapper == null) { if (objectMapper == null) {
throw new IllegalArgumentException("path [" + nestedPath +"] doesn't exist"); throw new IllegalArgumentException("path [" + nestedPath +"] doesn't exist");
@ -160,14 +160,14 @@ public class InnerHitsParseElement implements SearchParseElement {
if (objectMapper.nested().isNested() == false) { if (objectMapper.nested().isNested() == false) {
throw new IllegalArgumentException("path [" + nestedPath +"] isn't nested"); throw new IllegalArgumentException("path [" + nestedPath +"] isn't nested");
} }
ObjectMapper parentObjectMapper = parseContext.nestedScope().nextLevel(objectMapper); ObjectMapper parentObjectMapper = context.nestedScope().nextLevel(objectMapper);
ParseResult parseResult = parseSubSearchContext(searchContext, parseContext, parser); ParseResult parseResult = parseSubSearchContext(searchContext, context, parser);
parseContext.nestedScope().previousLevel(); context.nestedScope().previousLevel();
return new InnerHitsContext.NestedInnerHits(parseResult.context(), parseResult.query(), parseResult.childInnerHits(), parentObjectMapper, objectMapper); return new InnerHitsContext.NestedInnerHits(parseResult.context(), parseResult.query(), parseResult.childInnerHits(), parentObjectMapper, objectMapper);
} }
private ParseResult parseSubSearchContext(SearchContext searchContext, QueryParseContext parseContext, XContentParser parser) throws Exception { private ParseResult parseSubSearchContext(SearchContext searchContext, QueryShardContext context, XContentParser parser) throws Exception {
ParsedQuery query = null; ParsedQuery query = null;
Map<String, InnerHitsContext.BaseInnerHits> childInnerHits = null; Map<String, InnerHitsContext.BaseInnerHits> childInnerHits = null;
SubSearchContext subSearchContext = new SubSearchContext(searchContext); SubSearchContext subSearchContext = new SubSearchContext(searchContext);
@ -178,10 +178,10 @@ public class InnerHitsParseElement implements SearchParseElement {
fieldName = parser.currentName(); fieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if ("query".equals(fieldName)) { if ("query".equals(fieldName)) {
Query q = searchContext.queryParserService().parseInnerQuery(parseContext); Query q = searchContext.queryParserService().parseInnerQuery(context);
query = new ParsedQuery(q, parseContext.copyNamedQueries()); query = new ParsedQuery(q, context.copyNamedQueries());
} else if ("inner_hits".equals(fieldName)) { } else if ("inner_hits".equals(fieldName)) {
childInnerHits = parseInnerHits(parser, parseContext, searchContext); childInnerHits = parseInnerHits(parser, context, searchContext);
} else { } else {
parseCommonInnerHitOptions(parser, token, fieldName, subSearchContext, sortParseElement, sourceParseElement, highlighterParseElement, scriptFieldsParseElement, fieldDataFieldsParseElement); parseCommonInnerHitOptions(parser, token, fieldName, subSearchContext, sortParseElement, sourceParseElement, highlighterParseElement, scriptFieldsParseElement, fieldDataFieldsParseElement);
} }

View File

@ -41,7 +41,7 @@ import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.object.ObjectMapper; import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.query.IndexQueryParserService; import org.elasticsearch.index.query.IndexQueryParserService;
import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.query.ParsedQuery;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.similarity.SimilarityService; import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.script.ScriptService; import org.elasticsearch.script.ScriptService;
@ -74,12 +74,12 @@ public abstract class SearchContext implements Releasable, HasContextAndHeaders
public static void setCurrent(SearchContext value) { public static void setCurrent(SearchContext value) {
current.set(value); current.set(value);
QueryParseContext.setTypes(value.types()); QueryShardContext.setTypes(value.types());
} }
public static void removeCurrent() { public static void removeCurrent() {
current.remove(); current.remove();
QueryParseContext.removeTypes(); QueryShardContext.removeTypes();
} }
public static SearchContext current() { public static SearchContext current() {

Some files were not shown because too many files have changed in this diff Show More