Java Code Examples for org.elasticsearch.common.xcontent.XContentBuilder#map()

The following examples show how to use org.elasticsearch.common.xcontent.XContentBuilder#map() . 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: MetricProfileRepositoryImpl.java    From adaptive-alerting with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean profilingExists(Map<String, String> tags) {
    try {
        List<BytesReference> refList = new ArrayList<>();
        XContentBuilder xContent = XContentFactory.jsonBuilder();
        xContent.map(tags);
        refList.add(BytesReference.bytes(xContent));

        PercolateQueryBuilder percolateQuery = new PercolateQueryBuilder(PercolatorMetricProfiling.QUERY_KEYWORD,
                refList, XContentType.JSON);

        val boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.filter(percolateQuery);
        val searchSourceBuilder = elasticsearchUtil.getSourceBuilder(boolQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(elasticSearchProperties.getConfig().getConnectionTimeout()));
        searchSourceBuilder.size(500);

        val searchRequest = new SearchRequest().source(searchSourceBuilder).indices(METRIC_PROFILING_INDEX);
        val searchResponse = legacyElasticSearchClient.search(searchRequest, RequestOptions.DEFAULT);

        return searchResponse.getHits().getHits().length > 0;
    } catch (IOException e) {
        log.error("Error ES lookup", e);
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: CreateIndexRequest.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Adds mapping that will be added when the index gets created.
 *
 * @param type   The mapping type
 * @param source The mapping source
 */
@SuppressWarnings("unchecked")
public CreateIndexRequest mapping(String type, Map source) {
    if (mappings.containsKey(type)) {
        throw new IllegalStateException("mappings for type \"" + type + "\" were already defined");
    }
    // wrap it in a type map if its not
    if (source.size() != 1 || !source.containsKey(type)) {
        source = MapBuilder.<String, Object>newMapBuilder().put(type, source).map();
    }
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(source);
        return mapping(type, builder);
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
}
 
Example 3
Source File: PercolateRequest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Raw version of {@link #source(PercolateSourceBuilder)}
 */
@SuppressWarnings("unchecked")
public PercolateRequest source(Map document, XContentType contentType) throws ElasticsearchGenerationException {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(contentType);
        builder.map(document);
        return source(builder);
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + document + "]", e);
    }
}
 
Example 4
Source File: DetectorMappingRepositoryImpl.java    From adaptive-alerting with Apache License 2.0 5 votes vote down vote up
@Override
public MatchingDetectorsResponse findMatchingDetectorMappings(List<Map<String, String>> tagsList) {
    try {
        List<BytesReference> refList = new ArrayList<>();
        for (Map<String, String> tags : tagsList) {
            XContentBuilder xContent = XContentFactory.jsonBuilder();
            xContent.map(tags);
            refList.add(BytesReference.bytes(xContent));
        }
        PercolateQueryBuilder percolateQuery = new PercolateQueryBuilder(PercolatorDetectorMapping.QUERY_KEYWORD,
                refList, XContentType.JSON);
        val termQuery = QueryBuilders.termQuery("aa_enabled", true);

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.filter(percolateQuery);
        boolQueryBuilder.filter(termQuery);

        SearchSourceBuilder searchSourceBuilder = elasticsearchUtil.getSourceBuilder(boolQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(elasticSearchProperties.getConfig().getConnectionTimeout()));
        //FIXME setting default result set size to 500.
        // This is for returning detectors matching for set of metrics
        searchSourceBuilder.size(500);
        return getDetectorMappings(searchSourceBuilder, tagsList);
    } catch (IOException e) {
        log.error("Error ES lookup", e);
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: ClusterUpdateSettingsRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the persistent settings to be updated. They will get applied cross restarts
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public ClusterUpdateSettingsRequest persistentSettings(Map source) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(source);
        persistentSettings(Strings.toString(builder), builder.contentType());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    return this;
}
 
Example 6
Source File: PutIndexTemplateRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Adds mapping that will be added when the index gets created.
 *
 * @param type   The mapping type
 * @param source The mapping source
 */
public PutIndexTemplateRequest mapping(String type, Map<String, Object> source) {
    // wrap it in a type map if its not
    if (source.size() != 1 || !source.containsKey(type)) {
        source = MapBuilder.<String, Object>newMapBuilder().put(type, source).map();
    }
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(source);
        return mapping(type, builder);
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
}
 
Example 7
Source File: RestoreSnapshotRequest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Sets repository-specific restore settings
 * <p>
 * See repository documentation for more information.
 *
 * @param source repository-specific snapshot settings
 * @return this request
 */
public RestoreSnapshotRequest settings(Map<String, Object> source) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(source);
        settings(builder.string());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    return this;
}
 
Example 8
Source File: PutIndexTemplateRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the aliases that will be associated with the index when it gets created
 */
@SuppressWarnings("unchecked")
public PutIndexTemplateRequest aliases(Map source) {
    try {
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.map(source);
        return aliases(BytesReference.bytes(builder));
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
}
 
Example 9
Source File: GetIndexRequestRestListener.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private void writeMappings(ImmutableOpenMap<String, MappingMetadata> mappings, XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject(Fields.MAPPINGS);
    if (mappings != null) {
        for (ObjectObjectCursor<String, MappingMetadata> typeEntry : mappings) {
            builder.field(typeEntry.key);
            builder.map(typeEntry.value.sourceAsMap());
        }
    }
    builder.endObject();
}
 
Example 10
Source File: UpdateSettingsRequest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the settings to be updated (either json/yaml/properties format)
 */
@SuppressWarnings("unchecked")
public UpdateSettingsRequest settings(Map source) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(source);
        settings(builder.string());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    return this;
}
 
Example 11
Source File: PutMappingRequest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * The mapping source definition.
 */
@SuppressWarnings("unchecked")
public PutMappingRequest source(Map mappingSource) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(mappingSource);
        return source(builder.string());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + mappingSource + "]", e);
    }
}
 
Example 12
Source File: CountRequest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * The source to execute in the form of a map.
 */
@SuppressWarnings("unchecked")
public CountRequest source(Map querySource) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(Requests.CONTENT_TYPE);
        builder.map(querySource);
        return source(builder);
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + querySource + "]", e);
    }
}
 
Example 13
Source File: ExistsRequest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * The source to execute in the form of a map.
 */
public ExistsRequest source(Map querySource) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(Requests.CONTENT_TYPE);
        builder.map(querySource);
        return source(builder);
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + querySource + "]", e);
    }
}
 
Example 14
Source File: RootObjectMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected void doXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
    if (dynamicDateTimeFormatters != Defaults.DYNAMIC_DATE_TIME_FORMATTERS) {
        if (dynamicDateTimeFormatters.length > 0) {
            builder.startArray("dynamic_date_formats");
            for (FormatDateTimeFormatter dateTimeFormatter : dynamicDateTimeFormatters) {
                builder.value(dateTimeFormatter.format());
            }
            builder.endArray();
        }
    }

    if (dynamicTemplates != null && dynamicTemplates.length > 0) {
        builder.startArray("dynamic_templates");
        for (DynamicTemplate dynamicTemplate : dynamicTemplates) {
            builder.startObject();
            builder.field(dynamicTemplate.name());
            builder.map(dynamicTemplate.conf());
            builder.endObject();
        }
        builder.endArray();
    }

    if (dateDetection != Defaults.DATE_DETECTION) {
        builder.field("date_detection", dateDetection);
    }
    if (numericDetection != Defaults.NUMERIC_DETECTION) {
        builder.field("numeric_detection", numericDetection);
    }
}
 
Example 15
Source File: ClusterUpdateSettingsRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the transient settings to be updated. They will not survive a full cluster restart
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public ClusterUpdateSettingsRequest transientSettings(Map source) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(source);
        transientSettings(Strings.toString(builder), builder.contentType());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    return this;
}
 
Example 16
Source File: RestoreSnapshotRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets settings that should be added/changed in all restored indices
 */
public RestoreSnapshotRequest indexSettings(Map<String, Object> source) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(source);
        indexSettings(Strings.toString(builder), builder.contentType());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    return this;
}
 
Example 17
Source File: ObjectPath.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link XContentBuilder} from the xContent object underlying this {@link ObjectPath}.
 * This only works for {@link ObjectPath} instances created from an xContent object, not from nested
 * substructures. We throw an {@link UnsupportedOperationException} in those cases.
 */
@SuppressWarnings("unchecked")
public XContentBuilder toXContentBuilder(XContent xContent) throws IOException {
    XContentBuilder builder = XContentBuilder.builder(xContent);
    if (this.object instanceof Map) {
        builder.map((Map<String, Object>) this.object);
    } else {
        throw new UnsupportedOperationException("Only ObjectPath created from a map supported.");
    }
    return builder;
}
 
Example 18
Source File: AggregationBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Sets a raw (xcontent / json) sub addAggregation.
 */
public B subAggregation(Map<String, Object> aggs) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(Requests.CONTENT_TYPE);
        builder.map(aggs);
        return subAggregation(builder);
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + aggs + "]", e);
    }
}
 
Example 19
Source File: PutRepositoryRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the repository settings.
 *
 * @param source repository settings
 * @return this request
 */
public PutRepositoryRequest settings(Map<String, Object> source) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(source);
        settings(Strings.toString(builder), builder.contentType());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    return this;
}
 
Example 20
Source File: TransportShardUpsertAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Prepares an update request by converting it into an index request.
 * <p/>
 * TODO: detect a NOOP and return an update response if true
 */
@SuppressWarnings("unchecked")
private SourceAndVersion prepareUpdate(DocTableInfo tableInfo,
                                       ShardUpsertRequest request,
                                       ShardUpsertRequest.Item item,
                                       IndexShard indexShard) throws ElasticsearchException {
    final GetResult getResult = indexShard.getService().get(request.type(), item.id(),
            new String[]{RoutingFieldMapper.NAME, ParentFieldMapper.NAME, TTLFieldMapper.NAME},
            true, Versions.MATCH_ANY, VersionType.INTERNAL, FetchSourceContext.FETCH_SOURCE, false);

    if (!getResult.isExists()) {
        throw new DocumentMissingException(new ShardId(request.index(), request.shardId().id()), request.type(), item.id());
    }

    if (getResult.internalSourceRef() == null) {
        // no source, we can't do nothing, through a failure...
        throw new DocumentSourceMissingException(new ShardId(request.index(), request.shardId().id()), request.type(), item.id());
    }

    if (item.version() != Versions.MATCH_ANY && item.version() != getResult.getVersion()) {
        throw new VersionConflictEngineException(
                indexShard.shardId(), Constants.DEFAULT_MAPPING_TYPE, item.id(), getResult.getVersion(), item.version());
    }

    Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(getResult.internalSourceRef(), true);
    final Map<String, Object> updatedSourceAsMap;
    final XContentType updateSourceContentType = sourceAndContent.v1();

    updatedSourceAsMap = sourceAndContent.v2();

    SymbolToFieldExtractorContext ctx = new SymbolToFieldExtractorContext(functions, item.insertValues());

    Map<String, Object> pathsToUpdate = new LinkedHashMap<>();
    Map<String, Object> updatedGeneratedColumns = new LinkedHashMap<>();
    for (int i = 0; i < request.updateColumns().length; i++) {
        /**
         * NOTE: mapping isn't applied. So if an Insert was done using the ES Rest Endpoint
         * the data might be returned in the wrong format (date as string instead of long)
         */
        String columnPath = request.updateColumns()[i];
        Object value = SYMBOL_TO_FIELD_EXTRACTOR.convert(item.updateAssignments()[i], ctx).apply(getResult);
        ReferenceInfo referenceInfo = tableInfo.getReferenceInfo(ColumnIdent.fromPath(columnPath));
        if (referenceInfo instanceof GeneratedReferenceInfo) {
            updatedGeneratedColumns.put(columnPath, value);

        } else {
            pathsToUpdate.put(columnPath, value);
        }
    }

    processGeneratedColumns(tableInfo, pathsToUpdate, updatedGeneratedColumns, request.validateGeneratedColumns(), getResult);

    updateSourceByPaths(updatedSourceAsMap, pathsToUpdate);

    try {
        XContentBuilder builder = XContentFactory.contentBuilder(updateSourceContentType);
        builder.map(updatedSourceAsMap);
        return new SourceAndVersion(builder.bytes(), getResult.getVersion());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + updatedSourceAsMap + "]", e);
    }
}