/** * creates random highlighter, renders it to xContent and back to new instance that should be equal to original */ public void testFromXContent() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { HighlightBuilder highlightBuilder = randomHighlighterBuilder(); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { builder.prettyPrint(); } highlightBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentBuilder shuffled = shuffleXContent(builder); XContentParser parser = createParser(shuffled); QueryParseContext context = new QueryParseContext(parser); parser.nextToken(); HighlightBuilder secondHighlightBuilder; try { secondHighlightBuilder = HighlightBuilder.fromXContent(context); } catch (RuntimeException e) { throw new RuntimeException("Error parsing " + highlightBuilder, e); } assertNotSame(highlightBuilder, secondHighlightBuilder); assertEquals(highlightBuilder, secondHighlightBuilder); assertEquals(highlightBuilder.hashCode(), secondHighlightBuilder.hashCode()); } }
public void testFromXContent() throws Exception { SliceBuilder sliceBuilder = randomSliceBuilder(); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { builder.prettyPrint(); } builder.startObject(); sliceBuilder.innerToXContent(builder); builder.endObject(); XContentParser parser = createParser(shuffleXContent(builder)); QueryParseContext context = new QueryParseContext(parser); SliceBuilder secondSliceBuilder = SliceBuilder.fromXContent(context); assertNotSame(sliceBuilder, secondSliceBuilder); assertEquals(sliceBuilder, secondSliceBuilder); assertEquals(sliceBuilder.hashCode(), secondSliceBuilder.hashCode()); }
/** * creates random rescorer, renders it to xContent and back to new instance that should be equal to original */ public void testFromXContent() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) { RescoreBuilder<?> rescoreBuilder = randomRescoreBuilder(); XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values())); if (randomBoolean()) { builder.prettyPrint(); } rescoreBuilder.toXContent(builder, ToXContent.EMPTY_PARAMS); XContentBuilder shuffled = shuffleXContent(builder); XContentParser parser = createParser(shuffled); QueryParseContext context = new QueryParseContext(parser); parser.nextToken(); RescoreBuilder<?> secondRescoreBuilder = RescoreBuilder.parseFromXContent(context); assertNotSame(rescoreBuilder, secondRescoreBuilder); assertEquals(rescoreBuilder, secondRescoreBuilder); assertEquals(rescoreBuilder.hashCode(), secondRescoreBuilder.hashCode()); } }
public InnerHitsSubSearchContext parse(QueryParseContext parserContext) throws IOException, QueryParsingException { String fieldName = null; XContentParser.Token token; String innerHitName = null; SubSearchContext subSearchContext = new SubSearchContext(SearchContext.current()); try { XContentParser parser = parserContext.parser(); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { fieldName = parser.currentName(); } else if (token.isValue()) { if ("name".equals(fieldName)) { innerHitName = parser.textOrNull(); } else { parseCommonInnerHitOptions(parser, token, fieldName, subSearchContext, sortParseElement, sourceParseElement, highlighterParseElement, scriptFieldsParseElement, fieldDataFieldsParseElement); } } else { parseCommonInnerHitOptions(parser, token, fieldName, subSearchContext, sortParseElement, sourceParseElement, highlighterParseElement, scriptFieldsParseElement, fieldDataFieldsParseElement); } } } catch (Exception e) { throw new QueryParsingException(parserContext, "Failed to parse [_inner_hits]", e); } return new InnerHitsSubSearchContext(innerHitName, subSearchContext); }
public void testFailWithSubAgg() throws Exception { String source = "{\n" + " \"top-tags\": {\n" + " \"terms\": {\n" + " \"field\": \"tags\"\n" + " },\n" + " \"aggs\": {\n" + " \"top_tags_hits\": {\n" + " \"top_hits\": {},\n" + " \"aggs\": {\n" + " \"max\": {\n" + " \"max\": {\n" + " \"field\": \"age\"\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; XContentParser parser = createParser(JsonXContent.jsonXContent, source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(AggregationInitializationException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Aggregator [top_tags_hits] of type [top_hits] cannot accept sub-aggregations")); }
public void testTwoAggs() throws Exception { assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled", XContent.isStrictDuplicateDetectionEnabled()); XContentBuilder source = JsonXContent.contentBuilder() .startObject() .startObject("by_date") .startObject("date_histogram") .field("field", "timestamp") .field("interval", "month") .endObject() .startObject("aggs") .startObject("tag_count") .startObject("cardinality") .field("field", "tag") .endObject() .endObject() .endObject() .startObject("aggs") // 2nd "aggs": illegal .startObject("tag_count2") .startObject("cardinality") .field("field", "tag") .endObject() .endObject() .endObject() .endObject() .endObject(); XContentParser parser = createParser(source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(ParsingException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Found two sub aggregation definitions under [by_date]")); }
public void testParseJson_simple() throws IOException { String scriptSort = "{\n" + "\"_script\" : {\n" + "\"type\" : \"number\",\n" + "\"script\" : \"doc['field_name'].value\",\n" + "\"mode\" : \"max\",\n" + "\"order\" : \"asc\"\n" + "} }\n"; XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort); parser.nextToken(); parser.nextToken(); parser.nextToken(); QueryParseContext context = new QueryParseContext(parser); ScriptSortBuilder builder = ScriptSortBuilder.fromXContent(context, null); assertEquals("doc['field_name'].value", builder.script().getIdOrCode()); assertEquals(Script.DEFAULT_SCRIPT_LANG, builder.script().getLang()); assertEquals(builder.script().getParams(), Collections.emptyMap()); assertEquals(ScriptType.INLINE, builder.script().getType()); assertEquals(ScriptSortType.NUMBER, builder.type()); assertEquals(SortOrder.ASC, builder.order()); assertEquals(SortMode.MAX, builder.sortMode()); assertNull(builder.getNestedFilter()); assertNull(builder.getNestedPath()); }
public void testMissingType() throws Exception { XContentBuilder source = JsonXContent.contentBuilder() .startObject() .startObject("by_date") .startObject("date_histogram") .field("field", "timestamp") .field("interval", "month") .endObject() .startObject("aggs") .startObject("tag_count") // the aggregation type is missing //.startObject("cardinality") .field("field", "tag") //.endObject() .endObject() .endObject() .endObject() .endObject(); XContentParser parser = createParser(source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(ParsingException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Expected [START_OBJECT] under [field], but got a [VALUE_STRING] in [tag_count]")); }
public void testMissingName() throws Exception { XContentBuilder source = JsonXContent.contentBuilder() .startObject() .startObject("by_date") .startObject("date_histogram") .field("field", "timestamp") .field("interval", "month") .endObject() .startObject("aggs") // the aggregation name is missing //.startObject("tag_count") .startObject("cardinality") .field("field", "tag") .endObject() //.endObject() .endObject() .endObject() .endObject(); XContentParser parser = createParser(source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(ParsingException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Expected [START_OBJECT] under [field], but got a [VALUE_STRING] in [cardinality]")); }
public void testSameAggregationName() throws Exception { assumeFalse("Test only makes sense if XContent parser doesn't have strict duplicate checks enabled", XContent.isStrictDuplicateDetectionEnabled()); final String name = randomAsciiOfLengthBetween(1, 10); XContentBuilder source = JsonXContent.contentBuilder() .startObject() .startObject(name) .startObject("terms") .field("field", "a") .endObject() .endObject() .startObject(name) .startObject("terms") .field("field", "b") .endObject() .endObject() .endObject(); XContentParser parser = createParser(source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(ParsingException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Two sibling aggregations cannot have the same name: [" + name + "]")); }
private static InternalOrder parseOrder(XContentParser parser, QueryParseContext context) throws IOException { InternalOrder order = null; Token token; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_STRING) { String dir = parser.text(); boolean asc = "asc".equals(dir); if (!asc && !"desc".equals(dir)) { throw new ParsingException(parser.getTokenLocation(), "Unknown order direction: [" + dir + "]. Should be either [asc] or [desc]"); } order = resolveOrder(currentFieldName, asc); } } return order; }
public void testSortModeSumIsRejectedInJSON() throws IOException { String json = "{\n" + " \"testname\" : [ {\n" + " \"lat\" : -6.046997540714173,\n" + " \"lon\" : -51.94128329747579\n" + " } ],\n" + " \"unit\" : \"m\",\n" + " \"distance_type\" : \"arc\",\n" + " \"mode\" : \"SUM\"\n" + "}"; XContentParser itemParser = createParser(JsonXContent.jsonXContent, json); itemParser.nextToken(); QueryParseContext context = new QueryParseContext(itemParser); IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> GeoDistanceSortBuilder.fromXContent(context, "")); assertEquals("sort_mode [sum] isn't supported for sorting by geo distance", e.getMessage()); }
public static StoredFieldsContext fromXContent(String fieldName, QueryParseContext context) throws IOException { XContentParser parser = context.parser(); XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_STRING) { return fromList(Collections.singletonList(parser.text())); } else if (token == XContentParser.Token.START_ARRAY) { ArrayList<String> list = new ArrayList<>(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { list.add(parser.text()); } return fromList(list); } else { throw new ParsingException(parser.getTokenLocation(), "Expected [" + XContentParser.Token.VALUE_STRING + "] or [" + XContentParser.Token.START_ARRAY + "] in [" + fieldName + "] but found [" + token + "]", parser.getTokenLocation()); } }
private static void parseCompoundSortField(QueryParseContext context, List<SortBuilder<?>> sortFields) throws IOException { XContentParser.Token token; XContentParser parser = context.parser(); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { String fieldName = parser.currentName(); token = parser.nextToken(); if (token == XContentParser.Token.VALUE_STRING) { SortOrder order = SortOrder.fromString(parser.text()); sortFields.add(fieldOrScoreSort(fieldName).order(order)); } else { if (PARSERS.containsKey(fieldName)) { sortFields.add(PARSERS.get(fieldName).fromXContent(context, fieldName)); } else { sortFields.add(FieldSortBuilder.fromXContent(context, fieldName)); } } } } }
public void testTwoTypes() throws Exception { XContentBuilder source = JsonXContent.contentBuilder() .startObject() .startObject("in_stock") .startObject("filter") .startObject("range") .startObject("stock") .field("gt", 0) .endObject() .endObject() .endObject() .startObject("terms") .field("field", "stock") .endObject() .endObject() .endObject(); XContentParser parser = createParser(source); QueryParseContext parseContext = new QueryParseContext(parser); assertSame(XContentParser.Token.START_OBJECT, parser.nextToken()); Exception e = expectThrows(ParsingException.class, () -> AggregatorFactories.parseAggregators(parseContext)); assertThat(e.toString(), containsString("Found two aggregation type definitions in [in_stock]: [filter] and [terms]")); }
private AbstractDistanceScoreFunction parseVariable(String fieldName, XContentParser parser, QueryParseContext parseContext, MultiValueMode mode) throws IOException { // now, the field must exist, else we cannot read the value for // the doc later MappedFieldType fieldType = parseContext.fieldMapper(fieldName); if (fieldType == null) { throw new QueryParsingException(parseContext, "unknown field [{}]", fieldName); } // dates and time need special handling parser.nextToken(); if (fieldType instanceof DateFieldMapper.DateFieldType) { return parseDateVariable(fieldName, parser, parseContext, (DateFieldMapper.DateFieldType) fieldType, mode); } else if (fieldType instanceof GeoPointFieldMapper.GeoPointFieldType) { return parseGeoVariable(fieldName, parser, parseContext, (GeoPointFieldMapper.GeoPointFieldType) fieldType, mode); } else if (fieldType instanceof NumberFieldMapper.NumberFieldType) { return parseNumberVariable(fieldName, parser, parseContext, (NumberFieldMapper.NumberFieldType) fieldType, mode); } else { throw new QueryParsingException(parseContext, "field [{}] is of type [{}], but only numeric types are supported.", fieldName, fieldType); } }
public static ScriptScoreFunctionBuilder fromXContent(QueryParseContext parseContext) throws IOException, ParsingException { XContentParser parser = parseContext.parser(); Script script = null; String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else { if (Script.SCRIPT_PARSE_FIELD.match(currentFieldName)) { script = Script.parse(parser); } else { throw new ParsingException(parser.getTokenLocation(), NAME + " query does not support [" + currentFieldName + "]"); } } } if (script == null) { throw new ParsingException(parser.getTokenLocation(), NAME + " requires 'script' field"); } return new ScriptScoreFunctionBuilder(script); }
private InnerHitsContext.ParentChildInnerHits parseParentChild(XContentParser parser, QueryParseContext parseContext, SearchContext searchContext, String type) throws Exception { ParseResult parseResult = parseSubSearchContext(searchContext, parseContext, parser); DocumentMapper documentMapper = searchContext.mapperService().documentMapper(type); if (documentMapper == null) { throw new IllegalArgumentException("type [" + type + "] doesn't exist"); } return new InnerHitsContext.ParentChildInnerHits(parseResult.context(), parseResult.query(), parseResult.childInnerHits(), parseContext.mapperService(), documentMapper); }
private void assertQueryBuilder(BytesRef actual, QueryBuilder expected) throws IOException { XContentParser sourceParser = createParser(PercolatorFieldMapper.QUERY_BUILDER_CONTENT_TYPE.xContent(), new BytesArray(actual)); QueryParseContext qsc = indexService.newQueryShardContext( randomInt(20), null, () -> { throw new UnsupportedOperationException(); }) .newParseContext(sourceParser); assertThat(qsc.parseInnerQueryBuilder(), equalTo(expected)); }
public static TestDeprecatedQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, ParsingException { XContentParser parser = parseContext.parser(); if (parser.nextToken() != XContentParser.Token.END_OBJECT) { throw new ParsingException(parser.getTokenLocation(), "[{}] query does not have any fields", NAME); } return new TestDeprecatedQueryBuilder(); }
/** * test parsing order parameter if specified as `order` field in the json * instead of the `reverse` field that we render in toXContent */ public void testParseOrder() throws IOException { SortOrder order = randomBoolean() ? SortOrder.ASC : SortOrder.DESC; String scoreSortString = "{ \"_score\": { \"order\": \""+ order.toString() +"\" }}"; XContentParser parser = createParser(JsonXContent.jsonXContent, scoreSortString); // need to skip until parser is located on second START_OBJECT parser.nextToken(); parser.nextToken(); parser.nextToken(); QueryParseContext context = new QueryParseContext(parser); ScoreSortBuilder scoreSort = ScoreSortBuilder.fromXContent(context, "_score"); assertEquals(order, scoreSort.order()); }
public void testParseBadFieldNameExceptions() throws IOException { String scriptSort = "{\"_script\" : {" + "\"bad_field\" : \"number\"" + "} }"; XContentParser parser = createParser(JsonXContent.jsonXContent, scriptSort); parser.nextToken(); parser.nextToken(); parser.nextToken(); QueryParseContext context = new QueryParseContext(parser); Exception e = expectThrows(IllegalArgumentException.class, () -> ScriptSortBuilder.fromXContent(context, null)); assertEquals("[_script] unknown field [bad_field], parser not found", e.getMessage()); }
public static RandomScoreFunctionBuilder fromXContent(QueryParseContext parseContext) throws IOException, ParsingException { RandomScoreFunctionBuilder builder = RandomScoreFunctionBuilder.fromXContent(parseContext); RandomScoreFunctionBuilderWithFixedSeed replacement = new RandomScoreFunctionBuilderWithFixedSeed(); if (builder.getSeed() != null) { replacement.seed(builder.getSeed()); } return replacement; }
public Query prefixQuery(String value, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) { PrefixQuery query = new PrefixQuery(createTerm(value)); if (method != null) { query.setRewriteMethod(method); } return query; }
public void testParseErrorOnNonIntPrecision() throws Exception { XContentParser stParser = createParser(JsonXContent.jsonXContent, "{\"field\":\"my_loc\", \"precision\":\"2.0\"}"); QueryParseContext parseContext = new QueryParseContext(stParser); XContentParser.Token token = stParser.nextToken(); assertSame(XContentParser.Token.START_OBJECT, token); try { GeoGridAggregationBuilder.parse("geohash_grid", parseContext); fail(); } catch (ParsingException ex) { assertThat(ex.getCause(), instanceOf(NumberFormatException.class)); assertEquals("For input string: \"2.0\"", ex.getCause().getMessage()); } }
private void parseToken(String aggregationName, XContentParser parser, QueryParseContext context, String currentFieldName, XContentParser.Token currentToken, Map<String, Object> params) throws IOException { if (token(parser, context, currentFieldName, currentToken, params) == false) { throw new ParsingException(parser.getTokenLocation(), "Unexpected token " + currentToken + " [" + currentFieldName + "] in [" + aggregationName + "]"); } }
private AbstractDistanceScoreFunction parseGeoVariable(String fieldName, XContentParser parser, QueryParseContext parseContext, GeoPointFieldMapper.GeoPointFieldType fieldType, MultiValueMode mode) throws IOException { XContentParser.Token token; String parameterName = null; GeoPoint origin = new GeoPoint(); String scaleString = null; String offsetString = "0km"; double decay = 0.5; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { parameterName = parser.currentName(); } else if (parameterName.equals(DecayFunctionBuilder.SCALE)) { scaleString = parser.text(); } else if (parameterName.equals(DecayFunctionBuilder.ORIGIN)) { origin = GeoUtils.parseGeoPoint(parser); } else if (parameterName.equals(DecayFunctionBuilder.DECAY)) { decay = parser.doubleValue(); } else if (parameterName.equals(DecayFunctionBuilder.OFFSET)) { offsetString = parser.text(); } else { throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName); } } if (origin == null || scaleString == null) { throw new ElasticsearchParseException("[{}] and [{}] must be set for geo fields.", DecayFunctionBuilder.ORIGIN, DecayFunctionBuilder.SCALE); } double scale = DistanceUnit.DEFAULT.parse(scaleString, DistanceUnit.DEFAULT); double offset = DistanceUnit.DEFAULT.parse(offsetString, DistanceUnit.DEFAULT); IndexGeoPointFieldData indexFieldData = parseContext.getForField(fieldType); return new GeoFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), indexFieldData, mode); }
public void testParseErrorOnBooleanPrecision() throws Exception { XContentParser stParser = createParser(JsonXContent.jsonXContent, "{\"field\":\"my_loc\", \"precision\":false}"); QueryParseContext parseContext = new QueryParseContext(stParser); XContentParser.Token token = stParser.nextToken(); assertSame(XContentParser.Token.START_OBJECT, token); try { GeoGridAggregationBuilder.parse("geohash_grid", parseContext); fail(); } catch (IllegalArgumentException ex) { assertEquals("[geohash_grid] precision doesn't support values of type: VALUE_BOOLEAN", ex.getMessage()); } }
/** * This termQuery impl looks at the context to determine the index that * is being queried and then returns a MATCH_ALL_QUERY or MATCH_NO_QUERY * if the value matches this index. This can be useful if aliases or * wildcards are used but the aim is to restrict the query to specific * indices */ @Override public Query termQuery(Object value, @Nullable QueryParseContext context) { if (context == null) { return super.termQuery(value, context); } if (isSameIndex(value, context.index().getName())) { return Queries.newMatchAllQuery(); } else { return Queries.newMatchNoDocsQuery(); } }
private static Range parseRange(XContentParser parser, QueryParseContext context) throws IOException { String fromAsStr = null; String toAsStr = null; double from = 0.0; double to = Double.POSITIVE_INFINITY; String key = null; String toOrFromOrKey = null; Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { toOrFromOrKey = parser.currentName(); } else if (token == XContentParser.Token.VALUE_NUMBER) { if (Range.FROM_FIELD.match(toOrFromOrKey)) { from = parser.doubleValue(); } else if (Range.TO_FIELD.match(toOrFromOrKey)) { to = parser.doubleValue(); } } else if (token == XContentParser.Token.VALUE_STRING) { if (Range.KEY_FIELD.match(toOrFromOrKey)) { key = parser.text(); } else if (Range.FROM_FIELD.match(toOrFromOrKey)) { fromAsStr = parser.text(); } else if (Range.TO_FIELD.match(toOrFromOrKey)) { toAsStr = parser.text(); } } } if (fromAsStr != null || toAsStr != null) { return new Range(key, Double.parseDouble(fromAsStr), Double.parseDouble(toAsStr)); } else { return new Range(key, from, to); } }
private void assertParseSearchSource(SearchSourceBuilder testBuilder, XContentParser parser) throws IOException { QueryParseContext parseContext = new QueryParseContext(parser); if (randomBoolean()) { parser.nextToken(); // sometimes we move it on the START_OBJECT to // test the embedded case } SearchSourceBuilder newBuilder = SearchSourceBuilder.fromXContent(parseContext); assertNull(parser.nextToken()); assertEquals(testBuilder, newBuilder); assertEquals(testBuilder.hashCode(), newBuilder.hashCode()); }
public static IncludeExclude parseExclude(XContentParser parser, QueryParseContext context) throws IOException { XContentParser.Token token = parser.currentToken(); if (token == XContentParser.Token.VALUE_STRING) { return new IncludeExclude(null, parser.text()); } else if (token == XContentParser.Token.START_ARRAY) { return new IncludeExclude(null, new TreeSet<>(parseArrayToSet(parser))); } else { throw new IllegalArgumentException("Unrecognized token for an exclude [" + token + "]"); } }
private static Terms.Order parseOrderParam(XContentParser parser, QueryParseContext context) throws IOException { XContentParser.Token token; Terms.Order orderParam = null; String orderKey = null; boolean orderAsc = false; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { orderKey = parser.currentName(); } else if (token == XContentParser.Token.VALUE_STRING) { String dir = parser.text(); if ("asc".equalsIgnoreCase(dir)) { orderAsc = true; } else if ("desc".equalsIgnoreCase(dir)) { orderAsc = false; } else { throw new ParsingException(parser.getTokenLocation(), "Unknown terms order direction [" + dir + "]"); } } else { throw new ParsingException(parser.getTokenLocation(), "Unexpected token " + token + " for [order]"); } } if (orderKey == null) { throw new ParsingException(parser.getTokenLocation(), "Must specify at least one field for [order]"); } else { orderParam = resolveOrder(orderKey, orderAsc); } return orderParam; }
public static SamplerAggregationBuilder parse(String aggregationName, QueryParseContext context) throws IOException { XContentParser.Token token; String currentFieldName = null; Integer shardSize = null; XContentParser parser = context.parser(); while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_NUMBER) { if (SamplerAggregator.SHARD_SIZE_FIELD.match(currentFieldName)) { shardSize = parser.intValue(); } else { throw new ParsingException(parser.getTokenLocation(), "Unsupported property \"" + currentFieldName + "\" for aggregation \"" + aggregationName); } } else { throw new ParsingException(parser.getTokenLocation(), "Unsupported property \"" + currentFieldName + "\" for aggregation \"" + aggregationName); } } SamplerAggregationBuilder factory = new SamplerAggregationBuilder(aggregationName); if (shardSize != null) { factory.shardSize(shardSize); } return factory; }
@Override public Query termQuery(Object value, @Nullable QueryParseContext context) { if (indexOptions() == IndexOptions.NONE) { return new ConstantScoreQuery(new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.typePrefixAsBytes(BytesRefs.toBytesRef(value))))); } return new ConstantScoreQuery(new TermQuery(createTerm(value))); }
public InnerQuery(QueryParseContext parseContext1, @Nullable String... types) throws IOException { super(parseContext1); if (types != null) { String[] origTypes = QueryParseContext.setTypesWithPrevious(types); try { query = parseContext1.parseInnerQuery(); queryParsed = true; } finally { QueryParseContext.setTypes(origTypes); } } else { BytesReference innerBytes = XContentFactory.smileBuilder().copyCurrentStructure(parseContext1.parser()).bytes(); super.bytes(innerBytes); } }
/** * create a new parser from the rescorer string representation and reset context with it */ private QueryParseContext createContext(String rescoreElement) throws IOException { XContentParser parser = createParser(JsonXContent.jsonXContent, rescoreElement); QueryParseContext context = new QueryParseContext(parser); // move to first token, this is where the internal fromXContent assertTrue(parser.nextToken() == XContentParser.Token.START_OBJECT); return context; }
protected void checkParseException(ParseFieldRegistry<SignificanceHeuristicParser> significanceHeuristicParserRegistry, String faultyHeuristicDefinition, String expectedError) throws IOException { try { XContentParser stParser = createParser(JsonXContent.jsonXContent, "{\"field\":\"text\", " + faultyHeuristicDefinition + ",\"min_doc_count\":200}"); QueryParseContext parseContext = new QueryParseContext(stParser); stParser.nextToken(); SignificantTermsAggregationBuilder.getParser(significanceHeuristicParserRegistry).parse("testagg", parseContext); fail(); } catch (ParsingException e) { assertThat(e.getCause().getMessage(), containsString(expectedError)); } }
private Query parseQuery(String type, XContentParser parser) { String[] previousTypes = null; if (type != null) { QueryParseContext.setTypesWithPrevious(new String[]{type}); } QueryParseContext context = queryParserService.getParseContext(); try { context.reset(parser); // This means that fields in the query need to exist in the mapping prior to registering this query // The reason that this is required, is that if a field doesn't exist then the query assumes defaults, which may be undesired. // // Even worse when fields mentioned in percolator queries do go added to map after the queries have been registered // then the percolator queries don't work as expected any more. // // Query parsing can't introduce new fields in mappings (which happens when registering a percolator query), // because field type can't be inferred from queries (like document do) so the best option here is to disallow // the usage of unmapped fields in percolator queries to avoid unexpected behaviour // // if index.percolator.map_unmapped_fields_as_string is set to true, query can contain unmapped fields which will be mapped // as an analyzed string. context.setAllowUnmappedFields(false); context.setMapUnmappedFieldAsString(mapUnmappedFieldsAsString ? true : false); return queryParserService.parseInnerQuery(context); } catch (IOException e) { throw new QueryParsingException(context, "Failed to parse", e); } finally { if (type != null) { QueryParseContext.setTypes(previousTypes); } context.reset(null); } }
@Override public void parse(XContentParser parser, SearchContext searchContext) throws Exception { QueryParseContext context = searchContext.queryParserService().getParseContext(); context.reset(parser); Map<String, InnerHitsContext.BaseInnerHits> topLevelInnerHits = parseInnerHits(parser, context, searchContext); if (topLevelInnerHits != null) { InnerHitsContext innerHitsContext = searchContext.innerHits(); innerHitsContext.addInnerHitDefinitions(topLevelInnerHits); } }