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

The following examples show how to use org.elasticsearch.common.xcontent.XContentParser#intValue() . 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: GeolocationContextMapping.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private static final int parsePrecision(XContentParser parser) throws IOException, ElasticsearchParseException {
    switch (parser.currentToken()) {
    case VALUE_STRING:
        return GeoUtils.geoHashLevelsForPrecision(parser.text());
    case VALUE_NUMBER:
        switch (parser.numberType()) {
        case INT:
        case LONG:
            return parser.intValue();
        default:
            return GeoUtils.geoHashLevelsForPrecision(parser.doubleValue());
        }
    default:
        throw new ElasticsearchParseException("invalid precision value");
    }
}
 
Example 2
Source File: SnapshotShardFailure.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Deserializes snapshot failure information from JSON
 *
 * @param parser JSON parser
 * @return snapshot failure information
 */
public static SnapshotShardFailure fromXContent(XContentParser parser) throws IOException {
    SnapshotShardFailure snapshotShardFailure = new SnapshotShardFailure();

    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 ("index".equals(currentFieldName)) {
                        snapshotShardFailure.index = parser.text();
                    } else if ("node_id".equals(currentFieldName)) {
                        snapshotShardFailure.nodeId = parser.text();
                    } else if ("reason".equals(currentFieldName)) {
                        snapshotShardFailure.reason = parser.text();
                    } else if ("shard_id".equals(currentFieldName)) {
                        snapshotShardFailure.shardId = parser.intValue();
                    } else if ("status".equals(currentFieldName)) {
                        snapshotShardFailure.status = RestStatus.valueOf(parser.text());
                    } else {
                        throw new ElasticsearchParseException("unknown parameter [{}]", currentFieldName);
                    }
                }
            } else {
                throw new ElasticsearchParseException("unexpected token [{}]", token);
            }
        }
    } else {
        throw new ElasticsearchParseException("unexpected token [{}]", token);
    }
    return snapshotShardFailure;
}
 
Example 3
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 4
Source File: UserDefinedFunctionMetaData.java    From crate with Apache License 2.0 5 votes vote down vote up
public static DataType<?> fromXContent(XContentParser parser) throws IOException {
    XContentParser.Token token = parser.currentToken();
    if (token != XContentParser.Token.START_OBJECT) {
        throw new IllegalArgumentException("Expected a START_OBJECT but got " + parser.currentToken());
    }
    int id = DataTypes.NOT_SUPPORTED.id();
    DataType<?> innerType = DataTypes.UNDEFINED;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            String fieldName = parser.currentName();
            if ("id".equals(fieldName)) {
                if (parser.nextToken() != XContentParser.Token.VALUE_NUMBER) {
                    throw new IllegalArgumentException("Expected a VALUE_NUMBER but got " + parser.currentToken());
                }
                id = parser.intValue();
            } else if ("inner_type".equals(fieldName)) {
                if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
                    throw new IllegalArgumentException("Expected a START_OBJECT but got " + parser.currentToken());
                }
                innerType = fromXContent(parser);
            }
        }
    }
    if (id == ArrayType.ID) {
        return new ArrayType<>(innerType);
    }
    return DataTypes.fromId(id);
}
 
Example 5
Source File: FromParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, SearchContext context) throws Exception {
    XContentParser.Token token = parser.currentToken();
    if (token.isValue()) {
        int from = parser.intValue();
        if (from < 0) {
            throw new SearchParseException(context, "from is set to [" + from + "] and is expected to be higher or equal to 0",
                    parser.getTokenLocation());
        }
        context.from(from);
    }
}
 
Example 6
Source File: TerminateAfterParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, SearchContext context) throws Exception {
    XContentParser.Token token = parser.currentToken();
    if (token == XContentParser.Token.VALUE_NUMBER) {
        int terminateAfterCount = parser.intValue();
        if (terminateAfterCount <= 0) {
            throw new IllegalArgumentException("terminateAfter must be > 0");
        }
        context.terminateAfter(parser.intValue());
    }
}
 
Example 7
Source File: RescoreParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void parseSingleRescoreContext(XContentParser parser, SearchContext context) throws Exception {
    String fieldName = null;
    RescoreSearchContext rescoreContext = null;
    Integer windowSize = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            fieldName = parser.currentName();
            if (QueryRescorer.NAME.equals(fieldName)) {
                // we only have one at this point
                Rescorer rescorer = QueryRescorer.INSTANCE;
                token = parser.nextToken();
                if (token != XContentParser.Token.START_OBJECT) {
                    throw new ElasticsearchParseException("rescore type malformed, must start with start_object");
                }
                rescoreContext = rescorer.parse(parser, context);
            }
        } else if (token.isValue()) {
            if ("window_size".equals(fieldName)) {
                windowSize = parser.intValue();
            } else {
                throw new IllegalArgumentException("rescore doesn't support [" + fieldName + "]");
            }
        }
    }
    if (rescoreContext == null) {
        throw new IllegalArgumentException("missing rescore type");
    }
    if (windowSize != null) {
        rescoreContext.setWindowSize(windowSize.intValue());
    }
    context.addRescore(rescoreContext);
}
 
Example 8
Source File: CancelAllocationCommand.java    From crate with Apache License 2.0 5 votes vote down vote up
public static CancelAllocationCommand fromXContent(XContentParser parser) throws IOException {
    String index = null;
    int shardId = -1;
    String nodeId = null;
    boolean allowPrimary = false;

    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 (token.isValue()) {
            if ("index".equals(currentFieldName)) {
                index = parser.text();
            } else if ("shard".equals(currentFieldName)) {
                shardId = parser.intValue();
            } else if ("node".equals(currentFieldName)) {
                nodeId = parser.text();
            } else if ("allow_primary".equals(currentFieldName) || "allowPrimary".equals(currentFieldName)) {
                allowPrimary = parser.booleanValue();
            } else {
                throw new ElasticsearchParseException("[{}] command does not support field [{}]", NAME, currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException("[{}] command does not support complex json tokens [{}]", NAME, token);
        }
    }
    if (index == null) {
        throw new ElasticsearchParseException("[{}] command missing the index parameter", NAME);
    }
    if (shardId == -1) {
        throw new ElasticsearchParseException("[{}] command missing the shard parameter", NAME);
    }
    if (nodeId == null) {
        throw new ElasticsearchParseException("[{}] command missing the node parameter", NAME);
    }
    return new CancelAllocationCommand(index, shardId, nodeId, allowPrimary);
}
 
Example 9
Source File: AllocateAllocationCommand.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public AllocateAllocationCommand fromXContent(XContentParser parser) throws IOException {
    String index = null;
    int shardId = -1;
    String nodeId = null;
    boolean allowPrimary = false;

    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 (token.isValue()) {
            if ("index".equals(currentFieldName)) {
                index = parser.text();
            } else if ("shard".equals(currentFieldName)) {
                shardId = parser.intValue();
            } else if ("node".equals(currentFieldName)) {
                nodeId = parser.text();
            } else if ("allow_primary".equals(currentFieldName) || "allowPrimary".equals(currentFieldName)) {
                allowPrimary = parser.booleanValue();
            } else {
                throw new ElasticsearchParseException("[{}] command does not support field [{}]", NAME, currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException("[{}] command does not support complex json tokens [{}]", NAME, token);
        }
    }
    if (index == null) {
        throw new ElasticsearchParseException("[{}] command missing the index parameter", NAME);
    }
    if (shardId == -1) {
        throw new ElasticsearchParseException("[{}] command missing the shard parameter", NAME);
    }
    if (nodeId == null) {
        throw new ElasticsearchParseException("[{}] command missing the node parameter", NAME);
    }
    return new AllocateAllocationCommand(new ShardId(index, shardId), nodeId, allowPrimary);
}
 
Example 10
Source File: LimitQueryParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    deprecationLogger.deprecated("The [limit] query is deprecated, please use the [terminate_after] parameter of the search API instead.");

    XContentParser parser = parseContext.parser();

    int limit = -1;
    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 (token.isValue()) {
            if ("value".equals(currentFieldName)) {
                limit = parser.intValue();
            } else {
                throw new QueryParsingException(parseContext, "[limit] query does not support [" + currentFieldName + "]");
            }
        }
    }

    if (limit == -1) {
        throw new QueryParsingException(parseContext, "No value specified for limit query");
    }

    // this filter is deprecated and parses to a filter that matches everything
    return Queries.newMatchAllQuery();
}
 
Example 11
Source File: CancelAllocationCommand.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public CancelAllocationCommand fromXContent(XContentParser parser) throws IOException {
    String index = null;
    int shardId = -1;
    String nodeId = null;
    boolean allowPrimary = false;

    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 (token.isValue()) {
            if ("index".equals(currentFieldName)) {
                index = parser.text();
            } else if ("shard".equals(currentFieldName)) {
                shardId = parser.intValue();
            } else if ("node".equals(currentFieldName)) {
                nodeId = parser.text();
            } else if ("allow_primary".equals(currentFieldName) || "allowPrimary".equals(currentFieldName)) {
                allowPrimary = parser.booleanValue();
            } else {
                throw new ElasticsearchParseException("[{}] command does not support field [{}]", NAME, currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException("[{}] command does not support complex json tokens [{}]", NAME, token);
        }
    }
    if (index == null) {
        throw new ElasticsearchParseException("[{}] command missing the index parameter", NAME);
    }
    if (shardId == -1) {
        throw new ElasticsearchParseException("[{}] command missing the shard parameter", NAME);
    }
    if (nodeId == null) {
        throw new ElasticsearchParseException("[{}] command missing the node parameter", NAME);
    }
    return new CancelAllocationCommand(new ShardId(index, shardId), nodeId, allowPrimary);
}
 
Example 12
Source File: GeohashCellQuery.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    XContentParser parser = parseContext.parser();

    String fieldName = null;
    String geohash = null;
    int levels = -1;
    boolean neighbors = false;


    XContentParser.Token token;
    if ((token = parser.currentToken()) != Token.START_OBJECT) {
        throw new ElasticsearchParseException("failed to parse [{}] query. expected an object but found [{}] instead", NAME, token);
    }

    while ((token = parser.nextToken()) != Token.END_OBJECT) {
        if (token == Token.FIELD_NAME) {
            String field = parser.currentName();

            if (parseContext.isDeprecatedSetting(field)) {
                // skip
            } else if (PRECISION.equals(field)) {
                token = parser.nextToken();
                if(token == Token.VALUE_NUMBER) {
                    levels = parser.intValue();
                } else if(token == Token.VALUE_STRING) {
                    double meters = DistanceUnit.parse(parser.text(), DistanceUnit.DEFAULT, DistanceUnit.METERS);
                    levels = GeoUtils.geoHashLevelsForPrecision(meters);
                }
            } else if (NEIGHBORS.equals(field)) {
                parser.nextToken();
                neighbors = parser.booleanValue();
            } else {
                fieldName = field;
                token = parser.nextToken();
                if(token == Token.VALUE_STRING) {
                    // A string indicates either a gehash or a lat/lon string
                    String location = parser.text();
                    if(location.indexOf(",")>0) {
                        geohash = GeoUtils.parseGeoPoint(parser).geohash();
                    } else {
                        geohash = location;
                    }
                } else {
                    geohash = GeoUtils.parseGeoPoint(parser).geohash();
                }
            }
        } else {
            throw new ElasticsearchParseException("failed to parse [{}] query. unexpected token [{}]", NAME, token);
        }
    }

    if (geohash == null) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing geohash value", NAME);
    }

    MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
    if (fieldType == null) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing [{}] field [{}]", NAME, BaseGeoPointFieldMapper.CONTENT_TYPE, fieldName);
    }

    if (!(fieldType instanceof BaseGeoPointFieldMapper.GeoPointFieldType)) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. field [{}] is not a geo_point field", NAME, fieldName);
    }

    BaseGeoPointFieldMapper.GeoPointFieldType geoFieldType = ((BaseGeoPointFieldMapper.GeoPointFieldType) fieldType);
    if (!geoFieldType.isGeoHashPrefixEnabled()) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. [geohash_prefix] is not enabled for field [{}]", NAME, fieldName);
    }

    if(levels > 0) {
        int len = Math.min(levels, geohash.length());
        geohash = geohash.substring(0, len);
    }

    Query filter;
    if (neighbors) {
        filter = create(parseContext, geoFieldType, geohash, GeoHashUtils.addNeighbors(geohash, new ArrayList<CharSequence>(8)));
    } else {
        filter = create(parseContext, geoFieldType, geohash, null);
    }

    return filter;
}
 
Example 13
Source File: SecureHash.java    From crate with Apache License 2.0 4 votes vote down vote up
public static SecureHash fromXContent(XContentParser parser) throws IOException {
    XContentParser.Token currentToken;
    int iterations = 0;
    byte[] hash = new byte[0];
    byte[] salt = new byte[0];
    boolean hasPassword = false;

    while ((currentToken = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (currentToken == XContentParser.Token.FIELD_NAME) {
            while ((currentToken = parser.nextToken()) != XContentParser.Token.END_OBJECT) { // secure_hash
                hasPassword = true;
                if (currentToken == XContentParser.Token.FIELD_NAME) {
                    String currentFieldName = parser.currentName();
                    currentToken = parser.nextToken();
                    switch (currentFieldName) {
                        case X_CONTENT_KEY_ITERATIONS:
                            if (currentToken != XContentParser.Token.VALUE_NUMBER) {
                                throw new ElasticsearchParseException(
                                    "failed to parse SecureHash, 'iterations' value is not a number [{}]", currentToken);
                            }
                            iterations = parser.intValue();
                            break;
                        case X_CONTENT_KEY_HASH:
                            if (currentToken.isValue() == false) {
                                throw new ElasticsearchParseException(
                                    "failed to parse SecureHash, 'hash' does not contain any value [{}]", currentToken);
                            }
                            hash = parser.binaryValue();
                            break;
                        case X_CONTENT_KEY_SALT:
                            if (currentToken.isValue() == false) {
                                throw new ElasticsearchParseException(
                                    "failed to parse SecureHash, 'salt' does not contain any value [{}]", currentToken);
                            }
                            salt = parser.binaryValue();
                            break;
                        default:
                            throw new ElasticsearchParseException("failed to parse secure_hash");
                    }
                }
            }
        }
    }

    if (hasPassword) {
        return SecureHash.of(iterations, salt, hash);
    }
    return null;
}
 
Example 14
Source File: MoveAllocationCommand.java    From crate with Apache License 2.0 4 votes vote down vote up
public static MoveAllocationCommand fromXContent(XContentParser parser) throws IOException {
    String index = null;
    int shardId = -1;
    String fromNode = null;
    String toNode = 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 (token.isValue()) {
            if ("index".equals(currentFieldName)) {
                index = parser.text();
            } else if ("shard".equals(currentFieldName)) {
                shardId = parser.intValue();
            } else if ("from_node".equals(currentFieldName) || "fromNode".equals(currentFieldName)) {
                fromNode = parser.text();
            } else if ("to_node".equals(currentFieldName) || "toNode".equals(currentFieldName)) {
                toNode = parser.text();
            } else {
                throw new ElasticsearchParseException("[{}] command does not support field [{}]", NAME, currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException("[{}] command does not support complex json tokens [{}]", NAME, token);
        }
    }
    if (index == null) {
        throw new ElasticsearchParseException("[{}] command missing the index parameter", NAME);
    }
    if (shardId == -1) {
        throw new ElasticsearchParseException("[{}] command missing the shard parameter", NAME);
    }
    if (fromNode == null) {
        throw new ElasticsearchParseException("[{}] command missing the from_node parameter", NAME);
    }
    if (toNode == null) {
        throw new ElasticsearchParseException("[{}] command missing the to_node parameter", NAME);
    }
    return new MoveAllocationCommand(index, shardId, fromNode, toNode);
}
 
Example 15
Source File: IntegerFieldMapper.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException {
    int value;
    float boost = fieldType().boost();
    if (context.externalValueSet()) {
        Object externalValue = context.externalValue();
        if (externalValue == null) {
            if (fieldType().nullValue() == null) {
                return;
            }
            value = fieldType().nullValue();
        } else if (externalValue instanceof String) {
            String sExternalValue = (String) externalValue;
            if (sExternalValue.length() == 0) {
                if (fieldType().nullValue() == null) {
                    return;
                }
                value = fieldType().nullValue();
            } else {
                value = Integer.parseInt(sExternalValue);
            }
        } else {
            value = ((Number) externalValue).intValue();
        }
        if (context.includeInAll(includeInAll, this)) {
            context.allEntries().addText(fieldType().names().fullName(), Integer.toString(value), boost);
        }
    } else {
        XContentParser parser = context.parser();
        if (parser.currentToken() == XContentParser.Token.VALUE_NULL ||
                (parser.currentToken() == XContentParser.Token.VALUE_STRING && parser.textLength() == 0)) {
            if (fieldType().nullValue() == null) {
                return;
            }
            value = fieldType().nullValue();
            if (fieldType().nullValueAsString() != null && (context.includeInAll(includeInAll, this))) {
                context.allEntries().addText(fieldType().names().fullName(), fieldType().nullValueAsString(), boost);
            }
        } else if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
            XContentParser.Token token;
            String currentFieldName = null;
            Integer objValue = fieldType().nullValue();
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else {
                    if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) {
                        if (parser.currentToken() != XContentParser.Token.VALUE_NULL) {
                            objValue = parser.intValue(coerce.value());
                        }
                    } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) {
                        boost = parser.floatValue();
                    } else {
                        throw new IllegalArgumentException("unknown property [" + currentFieldName + "]");
                    }
                }
            }
            if (objValue == null) {
                // no value
                return;
            }
            value = objValue;
        } else {
            value = parser.intValue(coerce.value());
            if (context.includeInAll(includeInAll, this)) {
                context.allEntries().addText(fieldType().names().fullName(), parser.text(), boost);
            }
        }
    }
    addIntegerFields(context, fields, value, boost);
}
 
Example 16
Source File: PhraseCountQueryBuilder.java    From pyramid with Apache License 2.0 4 votes vote down vote up
public static Optional<PhraseCountQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
    XContentParser parser = parseContext.parser();
    String fieldName = null;
    Object value = null;
    float boost = AbstractQueryBuilder.DEFAULT_BOOST;
    String analyzer = null;
    int slop = MatchQuery.DEFAULT_PHRASE_SLOP;
    boolean inOrder = false;
    boolean weightedCount = false;
    String queryName = 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 (parseContext.isDeprecatedSetting(currentFieldName)) {
            // skip
        } else if (token == XContentParser.Token.START_OBJECT) {
            throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
            fieldName = currentFieldName;
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else if (token.isValue()) {
                    if (PhraseCountQueryBuilder.QUERY_FIELD.match(currentFieldName)) {
                        value = parser.objectText();
                    } else if (ANALYZER_FIELD.match(currentFieldName)) {
                        analyzer = parser.text();
                    } else if(IN_ORDER_FIELD.match(currentFieldName)) {
                        inOrder = parser.booleanValue();
                    } else if (WEIGHTED_COUNT_FIELD.match(currentFieldName)) {
                        weightedCount = parser.booleanValue();
                    } else if (BOOST_FIELD.match(currentFieldName)) {
                        boost = parser.floatValue();
                    } else if (SLOP_FIELD.match(currentFieldName)) {
                        slop = parser.intValue();
                    } else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName)) {
                        queryName = parser.text();
                    } else {
                        throw new ParsingException(parser.getTokenLocation(),
                            "[" + NAME + "] query does not support [" + currentFieldName + "]");
                    }
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                        "[" + NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]");
                }
            }
        } else {
            throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, parser.currentName());
            fieldName = parser.currentName();
            value = parser.objectText();
        }
    }

    PhraseCountQueryBuilder phraseCountQuery = new PhraseCountQueryBuilder(fieldName, value);
    phraseCountQuery.analyzer(analyzer);
    phraseCountQuery.slop(slop);
    phraseCountQuery.inOrder(inOrder);
    phraseCountQuery.weightedCount(weightedCount);
    phraseCountQuery.queryName(queryName);
    phraseCountQuery.boost(boost);
    return Optional.of(phraseCountQuery);
}
 
Example 17
Source File: UsersPrivilegesMetaData.java    From crate with Apache License 2.0 4 votes vote down vote up
private static void privilegeFromXContent(XContentParser parser, Set<Privilege> privileges) throws IOException {
    XContentParser.Token currentToken;
    State state = null;
    Privilege.Type type = null;
    Privilege.Clazz clazz = null;
    String ident = null;
    String grantor = null;
    while ((currentToken = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (currentToken == XContentParser.Token.FIELD_NAME) {
            String currentFieldName = parser.currentName();
            currentToken = parser.nextToken();
            switch (currentFieldName) {
                case "state":
                    if (currentToken != XContentParser.Token.VALUE_NUMBER) {
                        throw new ElasticsearchParseException(
                            "failed to parse privilege, 'state' value is not a number [{}]", currentToken);
                    }
                    state = State.values()[parser.intValue()];
                    break;
                case "type":
                    if (currentToken != XContentParser.Token.VALUE_NUMBER) {
                        throw new ElasticsearchParseException(
                            "failed to parse privilege, 'type' value is not a number [{}]", currentToken);
                    }
                    type = Privilege.Type.values()[parser.intValue()];
                    break;
                case "class":
                    if (currentToken != XContentParser.Token.VALUE_NUMBER) {
                        throw new ElasticsearchParseException(
                            "failed to parse privilege, 'class' value is not a number [{}]", currentToken);
                    }
                    clazz = Privilege.Clazz.values()[parser.intValue()];
                    break;
                case "ident":
                    if (currentToken != XContentParser.Token.VALUE_STRING
                        && currentToken != XContentParser.Token.VALUE_NULL) {
                        throw new ElasticsearchParseException(
                            "failed to parse privilege, 'ident' value is not a string or null [{}]", currentToken);
                    }
                    ident = parser.textOrNull();
                    break;
                case "grantor":
                    if (currentToken != XContentParser.Token.VALUE_STRING) {
                        throw new ElasticsearchParseException(
                            "failed to parse privilege, 'grantor' value is not a string [{}]", currentToken);
                    }
                    grantor = parser.text();
                    break;
                default:
                    throw new ElasticsearchParseException("failed to parse privilege");
            }
        } else if (currentToken == XContentParser.Token.END_ARRAY) {
            // empty privileges set
            return;
        }
    }
    privileges.add(new Privilege(state, type, clazz, ident, grantor));
}
 
Example 18
Source File: RandomScoreFunctionParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException {

    int seed = -1;

    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 (token.isValue()) {
            if ("seed".equals(currentFieldName)) {
                if (token == XContentParser.Token.VALUE_NUMBER) {
                    if (parser.numberType() == XContentParser.NumberType.INT) {
                        seed = parser.intValue();
                    } else if (parser.numberType() == XContentParser.NumberType.LONG) {
                        seed = Longs.hashCode(parser.longValue());
                    } else {
                        throw new QueryParsingException(parseContext, "random_score seed must be an int, long or string, not '"
                                + token.toString() + "'");
                    }
                } else if (token == XContentParser.Token.VALUE_STRING) {
                    seed = parser.text().hashCode();
                } else {
                    throw new QueryParsingException(parseContext, "random_score seed must be an int/long or string, not '"
                            + token.toString() + "'");
                }
            } else {
                throw new QueryParsingException(parseContext, NAMES[0] + " query does not support [" + currentFieldName + "]");
            }
        }
    }

    final MappedFieldType fieldType = SearchContext.current().mapperService().smartNameFieldType("_uid");
    if (fieldType == null) {
        // mapper could be null if we are on a shard with no docs yet, so this won't actually be used
        return new RandomScoreFunction();
    }

    if (seed == -1) {
        seed = Longs.hashCode(parseContext.nowInMillis());
    }
    final ShardId shardId = SearchContext.current().indexShard().shardId();
    final int salt = (shardId.index().name().hashCode() << 10) | shardId.id();
    final IndexFieldData<?> uidFieldData = SearchContext.current().fieldData().getForField(fieldType);

    return new RandomScoreFunction(seed, salt, uidFieldData);
}
 
Example 19
Source File: SamplerParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {

    XContentParser.Token token;
    String currentFieldName = null;
    String executionHint = null;
    int shardSize = DEFAULT_SHARD_SAMPLE_SIZE;
    int maxDocsPerValue = MAX_DOCS_PER_VALUE_DEFAULT;
    ValuesSourceParser vsParser = null;
    boolean diversityChoiceMade = false;

    vsParser = ValuesSourceParser.any(aggregationName, InternalSampler.TYPE, context).scriptable(true).formattable(false).build();

    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_NUMBER) {
            if (context.parseFieldMatcher().match(currentFieldName, SHARD_SIZE_FIELD)) {
                shardSize = parser.intValue();
            } else if (context.parseFieldMatcher().match(currentFieldName, MAX_DOCS_PER_VALUE_FIELD)) {
                diversityChoiceMade = true;
                maxDocsPerValue = parser.intValue();
            } else {
                throw new SearchParseException(context, "Unsupported property \"" + currentFieldName + "\" for aggregation \""
                        + aggregationName, parser.getTokenLocation());
            }
        } else if (!vsParser.token(currentFieldName, token, parser)) {
            if (context.parseFieldMatcher().match(currentFieldName, EXECUTION_HINT_FIELD)) {
                executionHint = parser.text();
            } else {
                throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "].",
                        parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unsupported property \"" + currentFieldName + "\" for aggregation \""
                    + aggregationName, parser.getTokenLocation());
        }
    }

    ValuesSourceConfig vsConfig = vsParser.config();
    if (vsConfig.valid()) {
        return new SamplerAggregator.DiversifiedFactory(aggregationName, shardSize, executionHint, vsConfig, maxDocsPerValue);
    } else {
        if (diversityChoiceMade) {
            throw new SearchParseException(context, "Sampler aggregation has " + MAX_DOCS_PER_VALUE_FIELD.getPreferredName()
                    + " setting but no \"field\" or \"script\" setting to provide values for aggregation \"" + aggregationName + "\"",
                    parser.getTokenLocation());

        }
        return new SamplerAggregator.Factory(aggregationName, shardSize);
    }
}
 
Example 20
Source File: SerialDiffParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public PipelineAggregatorFactory parse(String reducerName, XContentParser parser, SearchContext context) throws IOException {
    XContentParser.Token token;
    String currentFieldName = null;
    String[] bucketsPaths = null;
    String format = null;
    GapPolicy gapPolicy = GapPolicy.SKIP;
    int lag = 1;

    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if (context.parseFieldMatcher().match(currentFieldName, FORMAT)) {
                format = parser.text();
            } else if (context.parseFieldMatcher().match(currentFieldName, BUCKETS_PATH)) {
                bucketsPaths = new String[] { parser.text() };
            } else if (context.parseFieldMatcher().match(currentFieldName, GAP_POLICY)) {
                gapPolicy = GapPolicy.parse(context, parser.text(), parser.getTokenLocation());
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + reducerName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else if (token == XContentParser.Token.VALUE_NUMBER) {
            if (context.parseFieldMatcher().match(currentFieldName, LAG)) {
                lag = parser.intValue(true);
                if (lag <= 0) {
                    throw new SearchParseException(context, "Lag must be a positive, non-zero integer.  Value supplied was" +
                            lag + " in [" + reducerName + "]: ["
                            + currentFieldName + "].", parser.getTokenLocation());
                }
            }  else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + reducerName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            if (context.parseFieldMatcher().match(currentFieldName, BUCKETS_PATH)) {
                List<String> paths = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    String path = parser.text();
                    paths.add(path);
                }
                bucketsPaths = paths.toArray(new String[paths.size()]);
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + reducerName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unexpected token " + token + " in [" + reducerName + "].",
                    parser.getTokenLocation());
        }
    }

    if (bucketsPaths == null) {
        throw new SearchParseException(context, "Missing required field [" + BUCKETS_PATH.getPreferredName()
                + "] for derivative aggregation [" + reducerName + "]", parser.getTokenLocation());
    }

    ValueFormatter formatter;
    if (format != null) {
        formatter = ValueFormat.Patternable.Number.format(format).formatter();
    }  else {
        formatter = ValueFormatter.RAW;
    }

    return new SerialDiffPipelineAggregator.Factory(reducerName, bucketsPaths, formatter, gapPolicy, lag);
}