Java Code Examples for org.elasticsearch.common.xcontent.XContentParser#nextToken()

The following examples show how to use org.elasticsearch.common.xcontent.XContentParser#nextToken() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ContentBuilderUtil.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
public static void addComplexField(XContentBuilder builder, String fieldName,
    XContentType contentType, byte[] data) throws IOException {
  XContentParser parser = null;
  try {
    XContentBuilder tmp = jsonBuilder();
    parser = XContentFactory.xContent(contentType).createParser(data);
    parser.nextToken();
    tmp.copyCurrentStructure(parser);
    builder.field(fieldName, tmp);
  } catch (JsonParseException ex) {
    // If we get an exception here the most likely cause is nested JSON that
    // can't be figured out in the body. At this point just push it through
    // as is, we have already added the field so don't do it again
    addSimpleField(builder, fieldName, data);
  } finally {
    if (parser != null) {
      parser.close();
    }
  }
}
 
Example 2
Source File: SQLArgsParseElement.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
protected Object[] parseSubArray(SQLXContentSourceContext context, XContentParser parser)
    throws IOException
{
    XContentParser.Token token;
    List<Object> subList = new ArrayList<Object>();

    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
        if (token.isValue()) {
            subList.add(parser.objectText());
        } else if (token == XContentParser.Token.START_ARRAY) {
            subList.add(parseSubArray(context, parser));
        } else if (token == XContentParser.Token.START_OBJECT) {
            subList.add(parser.map());
        } else if (token == XContentParser.Token.VALUE_NULL) {
            subList.add(null);
        } else {
            throw new SQLParseSourceException(context, "Field [" + parser.currentName() + "] has an invalid value");
        }
    }

    return subList.toArray(new Object[subList.size()]);
}
 
Example 3
Source File: JobEvent.java    From elasticsearch-gatherer with Apache License 2.0 6 votes vote down vote up
public JobEvent fromXContent(XContentParser parser) throws IOException {
    //DateMathParser dateParser = new DateMathParser(Joda.forPattern("dateOptionalTime"), TimeUnit.MILLISECONDS);
    Long startTimestamp = null;
    String currentFieldName = null;
    Token token;
    while ((token = parser.nextToken()) != END_OBJECT) {
        if (token == FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token.isValue() || token == VALUE_NULL) {
            if ("started".equals(currentFieldName)) {
                startTimestamp =  Long.parseLong(parser.text());
            }
        } else if (token == START_ARRAY) {
            List<String> values = newArrayList();
            while ((parser.nextToken()) != END_ARRAY) {
                values.add(parser.text());
            }
        }
    }
    return new JobEvent().timestamp(startTimestamp);
}
 
Example 4
Source File: DocumentParser.java    From crate with Apache License 2.0 6 votes vote down vote up
private static void parseNonDynamicArray(ParseContext context, ObjectMapper mapper, String lastFieldName, String arrayFieldName) throws IOException {
    XContentParser parser = context.parser();
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
        if (token == XContentParser.Token.START_OBJECT) {
            parseObject(context, mapper, lastFieldName);
        } else if (token == XContentParser.Token.START_ARRAY) {
            parseArray(context, mapper, lastFieldName);
        } else if (token == XContentParser.Token.FIELD_NAME) {
            lastFieldName = parser.currentName();
        } else if (token == XContentParser.Token.VALUE_NULL) {
            parseNullValue(context, mapper, lastFieldName);
        } else if (token == null) {
            throw new MapperParsingException("object mapping for [" + mapper.name() + "] with array for [" + arrayFieldName + "] tried to parse as array, but got EOF, is there a mismatch in types for the same field?");
        } else {
            parseValue(context, mapper, lastFieldName, token);
        }
    }
}
 
Example 5
Source File: SQLXContentSourceParser.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public void parse(XContentParser parser) throws Exception {
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            String fieldName = parser.currentName();
            parser.nextToken();
            SQLParseElement element = elementParsers.get(fieldName);
            if (element == null) {
                throw new SQLParseException("No parser for element [" + fieldName + "]");
            }
            element.parse(parser, context);
        } else if (token == null) {
            break;
        }
    }
}
 
Example 6
Source File: DecayFunctionParser.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
 
Example 7
Source File: XGBoostJsonParser.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
public static XGBoostDefinition parse(XContentParser parser, FeatureSet set) throws IOException {
    XGBoostDefinition definition;
    XContentParser.Token startToken = parser.nextToken();

    // The model definition can either be an array of tree definitions, or an object containing the
    // tree definitions in the 'splits' field. Using an object allows for specification of additional
    // parameters.
    if (startToken == XContentParser.Token.START_OBJECT) {
        try {
            definition = PARSER.apply(parser, set);
        } catch (XContentParseException e) {
            throw new ParsingException(parser.getTokenLocation(), "Unable to parse XGBoost object", e);
        }
        if (definition.splitParserStates == null) {
            throw new ParsingException(parser.getTokenLocation(), "XGBoost model missing required field [splits]");
        }
    } else if (startToken == XContentParser.Token.START_ARRAY) {
        definition = new XGBoostDefinition();
        definition.splitParserStates = new ArrayList<>();
        while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
            definition.splitParserStates.add(SplitParserState.parse(parser, set));
        }
    } else {
        throw new ParsingException(parser.getTokenLocation(), "Expected [START_ARRAY] or [START_OBJECT] but got ["
                + startToken + "]");
    }
    if (definition.splitParserStates.size() == 0) {
        throw new ParsingException(parser.getTokenLocation(), "XGBoost model must define at lease one tree");
    }
    return definition;
}
 
Example 8
Source File: AliasMetaData.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static AliasMetaData fromXContent(XContentParser parser) throws IOException {
    Builder builder = new Builder(parser.currentName());

    String currentFieldName = null;
    XContentParser.Token token = parser.nextToken();
    if (token == null) {
        // no data...
        return builder.build();
    }
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.START_OBJECT) {
            if ("filter".equals(currentFieldName)) {
                Map<String, Object> filter = parser.mapOrdered();
                builder.filter(filter);
            }
        } else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) {
            if ("filter".equals(currentFieldName)) {
                builder.filter(new CompressedXContent(parser.binaryValue()));
            }
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if ("routing".equals(currentFieldName)) {
                builder.routing(parser.text());
            } else if ("index_routing".equals(currentFieldName) || "indexRouting".equals(currentFieldName)) {
                builder.indexRouting(parser.text());
            } else if ("search_routing".equals(currentFieldName) || "searchRouting".equals(currentFieldName)) {
                builder.searchRouting(parser.text());
            }
        }
    }
    return builder.build();
}
 
Example 9
Source File: ParseUtilsTests.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public void testToInstantWithNullValue() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder().value(randomLong());
    XContentParser parser = this.createParser(builder);
    parser.nextToken();
    parser.nextToken();
    XContentParser.Token token = parser.currentToken();
    assertNull(token);
    Instant instant = ParseUtils.toInstant(parser);
    assertNull(instant);
}
 
Example 10
Source File: GetIndexTemplatesResponse.java    From crate with Apache License 2.0 5 votes vote down vote up
public static GetIndexTemplatesResponse fromXContent(XContentParser parser) throws IOException {
    final List<IndexTemplateMetaData> templates = new ArrayList<>();
    for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) {
        if (token == XContentParser.Token.FIELD_NAME) {
            final IndexTemplateMetaData templateMetaData = IndexTemplateMetaData.Builder.fromXContent(parser, parser.currentName());
            templates.add(templateMetaData);
        }
    }
    return new GetIndexTemplatesResponse(templates);
}
 
Example 11
Source File: AccountRestAction.java    From elasticsearch-auth with Apache License 2.0 5 votes vote down vote up
@Override
protected void handleRequest(final RestRequest request,
        final RestChannel channel, final Client client) {
    final BytesReference content = request.content();
    final XContentType xContentType = XContentFactory.xContentType(content);
    XContentParser parser = null;
    String authenticator = null;
    String username = null;
    String password = null;
    String[] roles = null;
    try {
        parser = XContentFactory.xContent(xContentType).createParser(
                content);
        final XContentParser.Token t = parser.nextToken();
        if (t != null) {
            final Map<String, Object> contentMap = parser.map();
            authenticator = MapUtil.getAsString(contentMap,
                    "authenticator", null);
            username = MapUtil.getAsString(contentMap, "username", null);
            password = MapUtil.getAsString(contentMap, "password", null);
            roles = MapUtil.getAsArray(contentMap, "roles", new String[0]);
        }
    } catch (final Exception e) {
        logger.error("Could not parse the content.", e);
        ResponseUtil.send(request, channel, RestStatus.BAD_REQUEST,
                "message", "Could not parse the content.");
        return;
    } finally {
        if (parser != null) {
            parser.close();
        }
    }

    processRequest(request, channel, authenticator, username, password,
            roles);

}
 
Example 12
Source File: ArrayMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    /**
     * array mapping should look like:
     *
     * "fieldName": {
     *      "type": "array":
     *      "inner": {
     *          "type": "string"
     *          ...
     *      }
     * }
     *
     *
     * Use the innerMapper to generate the mapping for the inner type which will look like:
     *
     * "fieldName": {
     *      "type": "string",
     *      ...
     * }
     *
     * and then parse the contents of the object to set it into the "inner" field of the outer array type.
     */
    XContentBuilder innerBuilder = new XContentBuilder(builder.contentType().xContent(), new BytesStreamOutput(0));
    innerBuilder = innerMapper.toXContent(innerBuilder, params);
    innerBuilder.close();
    XContentParser parser = builder.contentType().xContent().createParser(innerBuilder.bytes());

    //noinspection StatementWithEmptyBody
    while ((parser.nextToken() != XContentParser.Token.START_OBJECT)) {
        // consume tokens until start of object
    }
    Map<String, Object> innerMap = parser.mapOrdered();

    builder.startObject(simpleName());
    builder.field("type", contentType());
    builder.field(INNER, innerMap);
    return builder.endObject();
}
 
Example 13
Source File: ReplicationResponse.java    From crate with Apache License 2.0 5 votes vote down vote up
public static Failure fromXContent(XContentParser parser) throws IOException {
    XContentParser.Token token = parser.currentToken();
    ensureExpectedToken(XContentParser.Token.START_OBJECT, token, parser::getTokenLocation);

    String shardIndex = null, nodeId = null;
    int shardId = -1;
    boolean primary = false;
    RestStatus status = null;
    ElasticsearchException reason = null;

    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token.isValue()) {
            if (INDEX.equals(currentFieldName)) {
                shardIndex = parser.text();
            } else if (SHARD.equals(currentFieldName)) {
                shardId = parser.intValue();
            } else if (NODE.equals(currentFieldName)) {
                nodeId = parser.text();
            } else if (STATUS.equals(currentFieldName)) {
                status = RestStatus.valueOf(parser.text());
            } else if (PRIMARY.equals(currentFieldName)) {
                primary = parser.booleanValue();
            }
        } else if (token == XContentParser.Token.START_OBJECT) {
            if (REASON.equals(currentFieldName)) {
                reason = ElasticsearchException.fromXContent(parser);
            } else {
                parser.skipChildren(); // skip potential inner objects for forward compatibility
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            parser.skipChildren(); // skip potential inner arrays for forward compatibility
        }
    }
    return new Failure(new ShardId(shardIndex, IndexMetaData.INDEX_UUID_NA_VALUE, shardId), nodeId, reason, status, primary);
}
 
Example 14
Source File: GeoBoundsParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {
    ValuesSourceParser<GeoPoint> vsParser = ValuesSourceParser.geoPoint(aggregationName, InternalGeoBounds.TYPE, context)
            .targetValueType(ValueType.GEOPOINT)
            .formattable(true)
            .build();
    boolean wrapLongitude = true;
    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (vsParser.token(currentFieldName, token, parser)) {
            continue;
            
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if ("wrap_longitude".equals(currentFieldName) || "wrapLongitude".equals(currentFieldName)) {
                wrapLongitude = parser.booleanValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in aggregation [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unknown key for a " + token + " in aggregation [" + aggregationName + "]: ["
                    + currentFieldName + "].", parser.getTokenLocation());
        }
    }
    return new GeoBoundsAggregator.Factory(aggregationName, vsParser.config(), wrapLongitude);
}
 
Example 15
Source File: BlobStoreIndexShardSnapshot.java    From crate with Apache License 2.0 4 votes vote down vote up
/**
 * Parses shard snapshot metadata
 *
 * @param parser parser
 * @return shard snapshot metadata
 */
public static BlobStoreIndexShardSnapshot fromXContent(XContentParser parser) throws IOException {
    String snapshot = null;
    long indexVersion = -1;
    long startTime = 0;
    long time = 0;
    int incrementalFileCount = 0;
    long incrementalSize = 0;

    List<FileInfo> indexFiles = new ArrayList<>();
    if (parser.currentToken() == null) { // fresh parser? move to the first token
        parser.nextToken();
    }
    XContentParser.Token token = parser.currentToken();
    if (token == XContentParser.Token.START_OBJECT) {
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                String currentFieldName = parser.currentName();
                token = parser.nextToken();
                if (token.isValue()) {
                    if (PARSE_NAME.match(currentFieldName, parser.getDeprecationHandler())) {
                        snapshot = parser.text();
                    } else if (PARSE_INDEX_VERSION.match(currentFieldName, parser.getDeprecationHandler())) {
                        // The index-version is needed for backward compatibility with v 1.0
                        indexVersion = parser.longValue();
                    } else if (PARSE_START_TIME.match(currentFieldName, parser.getDeprecationHandler())) {
                        startTime = parser.longValue();
                    } else if (PARSE_TIME.match(currentFieldName, parser.getDeprecationHandler())) {
                        time = parser.longValue();
                    } else if (PARSE_INCREMENTAL_FILE_COUNT.match(currentFieldName, parser.getDeprecationHandler())) {
                        incrementalFileCount = parser.intValue();
                    } else if (PARSE_INCREMENTAL_SIZE.match(currentFieldName, parser.getDeprecationHandler())) {
                        incrementalSize = parser.longValue();
                    } else {
                        throw new ElasticsearchParseException("unknown parameter [{}]", currentFieldName);
                    }
                } else if (token == XContentParser.Token.START_ARRAY) {
                    if (PARSE_FILES.match(currentFieldName, parser.getDeprecationHandler())) {
                        while ((parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                            indexFiles.add(FileInfo.fromXContent(parser));
                        }
                    } else {
                        throw new ElasticsearchParseException("unknown parameter [{}]", currentFieldName);
                    }
                } else {
                    throw new ElasticsearchParseException("unexpected token  [{}]", token);
                }
            } else {
                throw new ElasticsearchParseException("unexpected token [{}]", token);
            }
        }
    }

    return new BlobStoreIndexShardSnapshot(snapshot, indexVersion, Collections.unmodifiableList(indexFiles),
                                           startTime, time, incrementalFileCount, incrementalSize);
}
 
Example 16
Source File: SearchService.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
private void parseSource(SearchContext context, BytesReference source) throws SearchParseException {
    // nothing to parse...
    if (source == null || source.length() == 0) {
        return;
    }
    String abc = source.toUtf8();
    XContentParser parser = null;
    try {
        parser = XContentFactory.xContent(source).createParser(source);
        XContentParser.Token token;
        token = parser.nextToken();
        if (token != XContentParser.Token.START_OBJECT) {
            throw new ElasticsearchParseException("failed to parse search source. source must be an object, but found [{}] instead", token.name());
        }
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                String fieldName = parser.currentName();
                parser.nextToken();
                SearchParseElement element = elementParsers.get(fieldName);
                if (element == null) {
                    throw new SearchParseException(context, "failed to parse search source. unknown search element [" + fieldName + "]", parser.getTokenLocation());
                }
                element.parse(parser, context);
            } else {
                if (token == null) {
                    throw new ElasticsearchParseException("failed to parse search source. end of query source reached but query is not complete.");
                } else {
                    throw new ElasticsearchParseException("failed to parse search source. expected field name but got [{}]", token);
                }
            }
        }
    } catch (Throwable e) {
        String sSource = "_na_";
        try {
            sSource = XContentHelper.convertToJson(source, false);
        } catch (Throwable e1) {
            // ignore
        }
        XContentLocation location = parser != null ? parser.getTokenLocation() : null;
        throw new SearchParseException(context, "failed to parse search source [" + sSource + "]", location, e);
    } finally {
        if (parser != null) {
            parser.close();
        }
    }
}
 
Example 17
Source File: RestoreParser.java    From elasticsearch-inout-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Main method of this class to parse given payload of _restore action
 *
 * @param context
 * @param source
 * @throws org.elasticsearch.search.SearchParseException
 */
public void parseSource(ImportContext context, BytesReference source) throws ImportParseException {
    XContentParser parser = null;
    this.setDefaults(context);
    context.settings(true);
    context.mappings(true);
    try {
        if (source != null && source.length() != 0) {
            parser = XContentFactory.xContent(source).createParser(source);
            XContentParser.Token token;
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    String fieldName = parser.currentName();
                    parser.nextToken();
                    ImportParseElement element = elementParsers.get(fieldName);
                    if (element == null) {
                        throw new ImportParseException(context, "No parser for element [" + fieldName + "]");
                    }
                    element.parse(parser, context);
                } else if (token == null) {
                    break;
                }
            }
        }
        if (context.directory() == null) {
            context.directory(DumpParser.DEFAULT_DIR);
        }
    } catch (Exception e) {
        String sSource = "_na_";
        try {
            sSource = XContentHelper.convertToJson(source, false);
        } catch (Throwable e1) {
            // ignore
        }
        throw new ImportParseException(context, "Failed to parse source [" + sSource + "]", e);
    } finally {
        if (parser != null) {
            parser.close();
        }
    }
}
 
Example 18
Source File: SortParseElement.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
private void addCompoundSortField(XContentParser parser, SearchContext context, List<SortField> sortFields) throws Exception {
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            String fieldName = parser.currentName();
            boolean reverse = false;
            String missing = null;
            String innerJsonName = null;
            String unmappedType = null;
            MultiValueMode sortMode = null;
            NestedInnerQueryParseSupport nestedFilterParseHelper = null;
            token = parser.nextToken();
            if (token == XContentParser.Token.VALUE_STRING) {
                String direction = parser.text();
                if (direction.equals("asc")) {
                    reverse = SCORE_FIELD_NAME.equals(fieldName);
                } else if (direction.equals("desc")) {
                    reverse = !SCORE_FIELD_NAME.equals(fieldName);
                } else {
                    throw new IllegalArgumentException("sort direction [" + fieldName + "] not supported");
                }
                addSortField(context, sortFields, fieldName, reverse, unmappedType, missing, sortMode, nestedFilterParseHelper);
            } else {
                if (parsers.containsKey(fieldName)) {
                    sortFields.add(parsers.get(fieldName).parse(parser, context));
                } else {
                    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                        if (token == XContentParser.Token.FIELD_NAME) {
                            innerJsonName = parser.currentName();
                        } else if (token.isValue()) {
                            if (context.parseFieldMatcher().match(innerJsonName, REVERSE_FIELD)) {
                                reverse = parser.booleanValue();
                            } else if ("order".equals(innerJsonName)) {
                                if ("asc".equals(parser.text())) {
                                    reverse = SCORE_FIELD_NAME.equals(fieldName);
                                } else if ("desc".equals(parser.text())) {
                                    reverse = !SCORE_FIELD_NAME.equals(fieldName);
                                }
                            } else if ("missing".equals(innerJsonName)) {
                                missing = parser.textOrNull();
                            } else if (context.parseFieldMatcher().match(innerJsonName, IGNORE_UNMAPPED)) {
                                // backward compatibility: ignore_unmapped has been replaced with unmapped_type
                                if (unmappedType == null // don't override if unmapped_type has been provided too
                                        && parser.booleanValue()) {
                                    unmappedType = LongFieldMapper.CONTENT_TYPE;
                                }
                            } else if (context.parseFieldMatcher().match(innerJsonName, UNMAPPED_TYPE)) {
                                unmappedType = parser.textOrNull();
                            } else if ("mode".equals(innerJsonName)) {
                                sortMode = MultiValueMode.fromString(parser.text());
                            } else if ("nested_path".equals(innerJsonName) || "nestedPath".equals(innerJsonName)) {
                                if (nestedFilterParseHelper == null) {
                                    nestedFilterParseHelper = new NestedInnerQueryParseSupport(parser, context);
                                }
                                nestedFilterParseHelper.setPath(parser.text());
                            } else {
                                throw new IllegalArgumentException("sort option [" + innerJsonName + "] not supported");
                            }
                        } else if (token == XContentParser.Token.START_OBJECT) {
                            if ("nested_filter".equals(innerJsonName) || "nestedFilter".equals(innerJsonName)) {
                                if (nestedFilterParseHelper == null) {
                                    nestedFilterParseHelper = new NestedInnerQueryParseSupport(parser, context);
                                }
                                nestedFilterParseHelper.filter();
                            } else {
                                throw new IllegalArgumentException("sort option [" + innerJsonName + "] not supported");
                            }
                        }
                    }
                    addSortField(context, sortFields, fieldName, reverse, unmappedType, missing, sortMode, nestedFilterParseHelper);
                }
            }
        }
    }
}
 
Example 19
Source File: InnerHitsQueryParserHelper.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public static void parseCommonInnerHitOptions(XContentParser parser, XContentParser.Token token, String fieldName, SubSearchContext subSearchContext,
                                              SortParseElement sortParseElement, FetchSourceParseElement sourceParseElement, HighlighterParseElement highlighterParseElement,
                                              ScriptFieldsParseElement scriptFieldsParseElement, FieldDataFieldsParseElement fieldDataFieldsParseElement) throws Exception {
    if ("sort".equals(fieldName)) {
        sortParseElement.parse(parser, subSearchContext);
    } else if ("_source".equals(fieldName)) {
        sourceParseElement.parse(parser, subSearchContext);
    } else if (token == XContentParser.Token.START_OBJECT) {
        switch (fieldName) {
            case "highlight":
                highlighterParseElement.parse(parser, subSearchContext);
                break;
            case "scriptFields":
            case "script_fields":
                scriptFieldsParseElement.parse(parser, subSearchContext);
                break;
            default:
                throw new IllegalArgumentException("Unknown key for a " + token + " for nested query: [" + fieldName + "].");
        }
    } else if (token == XContentParser.Token.START_ARRAY) {
        switch (fieldName) {
            case "fielddataFields":
            case "fielddata_fields":
                fieldDataFieldsParseElement.parse(parser, subSearchContext);
                break;
            case "fields":
                boolean added = false;
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    String name = parser.text();
                    added = true;
                    subSearchContext.fieldNames().add(name);
                }
                if (!added) {
                    subSearchContext.emptyFieldNames();
                }
                break;
            default:
                throw new IllegalArgumentException("Unknown key for a " + token + " for nested query: [" + fieldName + "].");
        }
    } else if (token.isValue()) {
        switch (fieldName) {
            case "from":
                subSearchContext.from(parser.intValue());
                break;
            case "size":
                subSearchContext.size(parser.intValue());
                break;
            case "track_scores":
            case "trackScores":
                subSearchContext.trackScores(parser.booleanValue());
                break;
            case "version":
                subSearchContext.version(parser.booleanValue());
                break;
            case "explain":
                subSearchContext.explain(parser.booleanValue());
                break;
            case "fields":
                subSearchContext.fieldNames().add(parser.text());
                break;
            default:
                throw new IllegalArgumentException("Unknown key for a " + token + " for nested query: [" + fieldName + "].");
        }
    }
}
 
Example 20
Source File: FunctionArgumentDefinition.java    From crate with Apache License 2.0 4 votes vote down vote up
private static String parseStringField(XContentParser parser) throws IOException {
    if (parser.nextToken() != XContentParser.Token.VALUE_STRING && parser.currentToken() != XContentParser.Token.VALUE_NULL) {
        throw new IllegalArgumentException("Failed to parse string field");
    }
    return parser.textOrNull();
}