Search in sources :

Example 46 with XContentType

use of org.elasticsearch.common.xcontent.XContentType in project crate by crate.

the class ColumnPolicyIntegrationTest method testAlterColumnPolicyOnPartitionedTableWithExistingPartitions.

@Test
public void testAlterColumnPolicyOnPartitionedTableWithExistingPartitions() throws Exception {
    execute("create table dynamic_table (" + "  id integer, " + "  score double" + ") partitioned by (score) with (number_of_replicas=0, column_policy='strict')");
    ensureYellow();
    // create at least 2 partitions to test real multi partition logic (1 partition would behave similar to 1 normal table)
    execute("insert into dynamic_table (id, score) values (1, 10)");
    execute("insert into dynamic_table (id, score) values (1, 20)");
    execute("refresh table dynamic_table");
    ensureYellow();
    execute("alter table dynamic_table set (column_policy = 'dynamic')");
    waitNoPendingTasksOnAll();
    // After changing the column_policy it's possible to add new columns to existing and new
    // partitions
    execute("insert into dynamic_table (id, score, comment) values (2, 10, 'this is a new column')");
    execute("insert into dynamic_table (id, score, new_comment) values (2, 5, 'this is a new column on a new partition')");
    execute("refresh table dynamic_table");
    ensureYellow();
    GetIndexTemplatesResponse response = client().admin().indices().prepareGetTemplates(PartitionName.templateName(null, "dynamic_table")).execute().actionGet();
    assertThat(response.getIndexTemplates().size(), is(1));
    IndexTemplateMetaData template = response.getIndexTemplates().get(0);
    CompressedXContent mappingStr = template.mappings().get(Constants.DEFAULT_MAPPING_TYPE);
    assertThat(mappingStr, is(notNullValue()));
    Tuple<XContentType, Map<String, Object>> typeAndMap = XContentHelper.convertToMap(mappingStr.compressedReference(), false);
    @SuppressWarnings("unchecked") Map<String, Object> mapping = (Map<String, Object>) typeAndMap.v2().get(Constants.DEFAULT_MAPPING_TYPE);
    assertThat(String.valueOf(mapping.get("dynamic")), is(String.valueOf(ColumnPolicy.DYNAMIC.mappingValue())));
    execute("insert into dynamic_table (id, score, new_col) values (?, ?, ?)", new Object[] { 6, 3, "hello" });
    execute("refresh table dynamic_table");
    ensureYellow();
    MappingMetaData partitionMetaData = clusterService().state().metaData().indices().get(new PartitionName("dynamic_table", Arrays.asList(new BytesRef("10.0"))).asIndexName()).getMappings().get(Constants.DEFAULT_MAPPING_TYPE);
    assertThat(String.valueOf(partitionMetaData.getSourceAsMap().get("dynamic")), is(String.valueOf(ColumnPolicy.DYNAMIC.mappingValue())));
    partitionMetaData = clusterService().state().metaData().indices().get(new PartitionName("dynamic_table", Arrays.asList(new BytesRef("5.0"))).asIndexName()).getMappings().get(Constants.DEFAULT_MAPPING_TYPE);
    assertThat(String.valueOf(partitionMetaData.getSourceAsMap().get("dynamic")), is(String.valueOf(ColumnPolicy.DYNAMIC.mappingValue())));
    partitionMetaData = clusterService().state().metaData().indices().get(new PartitionName("dynamic_table", Arrays.asList(new BytesRef("3.0"))).asIndexName()).getMappings().get(Constants.DEFAULT_MAPPING_TYPE);
    assertThat(String.valueOf(partitionMetaData.getSourceAsMap().get("dynamic")), is(String.valueOf(ColumnPolicy.DYNAMIC.mappingValue())));
}
Also used : MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) PartitionName(io.crate.metadata.PartitionName) XContentType(org.elasticsearch.common.xcontent.XContentType) GetIndexTemplatesResponse(org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse) IndexTemplateMetaData(org.elasticsearch.cluster.metadata.IndexTemplateMetaData) CompressedXContent(org.elasticsearch.common.compress.CompressedXContent) HashMap(java.util.HashMap) Map(java.util.Map) BytesRef(org.apache.lucene.util.BytesRef) Test(org.junit.Test)

Example 47 with XContentType

use of org.elasticsearch.common.xcontent.XContentType in project elasticsearch by elastic.

the class TransportUpdateAction method shardOperation.

protected void shardOperation(final UpdateRequest request, final ActionListener<UpdateResponse> listener, final int retryCount) {
    final ShardId shardId = request.getShardId();
    final IndexService indexService = indicesService.indexServiceSafe(shardId.getIndex());
    final IndexShard indexShard = indexService.getShard(shardId.getId());
    final UpdateHelper.Result result = updateHelper.prepare(request, indexShard, threadPool::absoluteTimeInMillis);
    switch(result.getResponseResult()) {
        case CREATED:
            IndexRequest upsertRequest = result.action();
            // we fetch it from the index request so we don't generate the bytes twice, its already done in the index request
            final BytesReference upsertSourceBytes = upsertRequest.source();
            bulkAction.execute(toSingleItemBulkRequest(upsertRequest), wrapBulkResponse(ActionListener.<IndexResponse>wrap(response -> {
                UpdateResponse update = new UpdateResponse(response.getShardInfo(), response.getShardId(), response.getType(), response.getId(), response.getSeqNo(), response.getVersion(), response.getResult());
                if ((request.fetchSource() != null && request.fetchSource().fetchSource()) || (request.fields() != null && request.fields().length > 0)) {
                    Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(upsertSourceBytes, true, upsertRequest.getContentType());
                    update.setGetResult(updateHelper.extractGetResult(request, request.concreteIndex(), response.getVersion(), sourceAndContent.v2(), sourceAndContent.v1(), upsertSourceBytes));
                } else {
                    update.setGetResult(null);
                }
                update.setForcedRefresh(response.forcedRefresh());
                listener.onResponse(update);
            }, exception -> handleUpdateFailureWithRetry(listener, request, exception, retryCount))));
            break;
        case UPDATED:
            IndexRequest indexRequest = result.action();
            // we fetch it from the index request so we don't generate the bytes twice, its already done in the index request
            final BytesReference indexSourceBytes = indexRequest.source();
            bulkAction.execute(toSingleItemBulkRequest(indexRequest), wrapBulkResponse(ActionListener.<IndexResponse>wrap(response -> {
                UpdateResponse update = new UpdateResponse(response.getShardInfo(), response.getShardId(), response.getType(), response.getId(), response.getSeqNo(), response.getVersion(), response.getResult());
                update.setGetResult(updateHelper.extractGetResult(request, request.concreteIndex(), response.getVersion(), result.updatedSourceAsMap(), result.updateSourceContentType(), indexSourceBytes));
                update.setForcedRefresh(response.forcedRefresh());
                listener.onResponse(update);
            }, exception -> handleUpdateFailureWithRetry(listener, request, exception, retryCount))));
            break;
        case DELETED:
            DeleteRequest deleteRequest = result.action();
            bulkAction.execute(toSingleItemBulkRequest(deleteRequest), wrapBulkResponse(ActionListener.<DeleteResponse>wrap(response -> {
                UpdateResponse update = new UpdateResponse(response.getShardInfo(), response.getShardId(), response.getType(), response.getId(), response.getSeqNo(), response.getVersion(), response.getResult());
                update.setGetResult(updateHelper.extractGetResult(request, request.concreteIndex(), response.getVersion(), result.updatedSourceAsMap(), result.updateSourceContentType(), null));
                update.setForcedRefresh(response.forcedRefresh());
                listener.onResponse(update);
            }, exception -> handleUpdateFailureWithRetry(listener, request, exception, retryCount))));
            break;
        case NOOP:
            UpdateResponse update = result.action();
            IndexService indexServiceOrNull = indicesService.indexService(shardId.getIndex());
            if (indexServiceOrNull != null) {
                IndexShard shard = indexService.getShardOrNull(shardId.getId());
                if (shard != null) {
                    shard.noopUpdate(request.type());
                }
            }
            listener.onResponse(update);
            break;
        default:
            throw new IllegalStateException("Illegal result " + result.getResponseResult());
    }
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IndexRequest(org.elasticsearch.action.index.IndexRequest) CreateIndexRequest(org.elasticsearch.action.admin.indices.create.CreateIndexRequest) ShardId(org.elasticsearch.index.shard.ShardId) XContentType(org.elasticsearch.common.xcontent.XContentType) DeleteResponse(org.elasticsearch.action.delete.DeleteResponse) IndexResponse(org.elasticsearch.action.index.IndexResponse) CreateIndexResponse(org.elasticsearch.action.admin.indices.create.CreateIndexResponse) Map(java.util.Map) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest)

Example 48 with XContentType

use of org.elasticsearch.common.xcontent.XContentType in project elasticsearch by elastic.

the class UpdateHelper method prepare.

/**
     * Prepares an update request by converting it into an index or delete request or an update response (no action).
     */
@SuppressWarnings("unchecked")
protected Result prepare(ShardId shardId, UpdateRequest request, final GetResult getResult, LongSupplier nowInMillis) {
    if (!getResult.isExists()) {
        if (request.upsertRequest() == null && !request.docAsUpsert()) {
            throw new DocumentMissingException(shardId, request.type(), request.id());
        }
        IndexRequest indexRequest = request.docAsUpsert() ? request.doc() : request.upsertRequest();
        if (request.scriptedUpsert() && request.script() != null) {
            // Run the script to perform the create logic
            IndexRequest upsert = request.upsertRequest();
            Map<String, Object> upsertDoc = upsert.sourceAsMap();
            Map<String, Object> ctx = new HashMap<>(2);
            // Tell the script that this is a create and not an update
            ctx.put("op", "create");
            ctx.put("_source", upsertDoc);
            ctx.put("_now", nowInMillis.getAsLong());
            ctx = executeScript(request.script, ctx);
            //Allow the script to abort the create by setting "op" to "none"
            String scriptOpChoice = (String) ctx.get("op");
            // (the default) or "none", meaning abort upsert
            if (!"create".equals(scriptOpChoice)) {
                if (!"none".equals(scriptOpChoice)) {
                    logger.warn("Used upsert operation [{}] for script [{}], doing nothing...", scriptOpChoice, request.script.getIdOrCode());
                }
                UpdateResponse update = new UpdateResponse(shardId, getResult.getType(), getResult.getId(), getResult.getVersion(), DocWriteResponse.Result.NOOP);
                update.setGetResult(getResult);
                return new Result(update, DocWriteResponse.Result.NOOP, upsertDoc, XContentType.JSON);
            }
            indexRequest.source((Map) ctx.get("_source"));
        }
        indexRequest.index(request.index()).type(request.type()).id(request.id()).create(true).setRefreshPolicy(request.getRefreshPolicy()).routing(request.routing()).parent(request.parent()).waitForActiveShards(request.waitForActiveShards());
        if (request.versionType() != VersionType.INTERNAL) {
            // in all but the internal versioning mode, we want to create the new document using the given version.
            indexRequest.version(request.version()).versionType(request.versionType());
        }
        return new Result(indexRequest, DocWriteResponse.Result.CREATED, null, null);
    }
    long updateVersion = getResult.getVersion();
    if (request.versionType() != VersionType.INTERNAL) {
        assert request.versionType() == VersionType.FORCE;
        // remember, match_any is excluded by the conflict test
        updateVersion = request.version();
    }
    if (getResult.internalSourceRef() == null) {
        // no source, we can't do nothing, through a failure...
        throw new DocumentSourceMissingException(shardId, request.type(), request.id());
    }
    Tuple<XContentType, Map<String, Object>> sourceAndContent = XContentHelper.convertToMap(getResult.internalSourceRef(), true);
    String operation = null;
    final Map<String, Object> updatedSourceAsMap;
    final XContentType updateSourceContentType = sourceAndContent.v1();
    String routing = getResult.getFields().containsKey(RoutingFieldMapper.NAME) ? getResult.field(RoutingFieldMapper.NAME).getValue().toString() : null;
    String parent = getResult.getFields().containsKey(ParentFieldMapper.NAME) ? getResult.field(ParentFieldMapper.NAME).getValue().toString() : null;
    if (request.script() == null && request.doc() != null) {
        IndexRequest indexRequest = request.doc();
        updatedSourceAsMap = sourceAndContent.v2();
        if (indexRequest.routing() != null) {
            routing = indexRequest.routing();
        }
        if (indexRequest.parent() != null) {
            parent = indexRequest.parent();
        }
        boolean noop = !XContentHelper.update(updatedSourceAsMap, indexRequest.sourceAsMap(), request.detectNoop());
        // cases where users repopulating multi-fields or adding synonyms, etc.
        if (request.detectNoop() && noop) {
            operation = "none";
        }
    } else {
        Map<String, Object> ctx = new HashMap<>(16);
        ctx.put("_index", getResult.getIndex());
        ctx.put("_type", getResult.getType());
        ctx.put("_id", getResult.getId());
        ctx.put("_version", getResult.getVersion());
        ctx.put("_routing", routing);
        ctx.put("_parent", parent);
        ctx.put("_source", sourceAndContent.v2());
        ctx.put("_now", nowInMillis.getAsLong());
        ctx = executeScript(request.script, ctx);
        operation = (String) ctx.get("op");
        updatedSourceAsMap = (Map<String, Object>) ctx.get("_source");
    }
    if (operation == null || "index".equals(operation)) {
        final IndexRequest indexRequest = Requests.indexRequest(request.index()).type(request.type()).id(request.id()).routing(routing).parent(parent).source(updatedSourceAsMap, updateSourceContentType).version(updateVersion).versionType(request.versionType()).waitForActiveShards(request.waitForActiveShards()).setRefreshPolicy(request.getRefreshPolicy());
        return new Result(indexRequest, DocWriteResponse.Result.UPDATED, updatedSourceAsMap, updateSourceContentType);
    } else if ("delete".equals(operation)) {
        DeleteRequest deleteRequest = Requests.deleteRequest(request.index()).type(request.type()).id(request.id()).routing(routing).parent(parent).version(updateVersion).versionType(request.versionType()).waitForActiveShards(request.waitForActiveShards()).setRefreshPolicy(request.getRefreshPolicy());
        return new Result(deleteRequest, DocWriteResponse.Result.DELETED, updatedSourceAsMap, updateSourceContentType);
    } else if ("none".equals(operation)) {
        UpdateResponse update = new UpdateResponse(shardId, getResult.getType(), getResult.getId(), getResult.getVersion(), DocWriteResponse.Result.NOOP);
        update.setGetResult(extractGetResult(request, request.index(), getResult.getVersion(), updatedSourceAsMap, updateSourceContentType, getResult.internalSourceRef()));
        return new Result(update, DocWriteResponse.Result.NOOP, updatedSourceAsMap, updateSourceContentType);
    } else {
        logger.warn("Used update operation [{}] for script [{}], doing nothing...", operation, request.script.getIdOrCode());
        UpdateResponse update = new UpdateResponse(shardId, getResult.getType(), getResult.getId(), getResult.getVersion(), DocWriteResponse.Result.NOOP);
        return new Result(update, DocWriteResponse.Result.NOOP, updatedSourceAsMap, updateSourceContentType);
    }
}
Also used : DocumentSourceMissingException(org.elasticsearch.index.engine.DocumentSourceMissingException) HashMap(java.util.HashMap) IndexRequest(org.elasticsearch.action.index.IndexRequest) GetResult(org.elasticsearch.index.get.GetResult) XContentType(org.elasticsearch.common.xcontent.XContentType) DocumentMissingException(org.elasticsearch.index.engine.DocumentMissingException) HashMap(java.util.HashMap) Map(java.util.Map) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest)

Example 49 with XContentType

use of org.elasticsearch.common.xcontent.XContentType in project elasticsearch by elastic.

the class UpdateRequest method toXContent.

@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject();
    if (docAsUpsert) {
        builder.field("doc_as_upsert", docAsUpsert);
    }
    if (doc != null) {
        XContentType xContentType = doc.getContentType();
        try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY, doc.source(), xContentType)) {
            builder.field("doc");
            builder.copyCurrentStructure(parser);
        }
    }
    if (script != null) {
        builder.field("script", script);
    }
    if (upsertRequest != null) {
        XContentType xContentType = upsertRequest.getContentType();
        try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY, upsertRequest.source(), xContentType)) {
            builder.field("upsert");
            builder.copyCurrentStructure(parser);
        }
    }
    if (scriptedUpsert) {
        builder.field("scripted_upsert", scriptedUpsert);
    }
    if (detectNoop == false) {
        builder.field("detect_noop", detectNoop);
    }
    if (fields != null) {
        builder.array("fields", fields);
    }
    if (fetchSourceContext != null) {
        builder.field("_source", fetchSourceContext);
    }
    builder.endObject();
    return builder;
}
Also used : XContentType(org.elasticsearch.common.xcontent.XContentType) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 50 with XContentType

use of org.elasticsearch.common.xcontent.XContentType in project elasticsearch by elastic.

the class AbstractRestChannel method newBuilder.

/**
     * Creates a new {@link XContentBuilder} for a response to be sent using this channel. The builder's type is determined by the following
     * logic. If the request has a format parameter that will be used to attempt to map to an {@link XContentType}. If there is no format
     * parameter, the HTTP Accept header is checked to see if it can be matched to a {@link XContentType}. If this first attempt to map
     * fails, the request content type will be used if the value is not {@code null}; if the value is {@code null} the output format falls
     * back to JSON.
     */
@Override
public XContentBuilder newBuilder(@Nullable XContentType requestContentType, boolean useFiltering) throws IOException {
    // try to determine the response content type from the media type or the format query string parameter, with the format parameter
    // taking precedence over the Accept header
    XContentType responseContentType = XContentType.fromMediaTypeOrFormat(format);
    if (responseContentType == null) {
        if (requestContentType != null) {
            // if there was a parsed content-type for the incoming request use that since no format was specified using the query
            // string parameter or the HTTP Accept header
            responseContentType = requestContentType;
        } else {
            // default to JSON output when all else fails
            responseContentType = XContentType.JSON;
        }
    }
    Set<String> includes = Collections.emptySet();
    Set<String> excludes = Collections.emptySet();
    if (useFiltering) {
        Set<String> filters = Strings.splitStringByCommaToSet(filterPath);
        includes = filters.stream().filter(INCLUDE_FILTER).collect(toSet());
        excludes = filters.stream().filter(EXCLUDE_FILTER).map(f -> f.substring(1)).collect(toSet());
    }
    XContentBuilder builder = new XContentBuilder(XContentFactory.xContent(responseContentType), bytesOutput(), includes, excludes);
    if (pretty) {
        builder.prettyPrint().lfAtEnd();
    }
    builder.humanReadable(human);
    return builder;
}
Also used : XContentType(org.elasticsearch.common.xcontent.XContentType) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Aggregations

XContentType (org.elasticsearch.common.xcontent.XContentType)82 BytesReference (org.elasticsearch.common.bytes.BytesReference)48 XContentParser (org.elasticsearch.common.xcontent.XContentParser)42 Map (java.util.Map)19 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)19 HashMap (java.util.HashMap)18 IndexRequest (org.elasticsearch.action.index.IndexRequest)11 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)10 IOException (java.io.IOException)9 BytesRef (org.apache.lucene.util.BytesRef)8 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)8 Collections.emptyMap (java.util.Collections.emptyMap)6 ElasticsearchException (org.elasticsearch.ElasticsearchException)6 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)6 UpdateRequest (org.elasticsearch.action.update.UpdateRequest)6 Collections.singletonMap (java.util.Collections.singletonMap)5 HttpEntity (org.apache.http.HttpEntity)5 ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)5 GetRequest (org.elasticsearch.action.get.GetRequest)5 WriteRequest (org.elasticsearch.action.support.WriteRequest)5