Java Code Examples for org.elasticsearch.common.xcontent.XContentBuilder

The following examples show how to use org.elasticsearch.common.xcontent.XContentBuilder. These examples are extracted from open source projects. 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
public XContentBuilder toXContent(XContentBuilder builder) throws IOException {
  if (this.indices != null) {
    builder.field(Fields.INDICES, this.indices);
  }
  else {
    builder.nullField(Fields.INDICES);
  }
  if (this.types != null) {
    builder.field(Fields.TYPES, this.types);
  }
  else {
    builder.nullField(Fields.TYPES);
  }
  builder.field(Fields.FIELD, this.field);
  return builder;
}
 
Example 2
Source Project: SkyEye   Source File: KafkaConsumerTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static XContentBuilder buildXContentBuilder(String line) throws IOException {

        LogDto logDto = new LogDto(line);
        return jsonBuilder()
                .startObject()
                .field("day", logDto.getDay())
                .field("time", logDto.getTime())
                .field("app", logDto.getApp())
                .field("host", logDto.getHost())
                .field("thread", logDto.getThread())
                .field("level", logDto.getLevel())
                .field("pack", logDto.getPack())
                .field("clazz", logDto.getClazz())
                .field("line", logDto.getLine())
                .field("message_smart", logDto.getMessage())
                .field("message_max", logDto.getMessage())
                .endObject();
    }
 
Example 3
Source Project: Elasticsearch   Source File: ProfileResult.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder = builder.startObject()
            .field(QUERY_TYPE.getPreferredName(), queryType)
            .field(LUCENE_DESCRIPTION.getPreferredName(), luceneDescription)
            .field(NODE_TIME.getPreferredName(), String.format(Locale.US, "%.10gms", (double)(getTime() / 1000000.0)))
            .field(BREAKDOWN.getPreferredName(), timings);

    if (!children.isEmpty()) {
        builder = builder.startArray(CHILDREN.getPreferredName());
        for (ProfileResult child : children) {
            builder = child.toXContent(builder, params);
        }
        builder = builder.endArray();
    }

    builder = builder.endObject();
    return builder;
}
 
Example 4
protected static JsonObject readResponse(ToXContent toXContent) {
    try {
        final XContentBuilder builder = XContentFactory.jsonBuilder();
        if (toXContent.isFragment()) {
            builder.startObject();
            toXContent.toXContent(builder, SearchResponse.EMPTY_PARAMS);
            builder.endObject();
        } else {
            toXContent.toXContent(builder, SearchResponse.EMPTY_PARAMS);
        }

        return new JsonObject(builder.string());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject();
    builder.field(NAME.getPreferredName(), name);
    builder.field(PARAMS.getPreferredName(), queryParams);
    builder.field(TEMPLATE_LANGUAGE.getPreferredName(), templateLanguage);
    if (templateAsString) {
        builder.field(TEMPLATE.getPreferredName(), template);
    } else {
        builder.field(TEMPLATE.getPreferredName());
        // it's ok to use NamedXContentRegistry.EMPTY because we don't really parse we copy the structure...
        XContentParser parser = XContentFactory.xContent(template).createParser(NamedXContentRegistry.EMPTY,
                LoggingDeprecationHandler.INSTANCE, template);
        builder.copyCurrentStructure(parser);
    }
    builder.endObject();
    return builder;
}
 
Example 6
@Override
public XContentBuilder toXContent(XContentBuilder builder,
        Params params) throws IOException {
    builder.startObject();
    builder.startArray("writes");
    for (ShardSearchIntoResponse r : this.responses) {
        r.toXContent(builder, params);
    }
    builder.endArray();
    builder.field("total", totalWrites);
    builder.field("succeeded", succeededWrites);
    builder.field("failed", failedWrites);
    buildBroadcastShardsHeader(builder, this);
    builder.endObject();
    return builder;
}
 
Example 7
Source Project: Elasticsearch   Source File: RangeQueryBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(RangeQueryParser.NAME);
    builder.startObject(name);
    builder.field("from", from);
    builder.field("to", to);
    if (timeZone != null) {
        builder.field("time_zone", timeZone);
    }
    if (format != null) {
        builder.field("format", format);
    }
    builder.field("include_lower", includeLower);
    builder.field("include_upper", includeUpper);
    if (boost != -1) {
        builder.field("boost", boost);
    }
    builder.endObject();
    if (queryName != null) {
        builder.field("_name", queryName);
    }
    builder.endObject();
}
 
Example 8
Source Project: Elasticsearch   Source File: InternalStats.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
    builder.field(Fields.COUNT, count);
    builder.field(Fields.MIN, count != 0 ? min : null);
    builder.field(Fields.MAX, count != 0 ? max : null);
    builder.field(Fields.AVG, count != 0 ? getAvg() : null);
    builder.field(Fields.SUM, count != 0 ? sum : null);
    if (count != 0 && !(valueFormatter instanceof ValueFormatter.Raw)) {
        builder.field(Fields.MIN_AS_STRING, valueFormatter.format(min));
        builder.field(Fields.MAX_AS_STRING, valueFormatter.format(max));
        builder.field(Fields.AVG_AS_STRING, valueFormatter.format(getAvg()));
        builder.field(Fields.SUM_AS_STRING, valueFormatter.format(sum));
    }
    otherStatsToXCotent(builder, params);
    return builder;
}
 
Example 9
Source Project: Elasticsearch   Source File: PointCollection.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * builds an array of coordinates to a {@link XContentBuilder}
 * 
 * @param builder builder to use 
 * @param closed repeat the first point at the end of the array if it's not already defines as last element of the array  
 * @return the builder
 */
protected XContentBuilder coordinatesToXcontent(XContentBuilder builder, boolean closed) throws IOException {
    builder.startArray();
    for(Coordinate point : points) {
        toXContent(builder, point);
    }
    if(closed) {
        Coordinate start = points.get(0);
        Coordinate end = points.get(points.size()-1);
        if(start.x != end.x || start.y != end.y) {
            toXContent(builder, points.get(0));
        }
    }
    builder.endArray();
    return builder;
}
 
Example 10
Source Project: Elasticsearch   Source File: SpanOrQueryBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
    if (clauses.isEmpty()) {
        throw new IllegalArgumentException("Must have at least one clause when building a spanOr query");
    }
    builder.startObject(SpanOrQueryParser.NAME);
    builder.startArray("clauses");
    for (SpanQueryBuilder clause : clauses) {
        clause.toXContent(builder, params);
    }
    builder.endArray();
    if (boost != -1) {
        builder.field("boost", boost);
    }
    if (queryName != null) {
        builder.field("_name", queryName);
    }
    builder.endObject();
}
 
Example 11
Source Project: Siamese   Source File: ESConnector.java    License: GNU General Public License v3.0 6 votes vote down vote up
public long getIndicesStats(String indexName) {
        IndicesStatsResponse indicesStatsResponse = client.admin().indices().prepareStats(indexName)
                .all()
                .execute().actionGet();

        XContentBuilder builder = null;
        try {
            builder = XContentFactory.jsonBuilder();
            builder.startObject();
            indicesStatsResponse.toXContent(builder, ToXContent.EMPTY_PARAMS);
            builder.endObject();
            String jsonResponse = builder.prettyPrint().string();

            JsonParser jsonParser = new JsonParser(); // from import com.google.gson.JsonParser;
            Long docCount = jsonParser.parse(jsonResponse)
                    .getAsJsonObject().get("_all")
                    .getAsJsonObject().get("primaries")
                    .getAsJsonObject().get("docs")
                    .getAsJsonObject().get("count").getAsLong();
//            System.out.println(docCount);
            return docCount;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }
 
Example 12
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, Client client) {
    DeleteIndexedScriptRequest deleteIndexedScriptRequest = new DeleteIndexedScriptRequest(getScriptLang(request), request.param("id"));
    deleteIndexedScriptRequest.version(request.paramAsLong("version", deleteIndexedScriptRequest.version()));
    deleteIndexedScriptRequest.versionType(VersionType.fromString(request.param("version_type"), deleteIndexedScriptRequest.versionType()));
    client.deleteIndexedScript(deleteIndexedScriptRequest, new RestBuilderListener<DeleteIndexedScriptResponse>(channel) {
        @Override
        public RestResponse buildResponse(DeleteIndexedScriptResponse result, XContentBuilder builder) throws Exception {
            builder.startObject()
                    .field(Fields.FOUND, result.isFound())
                    .field(Fields._INDEX, result.getIndex())
                    .field(Fields._TYPE, result.getType())
                    .field(Fields._ID, result.getId())
                    .field(Fields._VERSION, result.getVersion())
                    .endObject();
            RestStatus status = OK;
            if (!result.isFound()) {
                status = NOT_FOUND;
            }
            return new BytesRestResponse(status, builder);
        }
    });
}
 
Example 13
Source Project: Elasticsearch   Source File: MergeStats.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(Fields.MERGES);
    builder.field(Fields.CURRENT, current);
    builder.field(Fields.CURRENT_DOCS, currentNumDocs);
    builder.byteSizeField(Fields.CURRENT_SIZE_IN_BYTES, Fields.CURRENT_SIZE, currentSizeInBytes);
    builder.field(Fields.TOTAL, total);
    builder.timeValueField(Fields.TOTAL_TIME_IN_MILLIS, Fields.TOTAL_TIME, totalTimeInMillis);
    builder.field(Fields.TOTAL_DOCS, totalNumDocs);
    builder.byteSizeField(Fields.TOTAL_SIZE_IN_BYTES, Fields.TOTAL_SIZE, totalSizeInBytes);
    builder.timeValueField(Fields.TOTAL_STOPPED_TIME_IN_MILLIS, Fields.TOTAL_STOPPED_TIME, totalStoppedTimeInMillis);
    builder.timeValueField(Fields.TOTAL_THROTTLED_TIME_IN_MILLIS, Fields.TOTAL_THROTTLED_TIME, totalThrottledTimeInMillis);
    builder.byteSizeField(Fields.TOTAL_THROTTLE_BYTES_PER_SEC_IN_BYTES, Fields.TOTAL_THROTTLE_BYTES_PER_SEC, totalBytesPerSecAutoThrottle);
    builder.endObject();
    return builder;
}
 
Example 14
Source Project: Elasticsearch   Source File: TermVectorsResponse.java    License: Apache License 2.0 6 votes vote down vote up
private void buildFieldStatistics(XContentBuilder builder, Terms curTerms) throws IOException {
    long sumDocFreq = curTerms.getSumDocFreq();
    int docCount = curTerms.getDocCount();
    long sumTotalTermFrequencies = curTerms.getSumTotalTermFreq();
    if (docCount > 0) {
        assert ((sumDocFreq > 0)) : "docCount >= 0 but sumDocFreq ain't!";
        assert ((sumTotalTermFrequencies > 0)) : "docCount >= 0 but sumTotalTermFrequencies ain't!";
        builder.startObject(FieldStrings.FIELD_STATISTICS);
        builder.field(FieldStrings.SUM_DOC_FREQ, sumDocFreq);
        builder.field(FieldStrings.DOC_COUNT, docCount);
        builder.field(FieldStrings.SUM_TTF, sumTotalTermFrequencies);
        builder.endObject();
    } else if (docCount == -1) { // this should only be -1 if the field
        // statistics were not requested at all. In
        // this case all 3 values should be -1
        assert ((sumDocFreq == -1)) : "docCount was -1 but sumDocFreq ain't!";
        assert ((sumTotalTermFrequencies == -1)) : "docCount was -1 but sumTotalTermFrequencies ain't!";
    } else {
        throw new IllegalStateException(
                "Something is wrong with the field statistics of the term vector request: Values are " + "\n"
                        + FieldStrings.SUM_DOC_FREQ + " " + sumDocFreq + "\n" + FieldStrings.DOC_COUNT + " " + docCount + "\n"
                        + FieldStrings.SUM_TTF + " " + sumTotalTermFrequencies);
    }
}
 
Example 15
@Override
public final XContentBuilder internalXContent(XContentBuilder builder, Params params)
    throws IOException {
  builder.startObject();
  // todo add ParseField support to XContentBuilder
  if (fields != null) {
    builder.field(CommonFields.FIELDS.getPreferredName(), fields);
  }
  if (missing != null) {
    builder.field(CommonFields.MISSING.getPreferredName(), missing);
  }
  if (format != null) {
    builder.field(CommonFields.FORMAT.getPreferredName(), format);
  }
  if (valueType != null) {
    builder.field(CommonFields.VALUE_TYPE.getPreferredName(), valueType.getPreferredName());
  }
  doXContentBody(builder, params);
  builder.endObject();
  return builder;
}
 
Example 16
Source Project: Elasticsearch   Source File: PhraseSuggestionBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(type);
    innerToXContent(builder,params);
    builder.endObject();
    return builder;
}
 
Example 17
Source Project: Elasticsearch   Source File: ReplicationTask.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject();
    builder.field("phase", phase);
    builder.endObject();
    return builder;
}
 
Example 18
Source Project: Elasticsearch   Source File: LineStringBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject();
    builder.field(FIELD_TYPE, TYPE.shapename);
    builder.field(FIELD_COORDINATES);
    coordinatesToXcontent(builder, false);
    builder.endObject();
    return builder;
}
 
Example 19
protected static XContentBuilder convertToJson(RestChannel channel, ToXContent toxContent) {
	try {
		XContentBuilder builder = channel.newBuilder();
		toxContent.toXContent(builder, ToXContent.EMPTY_PARAMS);
		return builder;
	} catch (IOException e) {
		throw ExceptionsHelper.convertToElastic(e);
	}
}
 
Example 20
Source Project: elasticshell   Source File: PutMappingRequestBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected XContentBuilder toXContent(PutMappingRequest request, PutMappingResponse response, XContentBuilder builder) throws IOException {
    builder.startObject()
            .field(Fields.OK, true)
            .field(Fields.ACKNOWLEDGED, response.isAcknowledged());
    builder.endObject();
    return builder;
}
 
Example 21
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(NAME);
    printBoostAndQueryName(builder);
    builder.field(QUERY_NAME.getPreferredName(), query);
    builder.field(TYPE_NAME.getPreferredName(), type);
    builder.endObject();
}
 
Example 22
Source Project: james-project   Source File: NodeMappingFactoryAuthTest.java    License: Apache License 2.0 5 votes vote down vote up
private XContentBuilder getOtherMappingsSources() throws Exception {
    return jsonBuilder()
        .startObject()
            .startObject(NodeMappingFactory.PROPERTIES)
                .startObject(MESSAGE)
                    .field(NodeMappingFactory.TYPE, NodeMappingFactory.TEXT)
                    .field(NodeMappingFactory.INDEX, false)
                .endObject()
            .endObject()
        .endObject();
}
 
Example 23
private void createFieldMappingDate(String dateFormat, XContentBuilder contentBuilder)
    throws IOException {
  contentBuilder.field(TYPE, "date").field("format", dateFormat);
  // not-analyzed field for aggregation
  // note: the norms settings defaults to false for not_analyzed fields
  contentBuilder
      .startObject(FIELDS)
      .startObject(FIELD_NOT_ANALYZED)
      .field(TYPE, KEYWORD_TYPE)
      .field(INDEX, true)
      .endObject()
      .endObject();
}
 
Example 24
Source Project: Elasticsearch   Source File: SpanFirstQueryBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(SpanFirstQueryParser.NAME);
    builder.field("match");
    matchBuilder.toXContent(builder, params);
    builder.field("end", end);
    if (boost != -1) {
        builder.field("boost", boost);
    }
    if (queryName != null) {
        builder.field("_name", queryName);
    }
    builder.endObject();
}
 
Example 25
Source Project: elasticshell   Source File: SuggestRequestBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected SuggestRequest request() {
    SuggestRequest suggestRequest = super.request();
    try {
        XContentBuilder builder = XContentFactory.contentBuilder(Requests.CONTENT_TYPE);
        suggest.toXContent(builder, ToXContent.EMPTY_PARAMS);
        suggestRequest.suggest(builder.bytes());
    } catch (IOException e) {
        throw new ElasticSearchException("Unable to build suggestion request", e);
    }
    return suggestRequest;
}
 
Example 26
Source Project: crate   Source File: PublishClusterStateStats.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject("published_cluster_states");
    {
        builder.field("full_states", fullClusterStateReceivedCount);
        builder.field("incompatible_diffs", incompatibleClusterStateDiffReceivedCount);
        builder.field("compatible_diffs", compatibleClusterStateDiffReceivedCount);
    }
    builder.endObject();
    return builder;
}
 
Example 27
private void writeAliases(List<AliasMetadata> aliases, XContentBuilder builder, ToXContent.Params params) throws IOException {
    builder.startObject(Fields.ALIASES);
    if (aliases != null) {
        for (AliasMetadata alias : aliases) {
            AliasMetadata.Builder.toXContent(alias, builder, params);
        }
    }
    builder.endObject();
}
 
Example 28
Source Project: crate   Source File: SqlHttpHandler.java    License: Apache License 2.0 5 votes vote down vote up
private CompletableFuture<XContentBuilder> executeBulkRequest(Session session,
                                                              String stmt,
                                                              List<List<Object>> bulkArgs) {
    final long startTimeInNs = System.nanoTime();
    session.parse(UNNAMED, stmt, emptyList());
    final RestBulkRowCountReceiver.Result[] results = new RestBulkRowCountReceiver.Result[bulkArgs.size()];
    for (int i = 0; i < bulkArgs.size(); i++) {
        session.bind(UNNAMED, UNNAMED, bulkArgs.get(i), null);
        ResultReceiver resultReceiver = new RestBulkRowCountReceiver(results, i);
        session.execute(UNNAMED, 0, resultReceiver);
    }
    if (results.length > 0) {
        DescribeResult describeResult = session.describe('P', UNNAMED);
        if (describeResult.getFields() != null) {
            return CompletableFuture.failedFuture(new UnsupportedOperationException(
                        "Bulk operations for statements that return result sets is not supported"));
        }
    }
    return session.sync()
        .thenApply(ignored -> {
            try {
                return ResultToXContentBuilder.builder(JsonXContent.contentBuilder())
                    .cols(emptyList())
                    .duration(startTimeInNs)
                    .bulkRows(results)
                    .build();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
}
 
Example 29
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    XContentBuilder xContentBuilder = builder
        .startObject()
        .field(DETECTOR_ID_FIELD, detectorId)
        .field(PERIOD_START_FIELD, periodStart.toEpochMilli())
        .field(PERIOD_END_FIELD, periodEnd.toEpochMilli())
        .field(DETECTOR_FIELD, detector);
    return xContentBuilder.endObject();
}
 
Example 30
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    return builder.startObject()
            .field("total", total)
            .field("features", features)
            .field("featuresets", featuresets)
            .field("models", models)
            .endObject();
}