Java Code Examples for org.elasticsearch.common.xcontent.XContentFactory#contentBuilder()

The following examples show how to use org.elasticsearch.common.xcontent.XContentFactory#contentBuilder() . 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: CompressedXContent.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Create a {@link CompressedXContent} out of a {@link ToXContent} instance.
 */
public CompressedXContent(ToXContent xcontent, XContentType type, ToXContent.Params params) throws IOException {
    BytesStreamOutput bStream = new BytesStreamOutput();
    OutputStream compressedStream = CompressorFactory.COMPRESSOR.streamOutput(bStream);
    CRC32 crc32 = new CRC32();
    try (OutputStream checkedStream = new CheckedOutputStream(compressedStream, crc32)) {
        try (XContentBuilder builder = XContentFactory.contentBuilder(type, checkedStream)) {
            builder.startObject();
            xcontent.toXContent(builder, params);
            builder.endObject();
        }
    }
    this.bytes = BytesReference.toBytes(bStream.bytes());
    this.crc32 = (int) crc32.getValue();
    assertConsistent();
}
 
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: SearchQueryServiceImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private void logProfileResults(final SearchResponse searchResponse) {
  for (Entry<String, List<ProfileShardResult>> entry : searchResponse.getProfileResults().entrySet()) {
    for (ProfileShardResult profileShardResult : entry.getValue()) {
      try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.startObject();
        profileShardResult.toXContent(builder, ToXContent.EMPTY_PARAMS);
        builder.endObject();
        log.info("Elasticsearch profile for {} is: {}", entry.getKey(), builder.string());
      }
      catch (IOException e) {
        log.error("Error writing elasticsearch profile result", e);
      }
    }
  }
}
 
Example 4
Source File: ESTestCase.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Randomly shuffles the fields inside objects parsed using the {@link XContentParser} passed in.
 * Recursively goes through inner objects and also shuffles them. Exceptions for this
 * recursive shuffling behavior can be made by passing in the names of fields which
 * internally should stay untouched.
 */
public static XContentBuilder shuffleXContent(XContentParser parser, boolean prettyPrint, String... exceptFieldNames)
        throws IOException {
    XContentBuilder xContentBuilder = XContentFactory.contentBuilder(parser.contentType());
    if (prettyPrint) {
        xContentBuilder.prettyPrint();
    }
    Token token = parser.currentToken() == null ? parser.nextToken() : parser.currentToken();
    if (token == Token.START_ARRAY) {
        List<Object> shuffledList = shuffleList(parser.listOrderedMap(), new HashSet<>(Arrays.asList(exceptFieldNames)));
        return xContentBuilder.value(shuffledList);
    }
    //we need a sorted map for reproducibility, as we are going to shuffle its keys and write XContent back
    Map<String, Object> shuffledMap = shuffleMap((LinkedHashMap<String, Object>)parser.mapOrdered(),
        new HashSet<>(Arrays.asList(exceptFieldNames)));
    return xContentBuilder.map(shuffledMap);
}
 
Example 5
Source File: RandomObjects.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a random source in a given XContentType containing a random number of fields, objects and array, with maximum depth 5.
 * The minimum number of fields per object is provided as an argument.
 *
 * @param random Random generator
 */
public static BytesReference randomSource(Random random, XContentType xContentType, int minNumFields) {
    try (XContentBuilder builder = XContentFactory.contentBuilder(xContentType)) {
        builder.startObject();
        addFields(random, builder, minNumFields, 0);
        builder.endObject();
        return BytesReference.bytes(builder);
    } catch(IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: CreateIndexRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * The settings to create the index with (either json/yaml/properties format)
 */
@SuppressWarnings("unchecked")
public CreateIndexRequest settings(Map source) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(source);
        settings(Strings.toString(builder), XContentType.JSON);
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    return this;
}
 
Example 7
Source File: CreateSnapshotRequest.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Sets repository-specific snapshot settings.
 * <p>
 * See repository documentation for more information.
 *
 * @param source repository-specific snapshot settings
 * @return this request
 */
public CreateSnapshotRequest 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: 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 9
Source File: SettingsContentBuilder.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
XContentBuilder createSettings(IndexSettings indexSettings) {
  try (XContentBuilder contentBuilder = XContentFactory.contentBuilder(xContentType)) {
    createSettings(indexSettings, contentBuilder);
    return contentBuilder;
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example 10
Source File: UpdateSettingsRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the settings to be updated (either json or yaml format)
 */
@SuppressWarnings("unchecked")
public UpdateSettingsRequest settings(Map 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 11
Source File: ClusterUpdateSettingsRequest.java    From Elasticsearch 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")
public ClusterUpdateSettingsRequest transientSettings(Map source) {
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(source);
        transientSettings(builder.string());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    return this;
}
 
Example 12
Source File: PutRepositoryRequest.java    From Elasticsearch 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(builder.string());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    return this;
}
 
Example 13
Source File: MappingContentBuilder.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
XContentBuilder createMapping(Mapping mapping) {
  try (XContentBuilder contentBuilder = XContentFactory.contentBuilder(xContentType)) {
    createMapping(mapping, contentBuilder);
    return contentBuilder;
  } catch (IOException e) {
    throw new UncheckedIOException(e);
  }
}
 
Example 14
Source File: AbstractRestActionTest.java    From elasticsearch-inout-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Convert an XContent object to a Java map
 * @param toXContent
 * @return
 * @throws IOException
 */
public static Map<String, Object> toMap(ToXContent toXContent) throws IOException {
    XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
    toXContent.toXContent(builder, ToXContent.EMPTY_PARAMS);
    return XContentFactory.xContent(XContentType.JSON).createParser(
            builder.string()).mapOrderedAndClose();
}
 
Example 15
Source File: RestoreSnapshotRequest.java    From crate 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(Strings.toString(builder), builder.contentType());
    } catch (IOException e) {
        throw new ElasticsearchGenerationException("Failed to generate [" + source + "]", e);
    }
    return this;
}
 
Example 16
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 17
Source File: CreateSnapshotRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Sets repository-specific snapshot settings.
 * <p>
 * See repository documentation for more information.
 *
 * @param source repository-specific snapshot settings
 * @return this request
 */
public CreateSnapshotRequest 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 18
Source File: Template.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected String parseInlineScript(XContentParser parser) throws IOException {
    if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
        contentType = parser.contentType();
        XContentBuilder builder = XContentFactory.contentBuilder(contentType);
        return builder.copyCurrentStructure(parser).bytes().toUtf8();
    } else {
        return parser.text();
    }
}
 
Example 19
Source File: MetaDataStateFormat.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
protected XContentBuilder newXContentBuilder(XContentType type, OutputStream stream ) throws IOException {
    return XContentFactory.contentBuilder(type, stream);
}
 
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);
    }
}