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

The following examples show how to use org.elasticsearch.common.xcontent.XContentParser#currentName() . 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: AbstractXContentParser.java    From crate with Apache License 2.0 6 votes vote down vote up
static Map<String, String> readMapStrings(XContentParser parser, MapStringsFactory mapStringsFactory) throws IOException {
    Map<String, String> map = mapStringsFactory.newMap();
    XContentParser.Token token = parser.currentToken();
    if (token == null) {
        token = parser.nextToken();
    }
    if (token == XContentParser.Token.START_OBJECT) {
        token = parser.nextToken();
    }
    for (; token == XContentParser.Token.FIELD_NAME; token = parser.nextToken()) {
        // Must point to field name
        String fieldName = parser.currentName();
        // And then the value...
        parser.nextToken();
        String value = parser.text();
        map.put(fieldName, value);
    }
    return map;
}
 
Example 2
Source File: TestCustomMetaData.java    From crate with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends MetaData.Custom> T fromXContent(Function<String, MetaData.Custom> supplier, XContentParser parser)
    throws IOException {
    XContentParser.Token token;
    String data = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            String currentFieldName = parser.currentName();
            if ("data".equals(currentFieldName)) {
                if (parser.nextToken() != XContentParser.Token.VALUE_STRING) {
                    throw new ElasticsearchParseException("failed to parse snapshottable metadata, invalid data type");
                }
                data = parser.text();
            } else {
                throw new ElasticsearchParseException("failed to parse snapshottable metadata, unknown field [{}]", currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException("failed to parse snapshottable metadata");
        }
    }
    if (data == null) {
        throw new ElasticsearchParseException("failed to parse snapshottable metadata, data not found");
    }
    return (T) supplier.apply(data);
}
 
Example 3
Source File: TenantMetadata.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public static TenantMetadata fromXContent(XContentParser parser) throws IOException {
    Builder builder = new Builder();
    XContentParser.Token token = parser.currentToken();
    String currentFieldName = parser.currentName();
    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 ("tenant_list".equalsIgnoreCase(currentFieldName)) {
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentFieldName = parser.currentName();
                    } else if (token == XContentParser.Token.START_OBJECT) {
                        TenantProperty tenantProperty = TenantProperty.Builder.fromXContent(parser);
                        builder.addOrChangeTenantProperty(tenantProperty);
                    }
                }
            }
        } else if (token == XContentParser.Token.VALUE_NUMBER) {
            if ("max_tenant_id".equalsIgnoreCase(currentFieldName)) {
                builder.maxTenantId(parser.longValue());
            }
        }
    }
    return builder.build();
}
 
Example 4
Source File: DecayFunctionParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private AbstractDistanceScoreFunction parseNumberVariable(String fieldName, XContentParser parser, QueryParseContext parseContext,
        NumberFieldMapper.NumberFieldType fieldType, MultiValueMode mode) throws IOException {
    XContentParser.Token token;
    String parameterName = null;
    double scale = 0;
    double origin = 0;
    double decay = 0.5;
    double offset = 0.0d;
    boolean scaleFound = false;
    boolean refFound = false;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            parameterName = parser.currentName();
        } else if (parameterName.equals(DecayFunctionBuilder.SCALE)) {
            scale = parser.doubleValue();
            scaleFound = true;
        } else if (parameterName.equals(DecayFunctionBuilder.DECAY)) {
            decay = parser.doubleValue();
        } else if (parameterName.equals(DecayFunctionBuilder.ORIGIN)) {
            origin = parser.doubleValue();
            refFound = true;
        } else if (parameterName.equals(DecayFunctionBuilder.OFFSET)) {
            offset = parser.doubleValue();
        } else {
            throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
        }
    }
    if (!scaleFound || !refFound) {
        throw new ElasticsearchParseException("both [{}] and [{}] must be set for numeric fields.", DecayFunctionBuilder.SCALE, DecayFunctionBuilder.ORIGIN);
    }
    IndexNumericFieldData numericFieldData = parseContext.getForField(fieldType);
    return new NumericFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), numericFieldData, mode);
}
 
Example 5
Source File: ExactPhraseQueryBuilder.java    From elasticsearch-plugin-bundle with GNU Affero General Public License v3.0 5 votes vote down vote up
public static ExactPhraseQueryBuilder fromXContent(XContentParser parser) throws IOException {
    float boost = AbstractQueryBuilder.DEFAULT_BOOST;
    String queryName = null;
    QueryBuilder query = 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 == XContentParser.Token.START_OBJECT) {
            if (currentFieldName != null) {
                if (QUERY_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    query = parseInnerQueryBuilder(parser);
                } else {
                    throw new ParsingException(parser.getTokenLocation(), "[nested] query does not support [" + currentFieldName + "]");
                }
            }
        } else if (token.isValue()) {
            if (currentFieldName != null) {
                if (AbstractQueryBuilder.BOOST_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    boost = parser.floatValue();
                } else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    queryName = parser.text();
                } else {
                    throw new ParsingException(parser.getTokenLocation(), "[nested] query does not support [" + currentFieldName + "]");
                }
            }
        }
    }
    return new ExactPhraseQueryBuilder(query).queryName(queryName).boost(boost);
}
 
Example 6
Source File: Alias.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Parses an alias and returns its parsed representation
 */
public static Alias fromXContent(XContentParser parser) throws IOException {
    Alias alias = new Alias(parser.currentName());

    String currentFieldName = null;
    XContentParser.Token token = parser.nextToken();
    if (token == null) {
        throw new IllegalArgumentException("No alias is specified");
    }
    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.match(currentFieldName, parser.getDeprecationHandler())) {
                Map<String, Object> filter = parser.mapOrdered();
                alias.filter(filter);
            }
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if (ROUTING.match(currentFieldName, parser.getDeprecationHandler())) {
                alias.routing(parser.text());
            } else if (INDEX_ROUTING.match(currentFieldName, parser.getDeprecationHandler())) {
                alias.indexRouting(parser.text());
            } else if (SEARCH_ROUTING.match(currentFieldName, parser.getDeprecationHandler())) {
                alias.searchRouting(parser.text());
            }
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if (IS_WRITE_INDEX.match(currentFieldName, parser.getDeprecationHandler())) {
                alias.writeIndex(parser.booleanValue());
            }
        }
    }
    return alias;
}
 
Example 7
Source File: SQLBulkArgsParseElement.java    From crate with Apache License 2.0 5 votes vote down vote up
private List<List<Object>> parseSubArrays(XContentParser parser) throws IOException {
    XContentParser.Token token;
    ArrayList<List<Object>> bulkArgs = new ArrayList<>();
    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
        if (token == XContentParser.Token.START_ARRAY) {
            bulkArgs.add(parseSubArray(parser));
        } else {
            throw new SQLParseSourceException("Field [" + parser.currentName() + "] has an invalid value");
        }
    }
    return bulkArgs;
}
 
Example 8
Source File: ShardStateMetaData.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public ShardStateMetaData fromXContent(XContentParser parser) throws IOException {
    XContentParser.Token token = parser.nextToken();
    if (token == null) {
        return null;
    }
    long version = -1;
    Boolean primary = null;
    String currentFieldName = null;
    String indexUUID = IndexMetaData.INDEX_UUID_NA_VALUE;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token.isValue()) {
            if (VERSION_KEY.equals(currentFieldName)) {
                version = parser.longValue();
            } else if (PRIMARY_KEY.equals(currentFieldName)) {
                primary = parser.booleanValue();
            } else if (INDEX_UUID_KEY.equals(currentFieldName)) {
                indexUUID = parser.text();
            } else {
                throw new CorruptStateException("unexpected field in shard state [" + currentFieldName + "]");
            }
        } else {
            throw new CorruptStateException("unexpected token in shard state [" + token.name() + "]");
        }
    }
    if (primary == null) {
        throw new CorruptStateException("missing value for [primary] in shard state");
    }
    if (version == -1) {
        throw new CorruptStateException("missing value for [version] in shard state");
    }
    return new ShardStateMetaData(version, primary, indexUUID);
}
 
Example 9
Source File: AnomalyDetectorExecutionInput.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public static AnomalyDetectorExecutionInput parse(XContentParser parser, String detectorId) throws IOException {
    Instant periodStart = null;
    Instant periodEnd = null;
    AnomalyDetector detector = null;

    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser::getTokenLocation);
    while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
        String fieldName = parser.currentName();
        parser.nextToken();

        switch (fieldName) {
            case PERIOD_START_FIELD:
                periodStart = ParseUtils.toInstant(parser);
                break;
            case PERIOD_END_FIELD:
                periodEnd = ParseUtils.toInstant(parser);
                break;
            case DETECTOR_FIELD:
                XContentParser.Token token = parser.currentToken();
                if (parser.currentToken().equals(XContentParser.Token.START_OBJECT)) {
                    detector = AnomalyDetector.parse(parser, detectorId);
                }
                break;
            default:
                break;
        }
    }
    return new AnomalyDetectorExecutionInput(detectorId, periodStart, periodEnd, detector);
}
 
Example 10
Source File: SQLBulkArgsParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private Object[][] parseSubArrays(SQLXContentSourceContext context, XContentParser parser) throws IOException {
    XContentParser.Token token;
    List<Object[]> list = new ArrayList<Object[]>();
    while((token = parser.nextToken()) != XContentParser.Token.END_ARRAY){
        if(token == XContentParser.Token.START_ARRAY) {
            list.add(parseSubArray(context, parser));
        } else {
            throw new SQLParseSourceException(context, "Field [" + parser.currentName() + "] has an invalid value");
        }
    }
    return list.toArray(new Object[list.size()][]);
}
 
Example 11
Source File: ShapeBuilder.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Parse the geometry specified by the source document and return a ShapeBuilder instance used to
 * build the actual geometry
 * @param parser - parse utility object including source document
 * @param shapeMapper - field mapper needed for index specific parameters
 * @return ShapeBuilder - a builder instance used to create the geometry
 */
public static ShapeBuilder parse(XContentParser parser, GeoShapeFieldMapper shapeMapper) throws IOException {
    if (parser.currentToken() == XContentParser.Token.VALUE_NULL) {
        return null;
    } else if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
        throw new ElasticsearchParseException("shape must be an object consisting of type and coordinates");
    }

    GeoShapeType shapeType = null;
    Distance radius = null;
    CoordinateNode node = null;
    GeometryCollectionBuilder geometryCollections = null;

    Orientation requestedOrientation = (shapeMapper == null) ? Orientation.RIGHT : shapeMapper.fieldType().orientation();
    boolean coerce = (shapeMapper == null) ? GeoShapeFieldMapper.Defaults.COERCE.value() : shapeMapper.coerce().value();

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

            if (FIELD_TYPE.equals(fieldName)) {
                parser.nextToken();
                shapeType = GeoShapeType.forName(parser.text());
            } else if (FIELD_COORDINATES.equals(fieldName)) {
                parser.nextToken();
                node = parseCoordinates(parser);
            } else if (FIELD_GEOMETRIES.equals(fieldName)) {
                parser.nextToken();
                geometryCollections = parseGeometries(parser, shapeMapper);
            } else if (CircleBuilder.FIELD_RADIUS.equals(fieldName)) {
                parser.nextToken();
                radius = Distance.parseDistance(parser.text());
            } else if (FIELD_ORIENTATION.equals(fieldName)) {
                parser.nextToken();
                requestedOrientation = orientationFromString(parser.text());
            } else {
                parser.nextToken();
                parser.skipChildren();
            }
        }
    }

    if (shapeType == null) {
        throw new ElasticsearchParseException("shape type not included");
    } else if (node == null && GeoShapeType.GEOMETRYCOLLECTION != shapeType) {
        throw new ElasticsearchParseException("coordinates not included");
    } else if (geometryCollections == null && GeoShapeType.GEOMETRYCOLLECTION == shapeType) {
        throw new ElasticsearchParseException("geometries not included");
    } else if (radius != null && GeoShapeType.CIRCLE != shapeType) {
        throw new ElasticsearchParseException("field [{}] is supported for [{}] only", CircleBuilder.FIELD_RADIUS, CircleBuilder.TYPE);
    }

    switch (shapeType) {
        case POINT: return parsePoint(node);
        case MULTIPOINT: return parseMultiPoint(node);
        case LINESTRING: return parseLineString(node);
        case MULTILINESTRING: return parseMultiLine(node);
        case POLYGON: return parsePolygon(node, requestedOrientation, coerce);
        case MULTIPOLYGON: return parseMultiPolygon(node, requestedOrientation, coerce);
        case CIRCLE: return parseCircle(node, radius);
        case ENVELOPE: return parseEnvelope(node, requestedOrientation);
        case GEOMETRYCOLLECTION: return geometryCollections;
        default:
            throw new ElasticsearchParseException("shape type [{}] not included", shapeType);
    }
}
 
Example 12
Source File: RepositoriesMetaData.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public RepositoriesMetaData fromXContent(XContentParser parser) throws IOException {
    XContentParser.Token token;
    List<RepositoryMetaData> repository = new ArrayList<>();
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            String name = parser.currentName();
            if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
                throw new ElasticsearchParseException("failed to parse repository [{}], expected object", name);
            }
            String type = null;
            Settings settings = Settings.EMPTY;
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    String currentFieldName = parser.currentName();
                    if ("type".equals(currentFieldName)) {
                        if (parser.nextToken() != XContentParser.Token.VALUE_STRING) {
                            throw new ElasticsearchParseException("failed to parse repository [{}], unknown type", name);
                        }
                        type = parser.text();
                    } else if ("settings".equals(currentFieldName)) {
                        if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
                            throw new ElasticsearchParseException("failed to parse repository [{}], incompatible params", name);
                        }
                        settings = Settings.settingsBuilder().put(SettingsLoader.Helper.loadNestedFromMap(parser.mapOrdered())).build();
                    } else {
                        throw new ElasticsearchParseException("failed to parse repository [{}], unknown field [{}]", name, currentFieldName);
                    }
                } else {
                    throw new ElasticsearchParseException("failed to parse repository [{}]", name);
                }
            }
            if (type == null) {
                throw new ElasticsearchParseException("failed to parse repository [{}], missing repository type", name);
            }
            repository.add(new RepositoryMetaData(name, type, settings));
        } else {
            throw new ElasticsearchParseException("failed to parse repositories");
        }
    }
    return new RepositoriesMetaData(repository.toArray(new RepositoryMetaData[repository.size()]));
}
 
Example 13
Source File: MultiValuesSourceParser.java    From elasticsearch-linear-regression with Apache License 2.0 4 votes vote down vote up
@Override
public final MultiValuesSourceAggregationBuilder<VS, ?> parse(String aggregationName,
    QueryParseContext context)
    throws IOException {

  XContentParser parser = context.parser();
  List<String> fields = null;
  ValueType valueType = null;
  String format = null;
  Map<String, Object> missingMap = null;
  Map<ParseField, Object> otherOptions = new HashMap<>();
  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 (token == XContentParser.Token.VALUE_STRING) {
      if (CommonFields.FIELDS.match(currentFieldName)) {
        fields = Collections.singletonList(parser.text());
      } else if (formattable && CommonFields.FORMAT.match(currentFieldName)) {
        format = parser.text();
      } else if (CommonFields.VALUE_TYPE.match(currentFieldName)) {
        throw new ParsingException(parser.getTokenLocation(),
            "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName
                + "]. " +
                "Multi-field aggregations do not support scripts.");
      } else if (!token(aggregationName, currentFieldName, token, parser, otherOptions)) {
        throw new ParsingException(parser.getTokenLocation(),
            "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName
                + "].");
      }
    } else if (token == XContentParser.Token.START_OBJECT) {
      if (CommonFields.MISSING.match(currentFieldName)) {
        missingMap = new HashMap<>();
        while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
          parseMissingAndAdd(aggregationName, currentFieldName, parser, missingMap);
        }
      } else if (Script.SCRIPT_PARSE_FIELD.match(currentFieldName)) {
        throw new ParsingException(parser.getTokenLocation(),
            "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName
                + "]. " +
                "Multi-field aggregations do not support scripts.");

      } else if (!token(aggregationName, currentFieldName, token, parser, otherOptions)) {
        throw new ParsingException(parser.getTokenLocation(),
            "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName
                + "].");
      }
    } else if (token == XContentParser.Token.START_ARRAY) {
      if (Script.SCRIPT_PARSE_FIELD.match(currentFieldName)) {
        throw new ParsingException(parser.getTokenLocation(),
            "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName
                + "]. " +
                "Multi-field aggregations do not support scripts.");
      } else if (CommonFields.FIELDS.match(currentFieldName)) {
        fields = new ArrayList<>();
        while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
          if (token == XContentParser.Token.VALUE_STRING) {
            fields.add(parser.text());
          } else {
            throw new ParsingException(parser.getTokenLocation(),
                "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName
                    + "].");
          }
        }
      } else if (!token(aggregationName, currentFieldName, token, parser, otherOptions)) {
        throw new ParsingException(parser.getTokenLocation(),
            "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName
                + "].");
      }
    } else if (!token(aggregationName, currentFieldName, token, parser, otherOptions)) {
      throw new ParsingException(parser.getTokenLocation(),
          "Unexpected token " + token + " [" + currentFieldName + "] in [" + aggregationName
              + "].");
    }
  }

  MultiValuesSourceAggregationBuilder<VS, ?> factory = createFactory(aggregationName,
      this.valuesSourceType, this.targetValueType,
      otherOptions);
  if (fields != null) {
    factory.fields(fields);
  }
  if (valueType != null) {
    factory.valueType(valueType);
  }
  if (format != null) {
    factory.format(format);
  }
  if (missingMap != null) {
    factory.missingMap(missingMap);
  }
  return factory;
}
 
Example 14
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 15
Source File: TermsEnumTermsQueryParser.java    From siren-join with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
  XContentParser parser = parseContext.parser();

  XContentParser.Token token = parser.nextToken();
  if (token != XContentParser.Token.FIELD_NAME) {
      throw new QueryParsingException(parseContext, "[termsenum_terms] a field name is required");
  }
  String fieldName = parser.currentName();

  String queryName = null;
  byte[] value = null;
  Long cacheKey = null;

  token = parser.nextToken();
  if (token == XContentParser.Token.START_OBJECT) {
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
      if (token == XContentParser.Token.FIELD_NAME) {
        currentFieldName = parser.currentName();
      } else {
        if ("value".equals(currentFieldName)) {
            value = parser.binaryValue();
        } else if ("_name".equals(currentFieldName)) {
            queryName = parser.text();
        } else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) {
            cacheKey = parser.longValue();
        } else {
          throw new QueryParsingException(parseContext, "[termsenum_terms] filter does not support [" + currentFieldName + "]");
        }
      }
    }
    parser.nextToken();
  } else {
    value = parser.binaryValue();
    // move to the next token
    parser.nextToken();
  }

  if (value == null) {
    throw new QueryParsingException(parseContext, "[termsenum_terms] a binary value is required");
  }
  if (cacheKey == null) { // cache key is mandatory - see #170
    throw new QueryParsingException(parseContext, "[termsenum_terms] a cache key is required");
  }

  if (fieldName == null) {
    throw new QueryParsingException(parseContext, "[termsenum_terms] a field name is required");
  }

  MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
  if (fieldType == null) {
    return new MatchNoDocsQuery();
  }

  Query query = new TermsEnumTermsQuery(value, fieldName, cacheKey);

  if (queryName != null) {
    parseContext.addNamedQuery(queryName, query);
  }

  return query;
}
 
Example 16
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 17
Source File: FilteredQueryParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    deprecationLogger.deprecated("The [filtered] query is deprecated, please use a [bool] query instead with a [must] "
            + "clause for the query part and a [filter] clause for the filter part.");

    XContentParser parser = parseContext.parser();

    Query query = Queries.newMatchAllQuery();
    Query filter = null;
    boolean filterFound = false;
    float boost = 1.0f;
    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) {
            if ("query".equals(currentFieldName)) {
                query = parseContext.parseInnerQuery();
            } else if ("filter".equals(currentFieldName)) {
                filterFound = true;
                filter = parseContext.parseInnerFilter();
            } else {
                throw new QueryParsingException(parseContext, "[filtered] query does not support [" + currentFieldName + "]");
            }
        } else if (token.isValue()) {
            if ("strategy".equals(currentFieldName)) {
                // ignore
            } else if ("_name".equals(currentFieldName)) {
                queryName = parser.text();
            } else if ("boost".equals(currentFieldName)) {
                boost = parser.floatValue();
            } else {
                throw new QueryParsingException(parseContext, "[filtered] query does not support [" + currentFieldName + "]");
            }
        }
    }

    // parsed internally, but returned null during parsing...
    if (query == null) {
        return null;
    }

    BooleanQuery filteredQuery = Queries.filtered(query, filter);
    filteredQuery.setBoost(boost);
    if (queryName != null) {
        parseContext.addNamedQuery(queryName, filteredQuery);
    }
    return filteredQuery;
}
 
Example 18
Source File: IndicesQueryParser.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();

    Query noMatchQuery = null;
    boolean queryFound = false;
    boolean indicesFound = false;
    boolean currentIndexMatchesIndices = false;
    String queryName = null;

    String currentFieldName = null;
    XContentParser.Token token;
    XContentStructure.InnerQuery innerQuery = null;
    XContentStructure.InnerQuery innerNoMatchQuery = null;
    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 (parseContext.parseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
                innerQuery = new XContentStructure.InnerQuery(parseContext, null);
                queryFound = true;
            } else if (parseContext.parseFieldMatcher().match(currentFieldName, NO_MATCH_QUERY)) {
                innerNoMatchQuery = new XContentStructure.InnerQuery(parseContext, null);
            } else {
                throw new QueryParsingException(parseContext, "[indices] query does not support [" + currentFieldName + "]");
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            if ("indices".equals(currentFieldName)) {
                if (indicesFound) {
                    throw new QueryParsingException(parseContext, "[indices] indices or index already specified");
                }
                indicesFound = true;
                Collection<String> indices = new ArrayList<>();
                while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                    String value = parser.textOrNull();
                    if (value == null) {
                        throw new QueryParsingException(parseContext, "[indices] no value specified for 'indices' entry");
                    }
                    indices.add(value);
                }
                currentIndexMatchesIndices = matchesIndices(parseContext.index().name(), indices.toArray(new String[indices.size()]));
            } else {
                throw new QueryParsingException(parseContext, "[indices] query does not support [" + currentFieldName + "]");
            }
        } else if (token.isValue()) {
            if ("index".equals(currentFieldName)) {
                if (indicesFound) {
                    throw new QueryParsingException(parseContext, "[indices] indices or index already specified");
                }
                indicesFound = true;
                currentIndexMatchesIndices = matchesIndices(parseContext.index().name(), parser.text());
            } else if (parseContext.parseFieldMatcher().match(currentFieldName, NO_MATCH_QUERY)) {
                String type = parser.text();
                if ("all".equals(type)) {
                    noMatchQuery = Queries.newMatchAllQuery();
                } else if ("none".equals(type)) {
                    noMatchQuery = Queries.newMatchNoDocsQuery();
                }
            } else if ("_name".equals(currentFieldName)) {
                queryName = parser.text();
            } else {
                throw new QueryParsingException(parseContext, "[indices] query does not support [" + currentFieldName + "]");
            }
        }
    }
    if (!queryFound) {
        throw new QueryParsingException(parseContext, "[indices] requires 'query' element");
    }
    if (!indicesFound) {
        throw new QueryParsingException(parseContext, "[indices] requires 'indices' or 'index' element");
    }

    Query chosenQuery;
    if (currentIndexMatchesIndices) {
        chosenQuery = innerQuery.asQuery();
    } else {
        // If noMatchQuery is set, it means "no_match_query" was "all" or "none"
        if (noMatchQuery != null) {
            chosenQuery = noMatchQuery;
        } else {
            // There might be no "no_match_query" set, so default to the match_all if not set
            if (innerNoMatchQuery == null) {
                chosenQuery = Queries.newMatchAllQuery();
            } else {
                chosenQuery = innerNoMatchQuery.asQuery();
            }
        }
    }
    if (queryName != null) {
        parseContext.addNamedQuery(queryName, chosenQuery);
    }
    return chosenQuery;
}
 
Example 19
Source File: ByteFieldMapper.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 {
    byte 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 = Byte.parseByte(sExternalValue);
            }
        } else {
            value = ((Number) externalValue).byteValue();
        }
        if (context.includeInAll(includeInAll, this)) {
            context.allEntries().addText(fieldType().names().fullName(), Byte.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;
            Byte 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 = (byte) parser.shortValue(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 = (byte) parser.shortValue(coerce.value());
            if (context.includeInAll(includeInAll, this)) {
                context.allEntries().addText(fieldType().names().fullName(), parser.text(), boost);
            }
        }
    }
    if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) {
        CustomByteNumericField field = new CustomByteNumericField(value, fieldType());
        field.setBoost(boost);
        fields.add(field);
    }
    if (fieldType().hasDocValues()) {
        addDocValue(context, fields, value);
    }
}
 
Example 20
Source File: AliasMetaData.java    From crate with Apache License 2.0 4 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 {
                parser.skipChildren();
            }
        } 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());
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            parser.skipChildren();
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if ("is_write_index".equals(currentFieldName)) {
                builder.writeIndex(parser.booleanValue());
            }
        }
    }
    return builder.build();
}